Skip to content

perf(web): cache and preserve adaptive playback playlists - #4832

Open
AatmanAJ wants to merge 9 commits into
CapSoftware:mainfrom
AatmanAJ:perf/playlist-caching-abr
Open

AatmanAJ wants to merge 9 commits into
CapSoftware:mainfrom
AatmanAJ:perf/playlist-caching-abr

Conversation

@AatmanAJ

@AatmanAJ AatmanAJ commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Share playback revalidated completed playlists on every load, collapsed legacy multivariant HLS masters to one rendition, and proxied media/preview responses with cache-defeating headers. Long playlists also required serial or unbounded signing work.

What changed

  • Completed VOD/master playlists are gzip-compressible and cache for 60s (public only for credential-free public access, otherwise private); growing/live segment playlists remain no-store.
  • Legacy multivariant masters are preserved, reordered for a faster starting rendition, and their child playlists are routed through signed rendition endpoints.
  • Added defensive source.hlsMasterKey ladder master/rendition/media routing with signed fMP4 URLs and optional short playlists.
  • The share page plays non-segmented sources with a non-empty source.hlsMasterKey through the HLS player via videoType=ladder-master; all other sources are unchanged.
  • Reported realistic segment-master bandwidth, codecs, and resolution; bounded playlist signing/head concurrency and parallelized legacy signing.
  • Storage proxy media responses now use private range caching with Accept-Ranges and ETag/conditional handling.
  • Preview and thumbnail URLs use windowed signing and public/private cache headers, with stored preview keys avoiding a blocking HEAD lookup.

Verification

  • bun run typecheck
  • bun run biome check --write on all touched files
  • bunx vitest run for the playlist, storage object, thumbnail, and preview route unit tests, plus the share-page ladder dispatch test (151 focused tests passing)

Confidence Score: 5/5RetriggerView in Greptile

The PR appears safe to merge; all previous findings are fixed and no new actionable issues were found.

Summary

The PR adds playlist caching and compression, preserves adaptive HLS choices, and improves media, preview, and thumbnail caching.

  • Share playback keeps available HLS quality choices and uses stored ladders.
  • Long segment playlists reduce how much signing work happens up front.
  • Media and image responses support private range caching and conditional requests.
  • Preview and thumbnail URLs can reuse signed links and safe cache responses.

Reviews (3) · Last reviewed commit: "fix(web): keep hlsMasterKey when decodin..." · Reviewed by Greptile

@vercel

vercel Bot commented Dec 3, 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:44pm UTC

@vercel
vercel Bot temporarily deployed to Preview – cap-status December 3, 2026 23:16 Inactive
Comment thread apps/web/app/api/playlist/route.ts Outdated
const START_MAX_SHORT_SIDE = 1080;
const HLS_PLAYLIST_FILE_PATTERN = /^[A-Za-z0-9_-]+\.m3u8$/;
const HLS_MEDIA_FILE_PATTERN = /^[A-Za-z0-9_-]+\.m4s$/;
const SEGMENTS_FILE_PATTERN = /^(video|audio)\/segment_(\d{3})\.m4s$/;

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 Long recordings stop playing

With segments=short, recordings that reach segment 1000 get URLs such as video/segment_1000.m4s. This pattern accepts exactly three digits, so segments-file returns 404 and playback stops or seeking fails. padStart(3) sets a minimum width, not a maximum. Accept three or more digits and keep the existing manifest membership check.

Suggested change
const SEGMENTS_FILE_PATTERN = /^(video|audio)\/segment_(\d{3})\.m4s$/;
const SEGMENTS_FILE_PATTERN = /^(video|audio)\/segment_(\d{3,})\.m4s$/;
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/app/api/playlist/route.ts
Line: 72

Comment:
**Long recordings stop playing**

With `segments=short`, recordings that reach segment 1000 get URLs such as `video/segment_1000.m4s`. This pattern accepts exactly three digits, so `segments-file` returns 404 and playback stops or seeking fails. `padStart(3)` sets a minimum width, not a maximum. Accept three or more digits and keep the existing manifest membership check.

