Skip to content

perf: generate adaptive HLS ladders for share videos - #4905

Open
AatmanAJ wants to merge 14 commits into
CapSoftware:mainfrom
AatmanAJ:perf/share-abr-ladder
Open

AatmanAJ wants to merge 14 commits into
CapSoftware:mainfrom
AatmanAJ:perf/share-abr-ladder

Conversation

@AatmanAJ

@AatmanAJ AatmanAJ commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Share links play one progressive MP4. Desktop uploads are muxed with -c copy and web uploads are transcoded without a bitrate cap or keyframe interval. A viewer on a slow link, or watching at 1.25x, waits at the start and stalls partway through, and nothing can step quality down. The media server already has an fMP4 HLS ladder with separate AAC audio (hls-ladder.ts / hls-ladder-encode.ts), but only the developer API uses it.

Change

  • Share ladders (workflows/share-hls-ladder.ts): once processing (process-video), desktop finalization or an edit finishes, a separate workflow is queued. It calls the existing /video/ladder endpoint with maxTier: "1080p", rungs 1080p/720p/360p (only up to the source size), includeAudio: true (one AAC track that every rung shares) and priority: "bulk". hlsMasterKey is written only after the job completes, and only if the MP4 it was encoded from is still the one viewers get. If anything fails (start rejected, server busy for ~20 min, job error, timeout, MP4 replaced twice), the video stays on its progressive MP4.
    • It encodes from the key viewers actually play (resolveRecordingObjectKey, which includes loudness-levelled audio). For videos the media server may still level (3 to 900 s), it first waits out the levelling window (≤150 s) so the ladder audio matches the MP4.
    • Skipped for clips under 10 s, sources whose short side is under 509 px (the media server would plan a single rung), non-S3 storage, and segmented or legacy sources. Videos that already exist are not touched.
  • Stale keys: edits clear hlsMasterKey and queue a new ladder. Duplicates drop it. Admin reprocess and replacement already reset source.
  • Media server: the ladder admits priority: "bulk" jobs only while at least one slot stays free. /video/process transcodes now get -maxrate/-bufsize caps based on the output's short side (matching the ladder tiers) and a 2 s keyframe interval (-g) on both libx264 and NVENC. Upload helpers accept cacheControl and send it as a header (S3 does not sign Cache-Control, so older workers keep working).
  • Caching: desktop outputs (their paths are unique to each recording generation) and ladder files are uploaded with public, max-age=31536000, immutable. Web result.mp4 and its screenshot are rewritten in place by reprocess and replacement, so they are left as they were.
  • Completion polling: desktop finalize polls at 2 s → 5 s → 15 s instead of a flat 15 s, so transcription and ladder dispatch start sooner.

Contract with #4832

  • source.hlsMasterKey = <ownerId>/<videoId>/.recording/outputs/share-hls/<24-hex>/<32-hex>/master.m3u8. The first hex is sha256(sourceKey + "\n" + ETag), and the second is a random id for each start, so no two jobs ever write the same files. It starts with the <ownerId>/<videoId>/ prefix, uses only [A-Za-z0-9_./-] and has no .. or empty segments, as getHlsMasterKey requires.
  • Every ladder file sits next to master.m3u8: audio.m3u8, audio.m4s, {1080p,720p,360p}.m3u8, {…}.m4s. The master playlist references <rung>.m3u8 and URI="audio.m3u8" as bare relative names (HLS_PLAYLIST_FILE_PATTERN). The rendition playlists are single-file byte-range playlists whose segment and EXT-X-MAP URIs are <rung>.m4s (HLS_MEDIA_FILE_PATTERN). These names come unchanged from encodeHlsLadder.
  • perf(web): cache and preserve adaptive playback playlists #4832 adds the same hlsMasterKey: Schema.optional(Schema.String) field to Video.source in packages/web-domain/src/Video.ts. The edit is identical to the one in this PR, so whichever merges second rebases without a conflict.
  • The key is present only when every file has been uploaded. Ladder files never change once written: a replaced MP4, or a new start, gets a new prefix and a new key.

Audit items #1, #15, #23 (workflow uploads) and #30.

Verification

  • bun run typecheck, biome check on the changed files
  • vitest run __tests__/unit (746 files pass), including the new share-hls-ladder.test.ts: publish, failure fallback, unavailable or busy media server, audio-level wait, MP4 replaced during the encode, skip cases. Also updated finalize, media-processing, duplicate and edit-replacement tests.
  • bun test media-server: nvenc-encoder (VBV tiers, portrait cap, -g), hls-ladder, media-video.integration, and a new ladder-bulk-admission test for bulk admission and the Cache-Control upload header; lint:tests passes

Confidence Score: 5/5RetriggerView in Greptile

The PR appears safe to merge; the latest changes prevent retries from sharing ladder files.

Summary

Adds HLS generation after video processing, desktop finalization, and edits, while keeping the progressive MP4 as the fallback.

  • Share videos get an adaptive ladder when the current MP4 is ready.
  • Video transcodes cap their bitrate and use shorter keyframe gaps.
  • Desktop finalization checks for finished recordings sooner.

