feat(watermark): serve the free-plan mark as a copy, so paying removes it from existing clips

Every file the pipeline and the clip editor write is now clean. On the free
plan the served file is a wm_<final> copy with the mark burned in
(main.mark_delivery, last step after captions; app._deliver for the editor
endpoints, decided from the caller's plan), and both twins go to R2. An
upgrade re-points the user's library at the clean twins from the Stripe
webhook (cloud.videos.unmark_user_library): no render, no source video,
and the dashboard chases the job result until no served URL carries wm_.

Before, the mark rode the reframe encode, so every derivative inherited it
and the upgrade modal's "upgrade to remove the watermark" was false for the
clips already made. The first cancellation for "clip quality" (29-sep) was a
user who paid 15 minutes after their first job and kept the mark on every
download and restyle.

- /videos guard refuses a marked job's clean deliverables (.marked dotfile),
  so the twin cannot be fetched by stripping the prefix off a URL; editor
  scratch files stay servable. Re-checked after an R2 restore.
- Walk-backs treat wm_ as the outermost layer; _canonical_clip_file globs it.
- Jobs from before this scheme (mark burned into the canonical) never get a
  second copy; a failed mark still serves under the wm_ name.
- Watermark notice once per job when the clips land on a free account, and
  before the first download if skipped; tracked with source=results|download.
  Upsell/banner/win-back copy now promise the instant removal.
This commit is contained in:
juancarlos.cavero 2026-10-01 09:35:53 +02:00
parent faff66de0b
commit cb37ae3aec
17 changed files with 930 additions and 86 deletions

View file

@ -183,6 +183,44 @@ otherwise process 45 minutes on a 20-minute reservation. `/api/status` and
the process response carry `partial`, and the results view says which part
of the video the clips came from, with the upsell for the rest.
### The free plan's watermark is a copy, and paying removes it (`watermarked.py`)
Every file the pipeline and the clip editor write is clean. On the free plan
the file that is *served* is `wm_<final>`, a copy of the final file with the
mark burned in (`main.mark_delivery`, the last step after captions; the
editor endpoints get it from `app._deliver`, decided from the caller's plan
right now, not from the job's flag, which a restart loses). Both twins live
on disk and in R2 (`cloud.videos._twins_to_archive`). Before 30-sep-2026 the
mark was burned into the canonical reframe, so every derivative inherited it
and the upgrade modal's "upgrade to remove the watermark" was false for the
clips already made: the first cancellation for "clip quality" was a user who
paid 15 minutes after their first job and kept the mark on every download.
- **Upgrade**: `cloud/billing._upsert_subscription` fires
`videos.unmark_user_library` on the free→live transition
(`became_live`). Per clip it checks the clean twin exists in R2, moves the
history row and the project state to it, deletes the marked object and
calls back into `app._unmark_local_job` so an open dashboard polls the
clean URL. No render, no source video. The dashboard chases the job
result after the plan flips (`App.jsx`, the `wm_` regex) and refreshes
the durable map.
- **Walk-backs**: `wm_` is the outermost layer; `_strip_burned_captions` /
`_strip_burned_hook` drop it first, `_canonical_clip_file` globs
`wm_*{clean}`.
- **`/videos` guard** (`app._media_guard`): a job rendered for the free plan
carries a `.marked` dotfile (`watermarked.MARKER_FILE`, written by
main.py, restored with the project, removed on unmark; `_deliver` marks
only jobs that carry it, so a job from before this scheme, whose canonical
has the mark burned in, never gets a second one);
while it exists the clean deliverables of that job are refused, so the
twin cannot be fetched by stripping the prefix off a URL. The editor's
`temp_*` scratch files and the caption sidecars stay servable.
- **Notice**: `WatermarkModal` shows once per job when the clips land on a
free account (`source=results`, 2.5 s after the grid) and, if skipped,
before the first download; tracked as `WatermarkNoticeSeen` /
`WatermarkNoticeUpgrade` with `source`. Its Upgrade opens the upsell
`TopUpModal`.
### Free sources past the balance never meet the wall (`app.free_overflow`)
Since 28-sep-2026 the wall above only shows to paid plans and to free
@ -601,8 +639,9 @@ checked by eye, audio identical):
- **Silero VAD on one CPU thread** (`vad_load_kwargs`): on CUDA it ran one
32 ms chunk per launch and was most of the transcription's wall time.
- **Blur at quarter size** (`ffmpeg_utils.blurred_backdrop`).
- **Watermark inside the reframe encode** (`reframe_v2.render(watermark=)`),
not a pass of its own (most jobs are free plan).
- **Watermark as a served copy** (`main.mark_delivery`, see the section
on the free plan's watermark): one NVENC pass per free clip, after
captions. It used to ride the reframe encode, which made it permanent.
- **hooked_ + subtitled_ from one ffmpeg** (`hooks.add_hook_to_video(also=)`):
the editor still needs both files (re-caption walks back to hooked_,
hook replace to the canonical), so nothing is skipped, only one decode.

130
app.py
View file

@ -31,6 +31,8 @@ from pydantic import BaseModel
from s3_uploader import upload_job_artifacts, list_all_clips, upload_actor_to_s3, list_actor_gallery, upload_video_to_gallery, list_video_gallery
import recut
import layout_ranges
import watermarked
import media_auth
load_dotenv()
@ -683,10 +685,13 @@ def _canonical_clip_file(output_dir, base_name, index):
# captioned hooks; the bare recut_/hooked_/hook_ patterns cover
# derivations that shipped uncaptioned (hook_ is the legacy manual-
# hook prefix, kept so old jobs still resolve).
# wm_*{clean} is the free plan's marked copy of any of those (or of
# the clean file itself: the * matches nothing), written last.
derived = (glob.glob(os.path.join(output_dir, f"subtitled_*_{clean}"))
+ glob.glob(os.path.join(output_dir, f"recut_*_{clean}"))
+ glob.glob(os.path.join(output_dir, f"hooked_*_{clean}"))
+ glob.glob(os.path.join(output_dir, f"hook_{clean}")))
+ glob.glob(os.path.join(output_dir, f"hook_{clean}"))
+ glob.glob(os.path.join(output_dir, f"wm_*{clean}")))
except Exception:
derived = []
if not derived:
@ -739,6 +744,21 @@ def _clips_actually_rendered(job_id, output_dir, base_name, clips):
return kept, len(clips) - len(kept)
def _strip_watermark_copy(output_dir, filename):
"""``wm_<final>`` -> ``<final>`` when the clean twin is on disk.
The free plan serves a marked copy of the final file and keeps the clean
one next to it (see the ``watermarked`` module); every derivation starts
from the clean one, so the mark is always the outermost layer to strip.
Same fail-safe contract as the other walk-backs: unchanged when there is
nothing to strip or the twin is gone."""
if watermarked.is_marked(filename):
clean = watermarked.clean_name(filename)
if os.path.exists(os.path.join(output_dir, clean)):
return clean
return filename
def _strip_burned_captions(output_dir, filename):
"""Walk ``subtitled_<ts>_`` prefixes back to the file without burned captions.
@ -746,6 +766,7 @@ def _strip_burned_captions(output_dir, filename):
underlying file is gone, e.g. a library restore that only kept the current
version).
"""
filename = _strip_watermark_copy(output_dir, filename)
while True:
m = re.match(r'^subtitled_\d+_(.+)$', filename)
if not m or not os.path.exists(os.path.join(output_dir, m.group(1))):
@ -758,6 +779,7 @@ def _strip_burned_hook(output_dir, filename):
without a burned hook. Same fail-safe contract as _strip_burned_captions:
the name is returned unchanged when there is nothing to strip or the
underlying file is gone."""
filename = _strip_watermark_copy(output_dir, filename)
while True:
m = re.match(r'^(?:hooked_\d+_|hook_)(.+)$', filename)
if not m or not os.path.exists(os.path.join(output_dir, m.group(1))):
@ -765,6 +787,80 @@ def _strip_burned_hook(output_dir, filename):
filename = m.group(1)
async def _deliver(request, job_id, filename):
"""The name to serve for a freshly derived clip file: the file itself, or
on the free plan its ``wm_`` copy (``main.mark_delivery``).
Decided from the caller's plan right now, not from the job's flag: the
flag is lost on a restart/restore, and a user who upgraded mid-session
must get clean files from their next edit on. Self-host never marks."""
if not BILLING_ENABLED:
return filename
user = await _user_from_request(request)
if user is None or user.plan != "free":
return filename
output_dir = os.path.join(OUTPUT_DIR, job_id)
# Only jobs the pipeline rendered under this scheme (marker file). A job
# from before it has the mark burned into its canonical, so every
# derivative already carries one and a copy would stack a second.
if not watermarked.job_is_marked(output_dir):
return filename
import main as _main
marked = await asyncio.get_event_loop().run_in_executor(
None, _main.mark_delivery, os.path.join(output_dir, filename))
return os.path.basename(marked)
def _media_guard(path: str) -> bool:
"""``/videos`` allowlist: deliverable types only (media_auth), and on a
job rendered for the free plan never the clean twin of a served clip.
The twins exist so an upgrade can re-point at them, not for stripping
``wm_`` off a URL."""
if not media_auth.is_servable(path):
return False
job_id, _, filename = path.replace("\\", "/").strip("/").partition("/")
if not filename or not watermarked.is_clean_deliverable(filename):
return True
return not watermarked.job_is_marked(os.path.join(OUTPUT_DIR, job_id))
def _unmark_local_job(job_id, clip_index, clean_filename):
"""After an upgrade: point the working copy of a clip at its clean twin.
Called by cloud/videos.unmark_user_library for every clip it re-pointed
in R2, so a dashboard still open on the job polls clean URLs from the
in-memory result and a later restore/recovery reads them from the
metadata. The marked file and the marker go, so the /videos guard opens
the twins again."""
job_dir = os.path.join(OUTPUT_DIR, job_id)
url = f"/videos/{job_id}/{clean_filename}"
job = jobs.get(job_id)
mem_clips = ((job or {}).get('result') or {}).get('clips') or []
if clip_index < len(mem_clips):
mem_clips[clip_index]['video_url'] = url
ready = (job or {}).get('ready_files')
if isinstance(ready, dict) and clip_index in ready:
ready[clip_index] = clean_filename
for meta_path in glob.glob(os.path.join(job_dir, "*_metadata.json")):
try:
with open(meta_path, 'r') as f:
data = json.load(f)
shorts = data.get('shorts', [])
if clip_index < len(shorts):
shorts[clip_index]['video_url'] = url
with open(meta_path, 'w') as f:
json.dump(data, f, indent=4)
except Exception as e:
print(f"⚠️ Could not unmark metadata of {job_id}: {e}")
watermarked.unmark_job(job_dir)
marked_path = os.path.join(job_dir, watermarked.marked_name(clean_filename))
if os.path.exists(marked_path):
try:
os.remove(marked_path)
except OSError:
pass
def _reapply_captions(job_id, clip_index, video_path):
"""Re-burn the default captions onto a freshly derived file.
@ -2182,6 +2278,10 @@ async def lifespan(app: FastAPI):
# Account erasure lives in cloud/, which can't import app.py; hand it the
# one thing only this module can do — wipe the local working files.
cloud.account.register_local_purge(_purge_local_jobs_for_user)
# Same arrangement for the watermark: when a user upgrades, cloud/videos
# re-points their clips at the clean twins in R2 and hands us each
# one so the working copy (and an open dashboard) follows.
cloud.videos.register_local_unmark(_unmark_local_job)
# Autopilot: watch connected YouTube channels for new videos. Paused
# while this instance drains so only the new container submits jobs.
cloud.autopilot.start(app, is_active=lambda: not _draining)
@ -2232,7 +2332,7 @@ from restoring_static import RestoringStaticFiles
import media_auth
app.mount("/videos", RestoringStaticFiles(
directory=OUTPUT_DIR,
guard=media_auth.is_servable,
guard=_media_guard,
restorer=lambda job_id: _restore_for_public_path(job_id)), name="videos")
# Mount static files for serving thumbnails
@ -3537,6 +3637,9 @@ async def _restore_job_files(job_id: str, proj, user_id: str) -> bool:
clip['video_url'] = (
f"/videos/{job_id}/"
f"{_canonical_clip_file(job_dir, base_name, i)}")
if any(watermarked.is_marked(c.get("server_file") or "")
for c in (proj.state or {}).get("clips", [])):
watermarked.mark_job(job_dir)
jobs[job_id] = {
'status': 'completed',
'logs': _TimedLog(["♻️ Project restored from your library."]),
@ -3752,6 +3855,7 @@ async def edit_clip(
if recap:
edited_filename = os.path.basename(recap)
edited_filename = await _deliver(request, req.job_id, edited_filename)
new_video_url = f"/videos/{req.job_id}/{edited_filename}"
# Persist the new current file like /api/subtitle does: in-memory job
@ -3970,7 +4074,8 @@ async def get_clip_edl(job_id: str, clip_index: int, request: Request):
"canonical_range": canonical_range,
"duration": total,
"current_file": current_file,
"has_captions": bool(re.match(r'^subtitled_\d+_', current_file)),
"has_captions": bool(re.match(r'^subtitled_\d+_',
watermarked.clean_name(current_file))),
"words": words_out,
"source": {
"available": bool(source_path),
@ -4133,13 +4238,13 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job):
input_path=source_path, segments=segments,
output_dir=output_dir, clean_name=clean_name,
reframe=True, output_format=data.get('output_format', 'auto'),
watermark=bool(job.get('watermark')),
force_strategy=force_strategy,
captions_transcript=v_transcript)
try:
loop = asyncio.get_event_loop()
served_name, _clean_recut_name = await loop.run_in_executor(None, run_recut)
served_name = await _deliver(request, req.job_id, served_name)
new_video_url = f"/videos/{req.job_id}/{served_name}"
new_recipe = {"v": 1, "segments": segments,
@ -4493,7 +4598,6 @@ async def _reframe_locked(req: ReframeRequest, request: Request, job, overrides)
input_path=source_path, segments=segments,
output_dir=output_dir, clean_name=clean_name,
reframe=True, output_format=data.get('output_format', 'auto'),
watermark=bool(job.get('watermark')),
force_strategy=force_strategy,
crop_overrides=overrides,
captions_transcript=v_transcript)
@ -4501,6 +4605,7 @@ async def _reframe_locked(req: ReframeRequest, request: Request, job, overrides)
try:
loop = asyncio.get_event_loop()
served_name, _clean = await loop.run_in_executor(None, run)
served_name = await _deliver(request, req.job_id, served_name)
new_video_url = f"/videos/{req.job_id}/{served_name}"
new_recipe = {"v": 1, "segments": segments,
@ -4894,6 +4999,8 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
if reservation_id:
await _metering.commit_reservation(reservation_id)
output_filename = await _deliver(request, req.job_id, output_filename)
# 3. Update Result and Metadata
# Update InMemory Jobs
if req.clip_index < len(job['result']['clips']):
@ -4960,16 +5067,15 @@ async def remove_subtitles(req: RemoveSubtitlesRequest, request: Request):
f"_clip_{req.clip_index + 1}.mp4")
# Same walk-back the burn path uses, so this undoes any number of restyles.
while True:
m = re.match(r'^subtitled_\d+_(.+)$', filename)
if not m or not os.path.exists(os.path.join(output_dir, m.group(1))):
break
filename = m.group(1)
filename = _strip_burned_captions(output_dir, filename)
if not os.path.exists(os.path.join(output_dir, filename)):
raise HTTPException(status_code=404,
detail="The original clip is no longer available.")
# Free plan: the un-captioned file is served through its wm_ copy, which
# is reused when the clip shipped that way (no encode).
filename = await _deliver(request, req.job_id, filename)
new_url = f"/videos/{req.job_id}/{filename}"
if req.clip_index < len(job.get('result', {}).get('clips', [])):
job['result']['clips'][req.clip_index]['video_url'] = new_url
@ -5091,6 +5197,8 @@ async def add_hook(req: HookRequest, request: Request):
if recap:
output_filename = os.path.basename(recap)
output_filename = await _deliver(request, req.job_id, output_filename)
# Record the burned hook so the editor knows what the clip carries (the
# auto-hook pipeline writes the same key).
if req.remove:
@ -5216,6 +5324,8 @@ async def translate_clip(
await loop.run_in_executor(
None, lambda: mark_ai_generated(output_path, "AI voice dubbing"))
output_filename = await _deliver(request, req.job_id, output_filename)
# Update InMemory Jobs
if req.clip_index < len(job['result']['clips']):
job['result']['clips'][req.clip_index]['video_url'] = f"/videos/{req.job_id}/{output_filename}"

View file

@ -502,6 +502,22 @@ def _sub_period(sub_obj: dict):
return start, end
LIVE_STATUSES = ("active", "trialing")
def became_live(prev_status, now_status) -> bool:
"""The transition that turns a free account into a paid one."""
return now_status in LIVE_STATUSES and prev_status not in LIVE_STATUSES
async def _unmark_after_upgrade(user_id):
try:
from . import videos
await videos.unmark_user_library(user_id)
except Exception as e:
print(f"⚠️ Could not unmark the library of {user_id} after upgrade: {e}")
async def _upsert_subscription(sub_obj: dict, event_created: datetime):
price_id = _sub_price_id(sub_obj)
info = plan_info_for_price(price_id)
@ -573,6 +589,11 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime):
# by the 'Payment received' alert on invoice.paid, which carries the
# amount; a second message here would just be noise.
now_status = sub_obj["status"]
if became_live(prev_status, now_status):
# The clips this user already made on the free plan lose their
# watermark now (cloud/videos): the upgrade modal promised exactly
# that. Fire-and-forget: Stripe must get its 200 whatever R2 does.
asyncio.create_task(_unmark_after_upgrade(user_id))
label = new_subscriber_label(now_status) if is_new_sub else None
if label:
from .alerts import send_admin_alert

View file

@ -297,7 +297,8 @@ async def send_winback_email(user_id, email: str, promo_code: str = "",
<h2>Liked your clips?</h2>
<p>Free clips carry a watermark and are deleted after 7 days. Starter
($12/mo) gives you 100 minutes a month, no watermark, and clips
stored forever.</p>
stored forever. The clips you already made lose the mark the
moment you upgrade.</p>
{offer}
{_cta(pricing, "See plans")}
<p style="color:#666;font-size:13px">Cancel anytime.</p>

View file

@ -45,6 +45,17 @@ def download_file(key, local_path):
client().download_file(settings.r2_bucket, key, local_path)
def object_size(key):
"""Size in bytes of one object, or None when it is not there."""
try:
return int(client().head_object(Bucket=settings.r2_bucket, Key=key)["ContentLength"])
except client().exceptions.ClientError as e:
code = str((e.response or {}).get("Error", {}).get("Code", ""))
if code in ("404", "NoSuchKey", "NotFound"):
return None
raise
def delete_key(key):
client().delete_object(Bucket=settings.r2_bucket, Key=key)

View file

@ -15,6 +15,8 @@ from . import database, storage, metering
from .models import UserVideo, Subscription, Project, User, ClipExpiryWarning
from .auth import get_current_user_required
import watermarked
router = APIRouter()
@ -22,6 +24,156 @@ def _clip_title(clip) -> str:
return clip.get("title") or clip.get("video_title_for_youtube_short") or "Short"
_HOOK_CHAIN_RE = re.compile(r'^subtitled_\d+_((?:hooked_\d+_|hook_).+)$')
def _canonical_name(base_name, clip_index):
return f"{base_name}_clip_{clip_index + 1}.mp4" if base_name else None
def _twins_to_archive(served, base_name, clip_index):
"""The files that must ride to R2 next to a served clip file, in order.
* its clean twin when it is a free-plan ``wm_`` copy (an upgrade re-points
at it: ``unmark_user_library``), unless that twin is the canonical,
which the caller archives on its own;
* the ``hooked_`` intermediate of a captioned hook chain, resolved on the
clean name, or a restored project's caption restyle cannot walk back to
the hook-only file and would silently drop or stack layers.
"""
out = []
clean = watermarked.clean_name(served)
canonical = _canonical_name(base_name, clip_index)
if clean != served and clean != canonical:
out.append(clean)
m = _HOOK_CHAIN_RE.match(clean)
if m and m.group(1) != canonical:
out.append(m.group(1))
return out
def _superseded_names(prev, original_file, new_filename, base_name, clip_index):
"""R2 objects an edit leaves behind: the previous served file and, when
that was a ``wm_`` copy, its clean twin. Never the pristine original (or
its twin), never the canonical, never the file just written."""
if not prev:
return []
keep = {new_filename, watermarked.clean_name(new_filename),
original_file or "", watermarked.clean_name(original_file or ""),
_canonical_name(base_name, clip_index) or ""}
out = []
for name in (prev, watermarked.clean_name(prev)):
if name and name not in keep and name not in out:
out.append(name)
return out
def unmarked_clip_state(state):
"""Pure half of ``unmark_user_library``: the project state with every
``wm_`` name replaced by its clean twin, plus ``[(index, wm, clean)]`` for
the clips whose served file changed."""
new_state = dict(state or {"v": 1, "clips": []})
changes, clips = [], []
for c in new_state.get("clips", []):
c = dict(c)
served = c.get("server_file") or ""
if watermarked.is_marked(served):
clean = watermarked.clean_name(served)
changes.append((c.get("index"), served, clean))
c["server_file"] = clean
original = c.get("original_file") or ""
if watermarked.is_marked(original):
c["original_file"] = watermarked.clean_name(original)
clips.append(c)
new_state["clips"] = clips
return new_state, changes
# app.py owns the working files and the in-memory job table; like the erasure
# purge (cloud/account.py) it registers a callback at startup rather than being
# imported from here.
_local_unmark = None
def register_local_unmark(fn):
"""Let app.py hand us a ``(job_id, clip_index, clean_filename)`` callback."""
global _local_unmark
_local_unmark = fn
async def unmark_user_library(user_id) -> int:
"""After an upgrade: serve every clip this user has through its clean twin.
The free plan burns the mark into a ``wm_`` copy and archives the clean
final next to it (``_twins_to_archive``), so losing the mark is a
re-pointing, not a render: the history row and the project state move to
the twin, the marked object is deleted, and app.py is told so a dashboard
that is open on the job follows. A clip whose twin is not in R2 keeps its
marked file: a dead link would be worse than the mark. Returns the number
of clips re-pointed.
"""
if not settings.r2_configured:
return 0
async with database.session() as s:
projects = list((await s.execute(
select(Project).where(Project.user_id == user_id)
)).scalars())
done = 0
for proj in projects:
new_state, changes = unmarked_clip_state(proj.state)
if not changes:
continue
applied = []
for index, wm_name, clean in changes:
clean_key = storage.job_key(user_id, proj.job_id, clean)
try:
size = await asyncio.to_thread(storage.object_size, clean_key)
except Exception as e:
print(f"⚠️ R2 head failed for {clean_key}: {e}")
size = None
if size is None:
continue
applied.append((index, wm_name, clean, clean_key, size))
if not applied:
continue
applied_idx = {a[0] for a in applied}
# Clips whose twin is missing keep their marked entry.
prior = {c.get("index"): c for c in (proj.state or {}).get("clips", [])}
new_state["clips"] = [
c if c.get("index") in applied_idx else dict(prior.get(c.get("index"), c))
for c in new_state["clips"]]
async with database.session() as s:
async with s.begin():
row = (await s.execute(
select(Project).where(Project.id == proj.id)
)).scalar_one_or_none()
if row is not None:
row.state = new_state
for index, _wm, _clean, clean_key, size in applied:
vid = (await s.execute(
select(UserVideo).where(UserVideo.user_id == user_id,
UserVideo.job_id == proj.job_id,
UserVideo.clip_index == index)
)).scalars().first()
if vid is not None:
vid.r2_key, vid.size_bytes = clean_key, size
for index, wm_name, clean, _key, _size in applied:
try:
await asyncio.to_thread(
storage.delete_key, storage.job_key(user_id, proj.job_id, wm_name))
except Exception as e:
print(f"⚠️ Could not delete marked R2 object {wm_name}: {e}")
if _local_unmark is not None:
try:
_local_unmark(proj.job_id, index, clean)
except Exception as e:
print(f"⚠️ Local unmark failed for {proj.job_id}: {e}")
done += 1
if done:
print(f"🏷️ Watermark removed from {done} clip(s) of user {user_id} after upgrade.")
return done
async def archive_job(user_id, job_id, clips, output_dir, attestation=None):
"""Upload a completed managed job's clips + metadata JSON to R2 and record
them for history. The metadata (transcript included) plus the Project row
@ -79,19 +231,17 @@ async def archive_job(user_id, job_id, clips, output_dir, attestation=None):
except Exception as e:
print(f"⚠️ R2 upload failed for {clean_key}: {e}")
# A captioned hook is a chain (subtitled_<ts>_hooked_<ts>_<clean>):
# the hooked_ intermediate must come back too, or a restored project's
# caption restyle cannot walk back to the hook-only file and would
# silently drop or stack layers.
m = re.match(r'^subtitled_\d+_((?:hooked_\d+_|hook_).+)$', filename)
if m:
mid_path = os.path.join(output_dir, m.group(1))
if os.path.exists(mid_path):
mid_key = storage.job_key(user_id, job_id, m.group(1))
# Free plan: the served file is the wm_ copy of the final one, and the
# clean final rides along so an upgrade can re-point at it without a
# render (unmark_user_library). The canonical is handled just above.
for twin_name in _twins_to_archive(filename, base_name, i):
twin_path = os.path.join(output_dir, twin_name)
if os.path.exists(twin_path):
twin_key = storage.job_key(user_id, job_id, twin_name)
try:
await asyncio.to_thread(storage.upload_file, mid_path, mid_key)
await asyncio.to_thread(storage.upload_file, twin_path, twin_key)
except Exception as e:
print(f"⚠️ R2 upload failed for {mid_key}: {e}")
print(f"⚠️ R2 upload failed for {twin_key}: {e}")
if not uploaded:
return
@ -163,21 +313,23 @@ async def archive_clip_edit(user_id, job_id, clip_index, output_dir, new_filenam
new_key = storage.job_key(user_id, job_id, new_filename)
await asyncio.to_thread(storage.upload_file, local_path, new_key)
# Same chain rule as archive_job: a captioned hook needs its hooked_
# intermediate archived too, or the restored project cannot re-style.
m = re.match(r'^subtitled_\d+_((?:hooked_\d+_|hook_).+)$', new_filename)
if m:
mid_path = os.path.join(output_dir, m.group(1))
if os.path.exists(mid_path):
try:
await asyncio.to_thread(
storage.upload_file, mid_path,
storage.job_key(user_id, job_id, m.group(1)))
except Exception as e:
print(f"⚠️ R2 upload failed for hook intermediate of {job_id}: {e}")
metadata_r2_key = None
meta_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
base_name = (os.path.basename(meta_files[0]).replace("_metadata.json", "")
if meta_files else None)
# Same chain rule as archive_job: a captioned hook needs its hooked_
# intermediate archived too, or the restored project cannot re-style; and
# a wm_ copy needs its clean twin, or an upgrade cannot drop the mark.
for twin_name in _twins_to_archive(new_filename, base_name, clip_index):
twin_path = os.path.join(output_dir, twin_name)
if os.path.exists(twin_path):
try:
await asyncio.to_thread(
storage.upload_file, twin_path,
storage.job_key(user_id, job_id, twin_name))
except Exception as e:
print(f"⚠️ R2 upload failed for {twin_name} of {job_id}: {e}")
if meta_files:
metadata_r2_key = storage.job_key(user_id, job_id, os.path.basename(meta_files[0]))
try:
@ -188,7 +340,7 @@ async def archive_clip_edit(user_id, job_id, clip_index, output_dir, new_filenam
metadata_r2_key = None
size = os.path.getsize(local_path)
superseded_key = None
superseded = []
async with database.session() as s:
async with s.begin():
proj = (await s.execute(
@ -203,8 +355,10 @@ async def archive_clip_edit(user_id, job_id, clip_index, output_dir, new_filenam
"active_layers": None}
clips_state.append(entry)
prev = entry.get("server_file")
if prev and prev not in (entry.get("original_file"), new_filename):
superseded_key = storage.job_key(user_id, job_id, prev)
superseded = [
storage.job_key(user_id, job_id, name) for name in
_superseded_names(prev, entry.get("original_file"), new_filename,
base_name, clip_index)]
entry["server_file"] = new_filename
state["clips"] = clips_state
proj.state = state
@ -220,7 +374,9 @@ async def archive_clip_edit(user_id, job_id, clip_index, output_dir, new_filenam
else:
s.add(UserVideo(user_id=user_id, job_id=job_id, clip_index=clip_index,
r2_key=new_key, size_bytes=size))
if superseded_key and superseded_key != new_key:
for superseded_key in superseded:
if superseded_key == new_key:
continue
try:
await asyncio.to_thread(storage.delete_key, superseded_key)
except Exception as e:

View file

@ -14,6 +14,8 @@ import ClipEditor from './components/ClipEditor';
import ReframeEditor from './components/ReframeEditor';
import UsageMeter from './components/UsageMeter';
import TopUpModal from './components/TopUpModal';
import WatermarkModal, { watermarkNoticeDismissed } from './components/WatermarkModal';
import { getApiUrl } from './config';
import StarBanner from './components/StarBanner';
import PlanChoiceModal from './components/PlanChoiceModal';
import ClipTutorial from './components/ClipTutorial';
@ -270,6 +272,9 @@ function App() {
const { billingEnabled, isManaged, isSignedIn, me, plan, refreshMe, jobRetentionSeconds, localLlm } = useAuth();
const [showLogin, setShowLogin] = useState(false);
const [showTopUp, setShowTopUp] = useState(false);
// Free plan: "want the watermark off?" once per job, when the clips land.
const [showWmNotice, setShowWmNotice] = useState(false);
const wmNoticedJobRef = useRef(null);
const [showPlanChoice, setShowPlanChoice] = useState(false);
const [tutorialPhase, setTutorialPhase] = useState(null); // null | intro | coach | celebrate
const [showTrialUpgrade, setShowTrialUpgrade] = useState(false);
@ -434,6 +439,47 @@ function App() {
// map on a backoff until the archived name matches the clip's new file, then it
// can play from R2 again. Gives up quietly: staying on /videos is correct, just
// slower, and is exactly what happens for self-hosted users all the time.
const openUpsell = () => { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); };
// The clips just landed on a free account: ask once, per job, whether they
// want the mark off. A beat after the grid renders, so the first thing they
// see is their clips and not a modal over them.
useEffect(() => {
if (status !== 'complete' || plan !== 'free' || !isManaged || !jobId) return;
if (!(results?.clips?.length > 0)) return;
if (wmNoticedJobRef.current === jobId || watermarkNoticeDismissed(jobId)) return;
wmNoticedJobRef.current = jobId;
const t = setTimeout(() => { if (jobIdRef.current === jobId) setShowWmNotice(true); }, 2500);
return () => clearTimeout(t);
}, [status, plan, isManaged, jobId, results?.clips?.length]);
// Paying re-points the clips already on screen at their clean twins (the API
// does it from the Stripe webhook, a few seconds after the plan flips). Chase
// the job result until no served file carries the wm_ prefix, then refresh
// the durable map so the players switch to the clean R2 copies too.
useEffect(() => {
if (!isManaged || !jobId || !plan || plan === 'free') return;
const isMarked = (c) => /\/wm_[^/]*$/.test(c?.video_url || '');
if (!(results?.clips || []).some(isMarked)) return;
let cancelled = false;
(async () => {
for (const delay of [1500, 3000, 6000, 12000, 20000]) {
await new Promise((r) => setTimeout(r, delay));
if (cancelled || jobIdRef.current !== jobId) return;
let data;
try { data = await pollJob(jobId); } catch { continue; }
if (cancelled || jobIdRef.current !== jobId) return;
if (data?.result) setResults(data.result);
if (!(data?.result?.clips || []).some(isMarked)) {
fetchDurableMap().then((m) => { if (!cancelled) setDurableClips(m); }).catch(() => {});
return;
}
}
})();
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [plan, isManaged, jobId]);
const chaseDurableFile = async (index, expectedFile) => {
const forJob = jobId;
for (const delay of [2500, 6000, 15000, 30000]) {
@ -2146,8 +2192,8 @@ function App() {
className="w-full text-left px-3 py-2.5 rounded-input bg-paper3 border border-brass/40 hover:border-brass text-sm transition-colors"
>
<span className="text-ink">Like these clips?</span>{' '}
<span className="text-muted">They carry a watermark and delete in 7 days.</span>{' '}
<span className="text-brass font-medium">Keep them forever →</span>
<span className="text-muted">Upgrade and these exact clips lose the watermark on the spot, and stay for good.</span>{' '}
<span className="text-brass font-medium">Remove the watermark →</span>
</button>
)}
{/* Distribution nudge at the same peak: clips on screen,
@ -2215,6 +2261,7 @@ function App() {
jobId={jobId}
onEditClip={(index) => setEditingClip(index)}
onReframeClip={(index) => setReframingClip(index)}
onUpgrade={isManaged ? openUpsell : null}
initialState={projectState?.clips?.find((c) => c.index === i) || null}
onStateChange={handleClipStateChange}
durable={durableClips[i]}
@ -2423,6 +2470,15 @@ function App() {
/>
)}
{showPlanChoice && <PlanChoiceModal onClose={() => setShowPlanChoice(false)} />}
{showWmNotice && (
<WatermarkModal
source="results"
jobId={jobId}
previewSrc={results?.clips?.[0]?.video_url ? getApiUrl(results.clips[0].video_url) : null}
onUpgrade={openUpsell}
onClose={() => setShowWmNotice(false)}
/>
)}
{showTopUp && (
<TopUpModal
onClose={() => setShowTopUp(false)}

View file

@ -36,7 +36,7 @@ function formatDuration(clip) {
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`;
}
export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null }) {
export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null, onUpgrade = null }) {
const [showModal, setShowModal] = useState(false);
// The "why" line is clamped to two lines so cards in a row stay level;
// when it overflows, a hover (desktop) or tap (touch) shows the whole
@ -980,7 +980,7 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
e.preventDefault();
// Free clips are watermarked — surface the upsell once
// before the first download, then get out of the way.
if (plan === 'free' && !watermarkNoticeDismissed()) {
if (plan === 'free' && !watermarkNoticeDismissed(jobId)) {
setShowWatermarkModal(true);
return;
}
@ -1199,6 +1199,9 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
{showWatermarkModal && (
<WatermarkModal
source="download"
jobId={jobId}
onUpgrade={onUpgrade}
onClose={() => setShowWatermarkModal(false)}
onContinue={downloadClip}
/>

View file

@ -120,7 +120,8 @@ export default function TopUpModal({ onClose, required, remaining, partialMinute
<p className="text-muted text-sm mb-5">
{isUpsell
? <>Every clip comes out <b className="text-ink font-medium">ready to post</b> and stays in your
library for good. On the free plan they carry a watermark and are deleted after 7 days.</>
library for good. On the free plan they carry a watermark and are deleted after 7 days;
upgrade now and the clips you already made <b className="text-ink font-medium">lose the mark on the spot</b>.</>
: blockedByLength
? <>This video is <b className="text-ink font-medium">{required} min</b> long and you have{' '}
<b className="text-ink font-medium">{remainingShown} min</b> this month. Pick a plan and the

View file

@ -1,17 +1,39 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import Modal from './ui/Modal';
import { track } from '../lib/analytics';
const DISMISS_KEY = 'os_watermark_notice_dismissed';
const SEEN_PREFIX = 'os_watermark_noticed_';
// eslint-disable-next-line react-refresh/only-export-components
export function watermarkNoticeDismissed() {
try { return localStorage.getItem(DISMISS_KEY) === '1'; } catch { return false; }
export function watermarkNoticeDismissed(jobId = null) {
try {
if (localStorage.getItem(DISMISS_KEY) === '1') return true;
// Once per job: the results view shows it when the clips land, so the
// first download of the same job must not show it a second time.
return !!(jobId && sessionStorage.getItem(SEEN_PREFIX + jobId) === '1');
} catch { return false; }
}
// Shown to free users before their first download: the clip carries a
// watermark, and upgrading removes it. Dismissible for good, like OpusClip's.
export default function WatermarkModal({ onClose, onContinue }) {
// eslint-disable-next-line react-refresh/only-export-components
export function markWatermarkNoticed(jobId) {
try { if (jobId) sessionStorage.setItem(SEEN_PREFIX + jobId, '1'); } catch { /* ignore */ }
}
// Shown to free users when their clips land (source="results") and, if they
// skipped that, before their first download (source="download"). The promise
// is literal since 30-sep-2026: the pipeline keeps a clean twin of every free
// clip and paying re-points the library at it, so the clips on screen lose
// the mark on the spot. Dismissible for good, like OpusClip's.
export default function WatermarkModal({ onClose, onContinue, onUpgrade, previewSrc = null,
source = 'download', jobId = null }) {
const [dontShow, setDontShow] = useState(false);
const [previewFailed, setPreviewFailed] = useState(false);
useEffect(() => {
markWatermarkNoticed(jobId);
track('WatermarkNoticeSeen', { props: { source } });
}, [jobId, source]);
const close = (proceed) => {
if (dontShow) {
@ -21,20 +43,32 @@ export default function WatermarkModal({ onClose, onContinue }) {
onClose();
};
const upgrade = () => {
track('WatermarkNoticeUpgrade', { props: { source } });
close(false);
if (onUpgrade) onUpgrade();
else window.location.hash = '#/pricing';
};
const src = previewSrc && !previewFailed ? previewSrc : '/demo/clip-vertical.mp4';
return (
<Modal isOpen onClose={() => close(false)} eyebrow="FREE PLAN" title="Upgrade to remove the watermark" size="md">
<Modal isOpen onClose={() => close(false)} eyebrow="FREE PLAN" title="Want the watermark off?" size="md">
<p className="text-muted text-sm mb-4">
Clips on the free plan carry the OpenShorts mark in the corner, and are
kept for 7 days. Any paid plan exports them clean and keeps them for good.
Clips on the free plan carry the OpenShorts mark and are deleted after 7 days.
Upgrade and <b className="text-ink font-medium">these exact clips lose the mark on the spot</b>,
no re-render, and stay in your library for good.
</p>
<div className="rounded-card border border-rule overflow-hidden bg-paper mb-5">
<video
src="/demo/clip-vertical.mp4"
key={src}
src={src}
autoPlay
muted
loop
playsInline
onError={() => setPreviewFailed(true)}
className="w-full max-h-56 object-cover"
/>
</div>
@ -51,13 +85,10 @@ export default function WatermarkModal({ onClose, onContinue }) {
</label>
<div className="flex items-center gap-2">
<button onClick={() => close(true)} className="btn-ghost px-4 py-2 text-sm">
Download anyway
{source === 'download' ? 'Download anyway' : 'Keep the watermark'}
</button>
<button
onClick={() => { close(false); window.location.hash = '#/pricing'; }}
className="btn-primary px-4 py-2 text-sm"
>
Upgrade
<button onClick={upgrade} className="btn-primary px-4 py-2 text-sm">
Remove the watermark
</button>
</div>
</div>

76
main.py
View file

@ -1,6 +1,7 @@
import time
import cv2
import subprocess
import shutil
import argparse
import re
import sys
@ -1394,12 +1395,14 @@ def watermark_filter(vw, vh, video="[0:v]", logo="[1:v]", out=""):
)
def apply_watermark(video_path):
def apply_watermark(video_path, output_path=None):
"""Burn the OpenShorts watermark into a finished clip (free plan).
One re-encode pass on the final file so every output format (TRACK,
GENERAL, horizontal passthrough) gets the mark, and later subtitle/hook
re-encodes keep it — they re-encode the already-marked pixels.
One re-encode pass over the final file so every output format (TRACK,
GENERAL, horizontal passthrough) gets the mark. In place by default; with
``output_path`` the source stays untouched and the marked copy is written
there, which is how the pipeline keeps the clean file next to the served
one (see ``mark_delivery``).
"""
logo_path = watermark_logo_path()
if not os.path.exists(logo_path):
@ -1420,7 +1423,7 @@ def apply_watermark(video_path):
return False
filt = watermark_filter(vw, vh)
tmp_path = video_path + ".wm.mp4"
tmp_path = (output_path or video_path) + ".wm.mp4"
cmd = ["ffmpeg", "-y", "-i", video_path, "-i", logo_path,
"-filter_complex", filt,
*video_encode_args(QUALITY), "-c:a", "copy", *METADATA_SCRUB,
@ -1428,7 +1431,7 @@ def apply_watermark(video_path):
result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
timeout=1800)
if result.returncode == 0 and os.path.exists(tmp_path):
os.replace(tmp_path, video_path)
os.replace(tmp_path, output_path or video_path)
return True
err = (result.stderr or b"").decode(errors="ignore")[-300:]
print(f" ⚠️ Watermark pass failed (clip kept unmarked): {err}")
@ -1437,6 +1440,37 @@ def apply_watermark(video_path):
return False
def mark_delivery(final_path, marker=None):
"""The free-plan copy of a finished clip to serve: ``wm_<final>`` next to it.
The clean ``final_path`` is left as it is. That is the whole point: an
upgrade re-points the clip at the clean twin instead of re-running the
job (``watermarked`` module). An existing copy is reused, so re-choosing
a file the user already had (captions off, hook off) costs no encode.
Returns the marked path, or ``final_path`` itself when the copy could not
be made: the mark must never cost the user the clip (same fail-open rule
apply_watermark has always had).
"""
import watermarked
out_path = os.path.join(os.path.dirname(final_path),
watermarked.marked_name(final_path))
if os.path.exists(out_path) and os.path.getsize(out_path) > 0:
return out_path
ok = (marker or apply_watermark)(final_path, out_path)
if ok and os.path.exists(out_path):
return out_path
# Still the wm_ name: the /videos guard refuses the clean deliverables of
# a free job, so serving the clean name here would be a clip the user
# cannot play. The copy simply carries no mark.
print(f" ⚠️ Serving {os.path.basename(final_path)} unmarked (copy).")
try:
shutil.copyfile(final_path, out_path)
return out_path
except OSError:
return final_path
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO,
force_strategy=None, crop_overrides=None, watermark=False):
"""
@ -2406,16 +2440,15 @@ if __name__ == '__main__':
# ffmpeg cut — re-encoding for precision on strict seconds
cut_clip(input_video, clip_temp_path, start, end, i + 1)
# Layer order: watermark burns into the canonical (so any
# later hook replacement, which re-derives from it, keeps
# the branding), the hook is a derived hooked_ file, and
# captions go last on top of whichever is current. The
# watermark rides the reframe's own encode instead of a
# pass of its own: one encode less per clip on every
# free-plan job. Each worker writes only its own clip
# dict, so the re-dump after the pool is race-free.
success = render_clip(clip_temp_path, clip_final_path, output_format,
watermark=os.environ.get("WATERMARK") == "1")
# Layer order: the canonical reframe stays CLEAN, the hook
# is a derived hooked_ file, captions go last on top of
# whichever is current, and on the free plan the served
# file is a wm_ copy of that final (mark_delivery). The
# mark used to ride the reframe encode, which made it
# permanent: paying could not remove it from clips already
# made. Each worker writes only its own clip dict, so the
# re-dump after the pool is race-free.
success = render_clip(clip_temp_path, clip_final_path, output_format)
if success:
print(f" 🎞️ Clip {i+1} framed")
deliver_path = clip_final_path
@ -2446,6 +2479,9 @@ if __name__ == '__main__':
captioned = auto_caption_clip(
deliver_path, transcript, start, end,
split_ranges=split_ranges)
served = captioned or deliver_path
if os.environ.get("WATERMARK") == "1":
served = mark_delivery(served)
print(f" ✅ Clip {i+1} ready: {clip_final_path}")
# Hand the API the file to actually serve for this clip.
# Without it the status poller guesses the clean reframe
@ -2455,8 +2491,7 @@ if __name__ == '__main__':
# Printed only after the full chain (reframe, watermark,
# hook, captions) so the file is complete when it is
# announced, never one that ffmpeg is still writing.
print(f"CLIP_READY {i} "
f"{os.path.basename(captioned or deliver_path)}")
print(f"CLIP_READY {i} {os.path.basename(served)}")
return success
finally:
if os.path.exists(clip_temp_path):
@ -2468,6 +2503,11 @@ if __name__ == '__main__':
clip_workers = max(int(os.environ.get("CLIP_WORKERS", "6")), 1)
shorts = clips_data['shorts']
failed = []
if os.environ.get("WATERMARK") == "1":
# Tells the /videos guard that the clean twins in this
# directory are not for serving (watermarked.MARKER_FILE).
import watermarked
watermarked.mark_job(output_dir)
with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool:
# Best clip first: the pool starts work in submission order, so
# the user's first delivered clip is the strongest one instead

View file

@ -68,4 +68,9 @@ class RestoringStaticFiles(StaticFiles):
restored = False
if not restored:
raise
# The guard may read the job directory (a free job's clean twins
# are refused by a marker file that only exists once the files
# are back), so the verdict before the restore is not final.
if self.guard is not None and not self.guard(path):
raise HTTPException(status_code=404)
return await super().get_response(path, scope)

View file

@ -71,7 +71,9 @@ class TestMainAnnouncesTheDeliveredFile:
"""
main_src = open("main.py", encoding="utf-8").read()
caption_at = main_src.index("captioned = auto_caption_clip(")
marker_at = main_src.index('print(f"CLIP_READY {i} "')
assert caption_at < marker_at
marker_line = main_src[marker_at:marker_at + 200]
assert "captioned or deliver_path" in marker_line
# The free plan's served file is a wm_ copy of the captioned final
# (mark_delivery), so the marker must also come after that step.
served_at = main_src.index("served = captioned or deliver_path")
mark_at = main_src.index("served = mark_delivery(served)")
marker_at = main_src.index('print(f"CLIP_READY {i} {os.path.basename(served)}")')
assert caption_at < served_at < mark_at < marker_at

View file

@ -21,8 +21,13 @@ class TestTheGuardIsWiredIn:
app = pytest.importorskip("app")
mount = next(r for r in app.app.routes
if getattr(r, "name", None) == "videos")
assert mount.app.guard is media_auth.is_servable, \
# app._media_guard wraps the allowlist (and adds the free-plan rule
# that refuses a marked job's clean twins, tests/test_watermark_delivery).
assert mount.app.guard is app._media_guard, \
"/videos is serving the working directory with no allowlist"
assert not app._media_guard("job/.resume.json")
assert not app._media_guard("job/x_metadata.json")
assert app._media_guard("job/x_clip_1.mp4")
class TestWhatMayLeave:

View file

@ -245,7 +245,9 @@ class TestRerenderPaths:
assert call["input_path"].endswith("src.mp4")
assert call["reframe"] is True
assert call["output_format"] == "auto"
assert call["watermark"] is False
# The free-plan mark is applied at delivery (app._deliver), never
# inside the recut, so the served twins stay clean for an upgrade.
assert not call.get("watermark")
# Source-absolute times, not rebased.
assert call["segments"] == [{"start": 45.0, "end": 55.0}]

View file

@ -0,0 +1,274 @@
"""The free plan's watermark is a served COPY, never the file itself.
Until 30-sep-2026 the mark was burned into the canonical reframe, so every
derivative (hook, captions, recut) inherited it and nothing short of running
the whole job again could remove it. The upgrade modal said "upgrade to remove
the watermark" all the same, and the first cancellation for "clip quality" was
a user who paid fifteen minutes after their first job and found the mark still
there on every download and every restyle.
Now every file the pipeline and the editor write is clean, the served file on
the free plan is a ``wm_`` twin of the final one (``main.mark_delivery``), both
go to R2, and an upgrade re-points the library at the clean twins with no
render (``cloud.videos.unmark_user_library``).
"""
import asyncio
import json
import os
import pytest
import watermarked
class TestNames:
def test_marked_and_clean_are_inverses(self):
assert watermarked.marked_name("a_clip_1.mp4") == "wm_a_clip_1.mp4"
assert watermarked.marked_name("wm_a_clip_1.mp4") == "wm_a_clip_1.mp4"
assert watermarked.clean_name("wm_subtitled_1_hooked_2_a_clip_1.mp4") == \
"subtitled_1_hooked_2_a_clip_1.mp4"
assert watermarked.clean_name("a_clip_1.mp4") == "a_clip_1.mp4"
assert watermarked.is_marked("wm_x.mp4") and not watermarked.is_marked("x.mp4")
def test_clean_deliverables_are_clips_and_their_derivatives(self):
for name in ("t_clip_1.mp4", "subtitled_1_t_clip_1.mp4", "hooked_1_t_clip_2.mp4",
"recut_1_ab_t_clip_1.mp4", "edited_t_clip_1.mp4",
"translated_es_t_clip_1.mp4"):
assert watermarked.is_clean_deliverable(name), name
# The marked copy itself, the editor's scratch files, and sidecars are
# not clean deliverables: they stay servable on a marked job.
for name in ("wm_t_clip_1.mp4", "temp_preview_0.mp4", "temp_scene_ab_001.jpg",
"subs_0_1.ass", "t_clip_1.layout.json"):
assert not watermarked.is_clean_deliverable(name), name
def test_marker_round_trip(self, tmp_path):
d = str(tmp_path)
assert not watermarked.job_is_marked(d)
watermarked.mark_job(d)
assert watermarked.job_is_marked(d)
watermarked.unmark_job(d)
assert not watermarked.job_is_marked(d)
watermarked.unmark_job(d) # idempotent
class TestMarkDelivery:
"""The pipeline's last step on a free job: a wm_ copy next to the clean final."""
def test_writes_the_copy_and_leaves_the_final_alone(self, tmp_path):
main = pytest.importorskip("main")
final = tmp_path / "subtitled_1_t_clip_1.mp4"
final.write_bytes(b"clean")
calls = []
def marker(src, out):
calls.append((os.path.basename(src), os.path.basename(out)))
with open(out, "wb") as f:
f.write(b"marked")
return True
served = main.mark_delivery(str(final), marker=marker)
assert os.path.basename(served) == "wm_subtitled_1_t_clip_1.mp4"
assert calls == [("subtitled_1_t_clip_1.mp4", "wm_subtitled_1_t_clip_1.mp4")]
assert final.read_bytes() == b"clean"
def test_reuses_an_existing_copy(self, tmp_path):
main = pytest.importorskip("main")
(tmp_path / "t_clip_1.mp4").write_bytes(b"clean")
(tmp_path / "wm_t_clip_1.mp4").write_bytes(b"marked")
served = main.mark_delivery(str(tmp_path / "t_clip_1.mp4"),
marker=lambda *_: pytest.fail("re-encoded"))
assert os.path.basename(served) == "wm_t_clip_1.mp4"
def test_fails_open_under_the_marked_name(self, tmp_path):
"""A failed mark still serves the clip, and still under the wm_ name:
the /videos guard refuses the clean deliverables of a free job, so a
clean name here would be a clip the user cannot play."""
main = pytest.importorskip("main")
(tmp_path / "t_clip_1.mp4").write_bytes(b"clean")
served = main.mark_delivery(str(tmp_path / "t_clip_1.mp4"),
marker=lambda *_: False)
assert os.path.basename(served) == "wm_t_clip_1.mp4"
assert (tmp_path / "wm_t_clip_1.mp4").read_bytes() == b"clean"
class TestWalkBacks:
"""The mark is the outermost layer: every editor derivation strips it first."""
def test_strip_captions_walks_through_the_mark(self, tmp_path):
app = pytest.importorskip("app")
d = str(tmp_path)
for name in ("t_clip_1.mp4", "hooked_2_t_clip_1.mp4",
"subtitled_3_hooked_2_t_clip_1.mp4",
"wm_subtitled_3_hooked_2_t_clip_1.mp4"):
(tmp_path / name).write_bytes(b"x")
assert app._strip_burned_captions(d, "wm_subtitled_3_hooked_2_t_clip_1.mp4") == \
"hooked_2_t_clip_1.mp4"
assert app._strip_burned_hook(d, "hooked_2_t_clip_1.mp4") == "t_clip_1.mp4"
# The mark is a copy of a file that is on disk: it walks back the same.
assert app._strip_burned_hook(d, "wm_hooked_2_t_clip_1.mp4") == "t_clip_1.mp4"
def test_strip_keeps_the_mark_when_the_twin_is_gone(self, tmp_path):
app = pytest.importorskip("app")
(tmp_path / "wm_t_clip_1.mp4").write_bytes(b"x")
assert app._strip_burned_captions(str(tmp_path), "wm_t_clip_1.mp4") == "wm_t_clip_1.mp4"
def test_canonical_clip_file_prefers_the_marked_copy(self, tmp_path):
app = pytest.importorskip("app")
import time
(tmp_path / "t_clip_1.mp4").write_bytes(b"x")
(tmp_path / "subtitled_5_t_clip_1.mp4").write_bytes(b"x")
time.sleep(0.02)
(tmp_path / "wm_subtitled_5_t_clip_1.mp4").write_bytes(b"x")
os.utime(tmp_path / "wm_subtitled_5_t_clip_1.mp4", None)
assert app._canonical_clip_file(str(tmp_path), "t", 0) == "wm_subtitled_5_t_clip_1.mp4"
class TestMediaGuard:
"""A free job's clean twins are not fetchable by stripping wm_ off the URL."""
def test_deliver_marks_only_jobs_the_pipeline_marked(self, tmp_path, monkeypatch):
"""An old-scheme free job (mark burned into the canonical, no marker)
must not get a second mark on its next edit."""
app = pytest.importorskip("app")
monkeypatch.setattr(app, "OUTPUT_DIR", str(tmp_path))
monkeypatch.setattr(app, "BILLING_ENABLED", True)
class _U:
plan = "free"
async def _user(_request):
return _U()
monkeypatch.setattr(app, "_user_from_request", _user)
(tmp_path / "old").mkdir()
(tmp_path / "old" / "t_clip_1.mp4").write_bytes(b"burned")
assert asyncio.run(app._deliver(None, "old", "t_clip_1.mp4")) == "t_clip_1.mp4"
(tmp_path / "new").mkdir()
(tmp_path / "new" / "t_clip_1.mp4").write_bytes(b"clean")
watermarked.mark_job(str(tmp_path / "new"))
# main.py needs the ML stack; _deliver imports it lazily, so a stub
# module stands in for it here (CI installs none of it).
import sys
import types
monkeypatch.setitem(sys.modules, "main", types.SimpleNamespace(
mark_delivery=lambda path, marker=None: os.path.join(
os.path.dirname(path), "wm_" + os.path.basename(path))))
assert asyncio.run(app._deliver(None, "new", "t_clip_1.mp4")) == "wm_t_clip_1.mp4"
def test_marked_job_refuses_clean_clips_only(self, tmp_path, monkeypatch):
app = pytest.importorskip("app")
monkeypatch.setattr(app, "OUTPUT_DIR", str(tmp_path))
(tmp_path / "job1").mkdir()
watermarked.mark_job(str(tmp_path / "job1"))
assert app._media_guard("job1/wm_subtitled_1_t_clip_1.mp4")
assert not app._media_guard("job1/subtitled_1_t_clip_1.mp4")
assert not app._media_guard("job1/t_clip_1.mp4")
# Editor scratch files and sidecars stay servable.
assert app._media_guard("job1/temp_preview_0.mp4")
assert app._media_guard("job1/subs_0_1.ass")
# And a dotfile never is, marker included.
assert not app._media_guard("job1/.marked")
def test_unmarked_job_serves_everything_deliverable(self, tmp_path, monkeypatch):
app = pytest.importorskip("app")
monkeypatch.setattr(app, "OUTPUT_DIR", str(tmp_path))
(tmp_path / "job2").mkdir()
assert app._media_guard("job2/t_clip_1.mp4")
assert not app._media_guard("job2/t_metadata.json")
class TestLocalUnmark:
def test_repoints_memory_metadata_and_drops_the_copy(self, tmp_path, monkeypatch):
app = pytest.importorskip("app")
monkeypatch.setattr(app, "OUTPUT_DIR", str(tmp_path))
job_dir = tmp_path / "j1"
job_dir.mkdir()
(job_dir / "t_clip_1.mp4").write_bytes(b"clean")
(job_dir / "wm_t_clip_1.mp4").write_bytes(b"marked")
watermarked.mark_job(str(job_dir))
(job_dir / "t_metadata.json").write_text(json.dumps({
"shorts": [{"video_url": "/videos/j1/wm_t_clip_1.mp4"}]}))
app.jobs["j1"] = {"status": "completed",
"result": {"clips": [{"video_url": "/videos/j1/wm_t_clip_1.mp4"}]},
"ready_files": {0: "wm_t_clip_1.mp4"}}
try:
app._unmark_local_job("j1", 0, "t_clip_1.mp4")
assert app.jobs["j1"]["result"]["clips"][0]["video_url"] == "/videos/j1/t_clip_1.mp4"
assert app.jobs["j1"]["ready_files"][0] == "t_clip_1.mp4"
meta = json.loads((job_dir / "t_metadata.json").read_text())
assert meta["shorts"][0]["video_url"] == "/videos/j1/t_clip_1.mp4"
assert not (job_dir / "wm_t_clip_1.mp4").exists()
assert (job_dir / "t_clip_1.mp4").exists()
assert not watermarked.job_is_marked(str(job_dir))
finally:
app.jobs.pop("j1", None)
class TestArchiveTwins:
def test_twins_of_a_marked_captioned_hook(self):
videos = pytest.importorskip("cloud.videos")
assert videos._twins_to_archive("wm_subtitled_3_hooked_2_t_clip_1.mp4", "t", 0) == [
"subtitled_3_hooked_2_t_clip_1.mp4", "hooked_2_t_clip_1.mp4"]
def test_the_canonical_is_the_callers_job(self):
videos = pytest.importorskip("cloud.videos")
# wm_ copy of the canonical itself: the twin IS the canonical, which
# archive_job uploads on its own branch.
assert videos._twins_to_archive("wm_t_clip_1.mp4", "t", 0) == []
# A clean captioned hook (paid plan): only the intermediate.
assert videos._twins_to_archive("subtitled_3_hooked_2_t_clip_1.mp4", "t", 0) == [
"hooked_2_t_clip_1.mp4"]
assert videos._twins_to_archive("t_clip_1.mp4", "t", 0) == []
def test_superseded_never_touches_master_or_original(self):
videos = pytest.importorskip("cloud.videos")
# An edit on a free job: the previous marked file and its clean twin go.
assert videos._superseded_names(
"wm_subtitled_1_t_clip_1.mp4", "wm_subtitled_0_t_clip_1.mp4",
"wm_subtitled_2_t_clip_1.mp4", "t", 0) == [
"wm_subtitled_1_t_clip_1.mp4", "subtitled_1_t_clip_1.mp4"]
# Back to the canonical (captions removed): the canonical survives.
assert videos._superseded_names(
"wm_t_clip_1.mp4", "wm_subtitled_0_t_clip_1.mp4",
"wm_subtitled_2_t_clip_1.mp4", "t", 0) == ["wm_t_clip_1.mp4"]
# The pristine original (and its twin) survive too.
assert videos._superseded_names(
"wm_subtitled_0_t_clip_1.mp4", "wm_subtitled_0_t_clip_1.mp4",
"wm_subtitled_2_t_clip_1.mp4", "t", 0) == []
assert videos._superseded_names(None, None, "x.mp4", "t", 0) == []
class TestUnmarkedState:
def test_replaces_marked_names_and_reports_changes(self):
videos = pytest.importorskip("cloud.videos")
state = {"v": 1, "rights_attestation": {"acknowledged": True}, "clips": [
{"index": 0, "original_file": "wm_subtitled_1_t_clip_1.mp4",
"server_file": "wm_subtitled_9_t_clip_1.mp4", "active_layers": None},
{"index": 1, "original_file": "t_clip_2.mp4", "server_file": "t_clip_2.mp4"},
]}
new_state, changes = videos.unmarked_clip_state(state)
assert changes == [(0, "wm_subtitled_9_t_clip_1.mp4", "subtitled_9_t_clip_1.mp4")]
assert new_state["clips"][0]["server_file"] == "subtitled_9_t_clip_1.mp4"
assert new_state["clips"][0]["original_file"] == "subtitled_1_t_clip_1.mp4"
assert new_state["clips"][1] == state["clips"][1]
assert new_state["rights_attestation"] == {"acknowledged": True}
# The input is not mutated.
assert state["clips"][0]["server_file"] == "wm_subtitled_9_t_clip_1.mp4"
def test_nothing_marked_nothing_changes(self):
videos = pytest.importorskip("cloud.videos")
assert videos.unmarked_clip_state(None) == ({"v": 1, "clips": []}, [])
class TestBecameLive:
def test_only_the_free_to_paid_transition(self):
billing = pytest.importorskip("cloud.billing")
assert billing.became_live(None, "active")
assert billing.became_live(None, "trialing")
assert billing.became_live("canceled", "active")
assert billing.became_live("incomplete", "active")
assert not billing.became_live("active", "active")
assert not billing.became_live("trialing", "active")
assert not billing.became_live(None, "incomplete")
assert not billing.became_live("active", "canceled")

87
watermarked.py Normal file
View file

@ -0,0 +1,87 @@
"""Names for the free plan's watermarked delivery copies.
Every file the pipeline and the clip editor write is CLEAN. On the free plan
the file that is *served* is a copy of the final one with the mark burned in,
named ``wm_<final>`` and kept next to it (and in R2 beside it). Two things
follow from keeping both:
* an upgrade removes the watermark from the clips the user already has by
re-pointing each clip at its clean twin, with no re-encode and no source
video, which is what the upgrade modal has always promised
(``cloud.videos.unmark_user_library``);
* the walk-backs that find the editable master under a served name
(``app._strip_burned_captions`` and friends) treat the ``wm_`` prefix as the
outermost layer, and the ``/videos`` guard refuses the clean twins of a
free job so the copy cannot be fetched by stripping the prefix from a URL.
Before 30-sep-2026 the mark was burned into the canonical reframe, so the
only way to lose it was to run the whole job again: the first cancellation
for "clip quality" was a user who paid 15 minutes after their first job and
found the mark still there on every download and every restyle.
No imports beyond the standard library on purpose: ``main.py``, ``app.py``
and ``cloud/videos.py`` all use it and only the first of those has ffmpeg.
"""
import os
import re
PREFIX = "wm_"
# The dotfile ``main.py`` writes in a job directory rendered for the free plan.
# Read by the ``/videos`` guard (a dotfile is never servable itself); removed
# when the library is unmarked after an upgrade.
MARKER_FILE = ".marked"
_VIDEO_EXTENSIONS = frozenset({".mp4", ".webm", ".mov", ".m4v", ".mkv", ".ogv"})
# Names that are a deliverable clip or one of its derivatives. The editor's
# own scratch files (``temp_preview_<i>.mp4``, ``temp_scene_*.jpg``) are not
# clips and stay servable on a marked job.
_DELIVERABLE_RE = re.compile(
r'^(?:subtitled_\d+_|hooked_\d+_|hook_|recut_|edited_|translated_)|_clip_\d+\.[A-Za-z0-9]+$'
)
def is_marked(filename: str) -> bool:
return bool(filename) and os.path.basename(filename).startswith(PREFIX)
def marked_name(filename: str) -> str:
"""``wm_<filename>``; idempotent."""
base = os.path.basename(filename)
return base if base.startswith(PREFIX) else PREFIX + base
def clean_name(filename: str) -> str:
"""The clean twin of a served name (the name itself when not marked)."""
base = os.path.basename(filename)
return base[len(PREFIX):] if base.startswith(PREFIX) else base
def is_clean_deliverable(filename: str) -> bool:
"""True for a clip file (canonical or derived) that carries no mark."""
base = os.path.basename(filename or "")
if not base or base.startswith(PREFIX):
return False
if os.path.splitext(base)[1].lower() not in _VIDEO_EXTENSIONS:
return False
return bool(_DELIVERABLE_RE.search(base))
def job_is_marked(job_dir: str) -> bool:
return os.path.exists(os.path.join(job_dir, MARKER_FILE))
def mark_job(job_dir: str) -> None:
try:
with open(os.path.join(job_dir, MARKER_FILE), "w") as f:
f.write("1")
except OSError:
pass
def unmark_job(job_dir: str) -> None:
try:
os.remove(os.path.join(job_dir, MARKER_FILE))
except OSError:
pass