```suggestion
const SEGMENTS_FILE_PATTERN = /^(video|audio)\/segment_(\d{3,})\.m4s$/;
```

---

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 d5c350e. SEGMENTS_FILE_PATTERN now accepts \d{3,}, and the parsed file must round-trip to the canonical padStart(3) name (so segment_0001 / segment_01 still 404) before the existing manifest membership check runs. The short playlist builder and the file route share one segmentsFileName helper. New tests in segment-playlist-route.test.ts list and redirect video/segment_1000.m4s from a 1000-segment manifest and reject non-canonical or unlisted names.

Comment on lines +108 to +114
headers: {
...getHeaders(origin),
"Cache-Control":
query.public && !request.headers.get("cookie")
? "public, max-age=300, s-maxage=300"
: "private, max-age=300",
},

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 Cached thumbnails mix allowed origins

The newly cacheable thumbnail response needs Vary: Origin. getHeaders(origin) reflects each trusted origin, but shared caches are not told to separate those responses. If a shared cache reuses a response from https://cap.so for https://cap.link, the browser blocks it because Access-Control-Allow-Origin names the wrong origin.

Suggested change
headers: {
...getHeaders(origin),
"Cache-Control":
query.public && !request.headers.get("cookie")
? "public, max-age=300, s-maxage=300"
: "private, max-age=300",
},
headers: {
...getHeaders(origin),
Vary: "Origin",
"Cache-Control":
query.public && !request.headers.get("cookie")
? "public, max-age=300, s-maxage=300"
: "private, max-age=300",
},
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/app/api/thumbnail/route.ts
Line: 108-114

Comment:
**Cached thumbnails mix allowed origins**

The newly cacheable thumbnail response needs `Vary: Origin`. `getHeaders(origin)` reflects each trusted origin, but shared caches are not told to separate those responses. If a shared cache reuses a response from `https://cap.so` for `https://cap.link`, the browser blocks it because `Access-Control-Allow-Origin` names the wrong origin.

```suggestion
			headers: {
				...getHeaders(origin),
				Vary: "Origin",
				"Cache-Control":
					query.public && !request.headers.get("cookie")
						? "public, max-age=300, s-maxage=300"
						: "private, max-age=300",
			},
```

---

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 043b956. The thumbnail response now sends Vary: Origin, and the public scope additionally requires the video to have no password (query.password), so password-protected videos never get shared-cache headers even before the cookie check. thumbnail-published-output.test.ts covers public, password-protected, private and signed-in cases and asserts Vary: Origin on each.