All three previous findings are addressed. No new actionable issues were found in the latest changes.

Reviews (3) · Last reviewed commit: "fix(web): give every share ladder start ..." · Reviewed by Greptile

Portrait outputs were matched to the tier of their long side, so a
1080x1920 output got the 1440p cap. Tiers now meet at geometric
midpoints, as the HLS ladder's rungs do.
result.mp4 and its screenshot are rewritten in place by admin reprocess
and replacement, so a year-long immutable header would keep serving the
old bytes. Only generation-unique desktop outputs and ladder files are
marked immutable.
The ladder ran inline at the end of the processing and finalize
workflows, holding them (and prefetch cleanup) for up to three hours,
and wrote to a fixed key next to result.mp4 that went stale when the
MP4 was replaced or loudness-levelled.

Processing and finalize now queue a separate workflow. It waits out the
audio-levelling window, encodes from the MP4 viewers actually play, and
writes under a prefix derived from that MP4's key and ETag, so ladder
files are immutable. hlsMasterKey is only recorded once the job is
complete and the MP4 is unchanged; any failure leaves the video on its
progressive MP4. Short clips, single-rung sources and non-S3 storage
are skipped.
Edits publish a new MP4 while spreading the old source, and duplicates
copy the source verbatim, so both carried an hlsMasterKey for other
content. Edits clear it and queue a fresh ladder; duplicates start on
their MP4.
@vercel

vercel Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
cap-status Skipped Skipped Dec 4, 2026 10:56pm UTC

@vercel
vercel Bot temporarily deployed to Preview – cap-status December 4, 2026 22:47 Inactive
Comment on lines +354 to +357
await tx
.update(videos)
.set({ source: { ...video.source, hlsMasterKey: target.masterKey } })
.where(eq(videos.id, Video.VideoId.make(videoId)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Ladder completion breaks active edits

Publishing hlsMasterKey changes the whole source while an active edit still expects its saved value. matchesEditOperation then rejects edit callbacks and throws “Edit operation has been replaced.” Failed-edit cleanup uses the same comparison, so the recording can remain stuck as processing.

Skip ladder publication while an edit is active, or make the edit checks ignore ladder-only changes.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/workflows/share-hls-ladder.ts
Line: 354-357

Comment:
**Ladder completion breaks active edits**

Publishing `hlsMasterKey` changes the whole `source` while an active edit still expects its saved value. `matchesEditOperation` then rejects edit callbacks and throws “Edit operation has been replaced.” Failed-edit cleanup uses the same comparison, so the recording can remain stuck as processing.

Skip ladder publication while an edit is active, or make the edit checks ignore ladder-only changes.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

🤖 claude-opus-5-5 on behalf of Aatman AJ Jain

Fixed in 8b30279. persistShareHlsLadder now checks video_uploads inside the same FOR UPDATE transaction, and an active edit always has that row. While the row exists it returns busy and leaves source untouched. The workflow re-checks every 60 s for up to an hour. When the edit commits, it has already replaced the MP4, cleared hlsMasterKey and queued its own ladder, so a ladder that waited behind it is dropped instead of re-encoded. Tests: waits for an edit holding the video… and leaves a ladder to the edit that replaced the MP4… in share-hls-ladder.test.ts.

Comment thread apps/web/workflows/share-hls-ladder.ts Outdated
Comment on lines +304 to +309
if (
started.status === "busy" ||
started.status === "unreachable" ||
started.status === "unconfirmed"
)
return { status: "retry" };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Retries overwrite immutable ladder files

An unconfirmed start can mean the server accepted the job but its response was lost. Retrying creates another job with the same upload keys. Both encoders can then overwrite playlists and media independently, even after one job finishes.

The results can differ, including when NVENC falls back to libx264. Cached playlists can then point at the wrong byte ranges. Do not resend an uncertain start without a way to recover or deduplicate the accepted job.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/workflows/share-hls-ladder.ts
Line: 304-309

Comment:
**Retries overwrite immutable ladder files**

An `unconfirmed` start can mean the server accepted the job but its response was lost. Retrying creates another job with the same upload keys. Both encoders can then overwrite playlists and media independently, even after one job finishes.

The results can differ, including when NVENC falls back to `libx264`. Cached playlists can then point at the wrong byte ranges. Do not resend an uncertain start without a way to recover or deduplicate the accepted job.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

🤖 claude-opus-5-5 on behalf of Aatman AJ Jain

Fixed in 8b30279. Only busy (a 503 refusal) and unreachable (the connection never opened) are retried now. unconfirmed ends the run and the video stays on its MP4, so two jobs can never write the same prefix. Test: does not resend a start the media server may have accepted (one /video/ladder call, no hlsMasterKey).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

🤖 claude-opus-5-5 on behalf of Aatman AJ Jain

Follow-up in 3ac8cd9 for the proxy case your summary raised: a start answered 502/503/504 may still have been accepted. Every start now uploads under its own share-hls/<source-fingerprint>/<random-run-id>/ directory (shareHlsRunPrefix). A retried start can no longer touch a running job's files, and hlsMasterKey names the files of the job that was actually polled to completion. unconfirmed starts are still not retried. Test: gives every start its own prefix so a refused start cannot share files.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This resolves the overwrite concern. Each start attempt gets a distinct shareHlsRunPrefix, so even if a 502/503/504 response masks an accepted job, that job cannot overwrite files from a later attempt. The workflow persists only the master key for the job it actually polls to completion, and still does not retry unconfirmed starts. The new test covers the distinct-prefix behavior.

} finally {
for (const jobId of held) jobManager.deleteJob(jobId);
}
}, 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 New timeout exceeds frozen allowance