Comment on lines +100 to +105
if (
body.byteLength >= COMPRESSED_PLAYLIST_MIN_BYTES &&
acceptEncoding.toLowerCase().includes("gzip")
) {
return HttpServerResponse.uint8Array(gzipSync(body), {
headers: { ...headers, "Content-Encoding": "gzip" },

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 Disabled gzip is still sent

Checking whether Accept-Encoding contains gzip also accepts gzip;q=0, which explicitly forbids gzip. Playlists over 1 KB are then compressed despite the client's stated restriction. Parse the encoding preferences and only compress when gzip has a positive quality value.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/app/api/playlist/route.ts
Line: 100-105

Comment:
**Disabled gzip is still sent**

Checking whether `Accept-Encoding` contains `gzip` also accepts `gzip;q=0`, which explicitly forbids gzip. Playlists over 1 KB are then compressed despite the client's stated restriction. Parse the encoding preferences and only compress when gzip has a positive quality value.

---

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 e3514b0. acceptsGzip parses Accept-Encoding entries with their q values: an explicit gzip/x-gzip entry wins, otherwise * applies, and compression only happens when the resulting quality is above 0. Tests cover gzip, br, gzip;q=0.5 and * (compressed) and gzip;q=0, gzip; q=0.0, br, *;q=0, identity and empty (plain text, still Vary: Accept-Encoding).

@richiemcilroy

Copy link
Copy Markdown
Member

Thanks @AatmanAJ, this looks like a useful change.

Before we can merge it:

  • Greptile is at 4/5 on the latest commit; it needs 5/5. Open points:
    • P1: with segments=short, recordings that reach segment 1000 stop playing
    • P2: the newly cacheable thumbnail response needs Vary: Origin
    • P2: Accept-Encoding: gzip;q=0 still gets gzip

Once those are sorted, request a re-review from Greptile.

AatmanAJ added a commit to AatmanAJ/Cap that referenced this pull request Dec 4, 2026
The ladder-master playlist route moves to CapSoftware#4832 with its endpoint.
@AatmanAJ
AatmanAJ force-pushed the perf/playlist-caching-abr branch from 2d6038f to d4ae850 Compare December 4, 2026 22:36
@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

@richiemcilroy all three open points are fixed on the new head (rebased onto current main, d4ae850):

  • P1, segments=short past segment 999: d5c350e. File names accept three or more digits but must match the canonical padStart(3) name, and the manifest membership check is unchanged. Tested with a 1000-segment recording.
  • P2, thumbnail Vary: Origin: 043b956. Added Vary: Origin. The public cache scope now also excludes password-protected videos explicitly, on top of the existing no-cookie requirement.
  • P2, gzip;q=0 still compressed: e3514b0. Accept-Encoding is parsed with q-values, so gzip is only sent when gzip (or *) has a positive quality.

Also in this PR now: d4ae850 moves the share-page caller for the ladder endpoint here from #4835, so the endpoint and its only caller ship together. A non-segmented source with a non-empty source.hlsMasterKey (read with optional chaining) plays through the HLS player via videoType=ladder-master. Everything else keeps its current source. Covered by share-video-ladder-dispatch.test.ts.

Private and password-protected videos never get public cache headers on any route in this PR. Local checks: bun run typecheck, biome on the changed files, lint:tests, and all 10 changed vitest files (151 tests) pass.

@greptileai review

Comment thread apps/web/app/api/playlist/route.ts Outdated
Comment on lines +244 to +245
const key = (video.source as { hlsMasterKey?: unknown }).hlsMasterKey;
if (typeof key !== "string" || !key.endsWith(".m3u8")) return null;

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 videos cannot play

For a video whose stored source includes hlsMasterKey, the share page selects ladder-master. But getByIdForViewing loads the video through VideosRepo.decodeRow, which calls Video.Video.decodeSync. The source schema does not include hlsMasterKey, so decoding removes it. This check then returns null, and the playlist request returns 404 instead of playing the video.

Add hlsMasterKey to the shared source schema so the page and API agree.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/app/api/playlist/route.ts
Line: 244-245

Comment:
**Ladder videos cannot play**

For a video whose stored source includes `hlsMasterKey`, the share page selects `ladder-master`. But `getByIdForViewing` loads the video through `VideosRepo.decodeRow`, which calls `Video.Video.decodeSync`. The `source` schema does not include `hlsMasterKey`, so decoding removes it. This check then returns `null`, and the playlist request returns 404 instead of playing the video.

Add `hlsMasterKey` to the shared source schema so the page and API agree.

---

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

Valid. Fixed in 5ba1d3c. hlsMasterKey: Schema.optional(Schema.String) is now part of the shared Video.source schema, so VideosRepo.decodeRow keeps it and getHlsMasterKey reads video.source.hlsMasterKey directly instead of casting. The route tests previously returned plain objects and skipped decoding. The new test in legacy-playlist-route.test.ts serves the video through Video.Video.decodeSync and plays ladder-master then ladder-rendition end to end. Without the schema field it fails as you described.

@AatmanAJ

AatmanAJ commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Note

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

Greptile's new P1 on d4ae850 was valid: the decoded Video schema dropped source.hlsMasterKey, so ladder-master returned 404. Fixed in 5ba1d3c by adding the field to the shared schema, with a route test that decodes the video like VideosRepo does. The earlier three findings stay fixed.

@greptileai review

This branch was previously deployed

1 inactive deployment
Preview – cap-status — 5ba1d3c7 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.

2 participants