The new test adds a 180_000 per-test timeout. AGENTS.md forbids new raised per-test timeouts and says existing allowances may only decrease. This file already has six allowed occurrences in scripts/test-lint/oxlintrc.json; the added test makes seven.

Split the fast admission/header checks from encoding, or wait for a completion signal without another raised timeout. This repository requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/media-server/src/__tests__/lib/hls-ladder-route.integration.test.ts
Line: 338

Comment:
**New timeout exceeds frozen allowance**

The new test adds a `180_000` per-test timeout. `AGENTS.md` forbids new raised per-test timeouts and says existing allowances may only decrease. This file already has six allowed occurrences in `scripts/test-lint/oxlintrc.json`; the added test makes seven.

Split the fast admission/header checks from encoding, or wait for a completion signal without another raised timeout. This repository requirement must be satisfied before merging.

**Context Used:** AGENTS.md ([source](https://github.com/capsoftware/cap/blob/main/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

🤖 claude-opus-5-5 on behalf of Aatman AJ Jain

Fixed in acbb6ab. The route integration suite is back to its origin/main contents. The bulk-admission 503 check and the Cache-Control upload-header checks now live in ladder-bulk-admission.test.ts. That file does no encode and raises no timeouts. node scripts/test-lint/run.mjs passes (950 files).

…e suite

Editing the route integration suite made test lint check its existing
raised timeouts. The bulk admission and Cache-Control checks need no
encode, so they live in a fast file of their own.
@vercel
vercel Bot temporarily deployed to Preview – cap-status December 4, 2026 22:55 Inactive
An edit fences the video on its starting source, so recording the
ladder mid-edit made the edit's callbacks reject. The ladder now waits
while an upload row holds the video and leaves the result to the edit
if it replaced the MP4.

An unconfirmed start may be running; resending it could have two jobs
write the same immutable files, so it is no longer retried.
@vercel
vercel Bot temporarily deployed to Preview – cap-status December 4, 2026 22:56 Inactive
@AatmanAJ

AatmanAJ commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Note

🤖 claude-opus-5-5 on behalf of Aatman AJ Jain

All three Greptile findings are fixed on 8b302797d9:

  • Active edits (P1): the ladder no longer writes source while a video_uploads row holds the video. It waits, and if the edit replaced the MP4 it leaves the new ladder to the edit, which already clears the old key and queues its own.
  • Uncertain starts (P1): unconfirmed starts are no longer resent, so two jobs can never write the same immutable prefix.
  • Test timeout allowance (P2): the route integration suite is unchanged from main. The new checks live in a fast ladder-bulk-admission.test.ts.

Also fixed: the Lint tests CI failure (same cause as the P2). The only remaining non-green check is Vercel Authorization required for a fork PR.

Contract with #4832 is unchanged: source.hlsMasterKey = <owner>/<video>/.recording/outputs/share-hls/<hash>/master.m3u8, with sibling rendition and audio files referenced by bare relative names. Video.ts carries the same schema field #4832 adds.

Verified: bun run typecheck, Biome, lint:tests, all web unit tests, and the media-server nvenc-encoder / hls-ladder / ladder-bulk-admission tests.

@greptileai review

A start the proxy answered with 502/503/504 may still have been accepted.
Each start now writes under a fresh run directory below the source
fingerprint, so a retried start can never overwrite files of a job that
is still running, and the recorded key names the files of the job that
was polled.
@vercel

vercel Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

@AatmanAJ is attempting to deploy a commit to the Cap Software Inc Team on Vercel.

A member of the Team first needs to authorize it.

@AatmanAJ

AatmanAJ commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Note

🤖 claude-opus-5-5 on behalf of Aatman AJ Jain

Pushed 3ac8cd9 for the remaining point in the 4/5 summary (a retry after a proxy error hiding an accepted job). Each ladder start now writes under its own run directory, so retried starts never share or overwrite files. The PR body has the updated hlsMasterKey format: <owner>/<video>/.recording/outputs/share-hls/<fingerprint>/<run>/master.m3u8. It still meets #4832's prefix, character and relative-URI checks.

Re-verified: bun run typecheck, Biome, lint:tests, and all web unit tests (746 files).

@greptileai review

This branch was previously deployed

1 inactive (outdated) deployment
Preview – cap-status — 8b302797 Deployed Dec 4, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant