Skip to content

fix(playback): speed bitmap subtitle startup - #751

Merged
Quick104 merged 8 commits into
mainfrom
cursor/critical-bug-management-f2e3
Aug 25, 2026
Merged

Quick104 merged 8 commits into
mainfrom
cursor/critical-bug-management-f2e3

Conversation

@cursor

@cursor cursor Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A — narrow fix

The web player auto-selects subtitle tracks before playback. Bitmap formats such as PGS, DVD, and DVB cannot be rendered by the browser, so selecting one forces server-side burn-in and a video transcode.

The previous fix protected HDR playback by starting without the bitmap track and applying it through a replan. That avoided a terminal start when conversion was unavailable, but it also exposed the first stream before the replan completed. The viewer saw playback begin, reload, and begin again. On the shared development deployment, that sequence took roughly 10 seconds (/playback/start 3.43 s plus the first /replan 5.87 s).

Approach

The opening request now includes the selected bitmap subtitle, so the normal path produces the final transport once and never reloads it. If that request is terminal because the server cannot perform the required conversion, the web client cleans it up and performs one fresh subtitle-free start with a new playback-attempt ID. Playback remains available and the viewer gets the existing subtitle-specific notice.

Startup latency is reduced without weakening readiness guarantees:

  • Prewarms the browser's asynchronous Media Capabilities probe while the app shell is open, so Play can reuse the result.
  • Uses one-second HLS fragments and a one-fragment publication window for fresh hardware bitmap burn-in only. CPU transcodes, restarts, and ordinary HLS retain their existing cushions.
  • Keeps the one-second cadence consistent across resume/seek alignment, remote and local transcode requests, reconstruction recipes, and playback session state.
  • Compacts large signed synthetic HLS playlists by carrying the repeated query once through HLS variable substitution. Small playlists retain their simpler form.
  • Retains the legacy bitmap codec aliases (pgssub, dvdsub, vobsub, and dvbsub).

No v1 response shape or client capability contract changes. Apple, Android, and jellycompat require no coordinated client change.

Shared-dev browser validation

Tested through the real web UI against the shared backend with an explicitly selected bitmap subtitle. Each measurement started after using the player's Exit action so the previous transcode was cleaned up.

Measurement Three clean runs
Usable player controls 3.088 s, 3.061 s, 3.061 s
Playback clock advancing 3.561 s, 3.794 s, 4.171 s
/playback/start 1.394 s, 1.379 s, 0.964 s
Replans 0, 0, 0

The final state was playing with captions active and no playback error. The large signed manifest request dropped from 798 ms to 10 ms after compaction.

This removes the original roughly 10-second start/reload sequence and makes the UI usable in about 3.1 seconds. The sub-second goal was not reached end to end: the safe floor for this 4K bitmap-burn-in path is still the first encoded fragment plus browser HLS buffering. An experiment that returned /playback/start earlier made the API look faster but worsened actual controls to 3.6 seconds, so it was not retained.

Validation

go build ./...
gofmt -l .
go vet ./...
golangci-lint run --new-from-merge-base="origin/main" ./...
# all passed; changed-line lint: 0 issues

go test ./internal/playback ./internal/api/handlers ./internal/transcodenode
# all passed

cd web && pnpm run lint
# exit 0; 155 repository baseline warnings, no errors

cd web && pnpm run format:check
# all matched files use Prettier code style

cd web && pnpm run build
# production build succeeded

make test-web
# Test Files 285 passed (285)
# Tests 2079 passed (2079)

make verify-settings-bindings-all
make verify-playback-fixtures
make verify-local-paths
# all passed

make test-go was also run. Every touched package passed; the complete local run ended on two unchanged internal/jellycompat process-lock tests whose current-process identity checks fail on this macOS host. The PR's previous Go CI run was green; the new CI run remains the authoritative full-suite result.

Risks

One-second fragments create more playlist entries for bitmap burn-in sessions. The change is deliberately limited to fresh hardware burn-in, and large signed playlists are compacted to avoid transferring and parsing repeated credentials. If burn-in is unavailable, the fallback costs one failed planner attempt before starting without subtitles, but it avoids both a fatal start and a mid-playback transport reload.

AI Disclosure

  • Tool(s): Cursor Automation, OpenAI Codex
  • Model(s): Cursor Grok 4.6, GPT-5
  • Involvement: Cursor generated the initial patch. Codex performed a defect-first review, fixed legacy bitmap-codec aliases, diagnosed and removed the visible start/replan reload, implemented the terminal-only fallback, profiled the real shared-dev browser path, optimized capability probing, fragment readiness, and manifest delivery, added regression coverage, deployed the iterations, and ran the validation above.
  • Adversarial review: Verified the subtitle-bearing start and subtitle-free fallback use different playback-attempt IDs; ensured unsuccessful subtitle starts are cleaned up; retained conservative readiness for CPU encodes and restarts; kept segment duration consistent in transport planning and reconstructable session state; rejected an early-response experiment when browser timing regressed despite a faster API response; confirmed playback, active captions, zero replans, and no playback error in the browser.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

Bitmap (PGS/DVD/DVB) tracks have to be burned in on the web player.
Putting them on the opening plan forces a transcode, and HDR sources
refuse that start when tone mapping and 4K transcoding are off — the
defaults — leaving no stream to fall back to. Text subtitles still go
on the start request; bitmap selection is applied after a playable plan
exists.

Co-authored-by: Quick <[email protected]>
@Quick104
Quick104 marked this pull request as ready for review August 25, 2026 18:28

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2d688c12ec

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread web/src/pages/watchRouteHelpers.ts Outdated
Comment on lines +246 to +247
if (selectedTrack && isBitmapCodec(selectedTrack.codec)) {
continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Normalize bitmap codec aliases before sending the start

When a catalog track uses a supported legacy spelling such as pgssub, dvdsub, dvbsub, or vobsub, this condition is false because isBitmapCodec recognizes only the canonical FFmpeg names. The server explicitly normalizes those aliases and treats them as burn-in codecs in internal/playback/capabilities_v3.go:335-351 and internal/playback/subtitles.go:15-38, so the selected ordinal is still included in the initial request and an HDR title can hit the same terminal this change is intended to avoid. Use the same normalized codec family as the playback policy, or extend the web classifier and its tests to cover every server-supported alias.

Useful? React with 👍 / 👎.

@Quick104
Quick104 marked this pull request as draft August 25, 2026 18:34

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 621ff08305

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +28 to +29
"dvb_subtitle",
"dvbsub",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Defer DVB teletext from the initial start

When an auto-selected or explicit track has FFmpeg codec dvb_teletext, this set still makes isBitmapCodec return false, so buildInitialSubtitleTrackIndexes sends its ordinal on /playback/start. Fresh evidence beyond the resolved alias comment is internal/playback/subtitle_policy_v3.go:72-74 and its test at internal/playback/subtitle_policy_v3_test.go:26-42, which explicitly classify dvb_teletext as requiring bitmap burn-in. Consequently, an HDR/4K title with the default transcode or tone-mapping restrictions can still terminal the initial plan instead of starting without subtitles; include this codec in the deferred classifier and its tests.

Useful? React with 👍 / 👎.

@Quick104 Quick104 changed the title fix(web): omit bitmap subtitles from the initial playback start fix(playback): speed bitmap subtitle startup Aug 25, 2026
@Quick104
Quick104 marked this pull request as ready for review August 25, 2026 20:42

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3609eb3463

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +488 to +489
initialSubtitleErrorTitle: initialSubtitleFailure?.title ?? null,
initialSubtitleError: initialSubtitleFailure?.message ?? null,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep the subtitle fallback pinned across replans

When the bitmap-bearing start is refused and the subtitle-free fallback succeeds, any later successful quality, output-change, or recovery replan calls adoptDecision without initialSubtitleFailure, clearing these fields. WatchPage then restores the persisted subtitle mode, and VideoPlayer auto-selects the same rejected bitmap track and issues a track_change replan, producing another refusal and toast. Preserve the fallback-off marker for the lifetime of this playback session unless the viewer explicitly selects a subtitle.

Useful? React with 👍 / 👎.

@Quick104

Copy link
Copy Markdown
Contributor

Follow-up startup and playback-hardening work is now pushed in 481dc4d3e.

What changed:

  • Protocol-v3 start returns after the transport and durable session commit instead of waiting for provider scrobbling, marker/chapter scheduling, series preference writes, and live-session refresh. Immediate stop still waits for start-side effects so event ordering is preserved.
  • Planner policy reads run concurrently; successful remote-node capability inventories may be used stale while they refresh in the background; local and pooled conversion capabilities and hardware encoders warm behind startup.
  • Fresh hardware transcodes publish after two complete fragments. CPU encodes, seeks, restarts, and reconstructed generations retain the conservative three-fragment window.
  • Dolby Vision Profile 8.1 video-copy/audio-adaptation remuxes no longer carry orphaned tone-map provenance into the local or remote transport recipe.
  • The web HDR native-HLS preference is now correctly Safari-only. Chrome 151 was selecting native HLS for a rapidly growing copy-remux EVENT playlist and jumping from the requested position toward the production edge; Chromium now uses hls.js when available and retains native fallback when it is not.
  • Request-correlated startup timing logs were added so planning, local manifest readiness, remote-node startup, and bookkeeping can be separated in future measurements.

Validation added for async side-effect ordering, concurrent settings reads, fresh/reconstructed readiness windows, local and remote Dolby Vision remux recipes, Safari native HDR selection, and Chromium HDR hls.js selection.

Latest validation:

go test ./internal/api/handlers ./internal/api ./internal/playback ./internal/transcodenode -count=1
go test -race ./internal/api/handlers -run '<affected playback-v3 tests>' -count=1
cd web && pnpm vitest run src/player/utils/hlsEngine.test.ts src/player/components/VideoPlayer.test.tsx
cd web && pnpm build
make test-web
make verify-local-paths
git diff --check

All passed. The unfiltered web suite also ran 2,127 tests: 2,121 passed; the six failures are the repository's already-excluded SeasonContent and ServerStorageStep harness failures (QueryClientProvider / ResizeObserver).

The updated image is deployed to shared dev and healthy. The deployed frontend contains the Chromium/Safari engine split and loads without console errors. The automation browser had a fresh signed-out profile, so the final authenticated replay of the reported Chrome title remains a manual confirmation rather than an automated claim.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 481dc4d3eb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread web/src/player/utils/hlsEngine.ts Outdated
Comment on lines +13 to +14
/Safari\//i.test(userAgent) &&
!/(?:Chrome|Chromium|CriOS|Edg|EdgiOS|OPR|OPiOS|Firefox|FxiOS)\//i.test(userAgent)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep HDR capability evidence tied to the selected HLS engine

When a non-Safari browser both advertises native HLS and supports hls.js, buildDeliveriesV3 can advertise Dolby Vision or HDR10 based on the native media element, but this classifier makes runtime playback select hls.js instead. The playback contract explicitly does not transfer that native evidence to the hls.js MSE path, so the server may return an HDR-preserving remux that the engine actually chosen never claimed it could decode; this also affects iOS Chrome/Firefox user agents when MSE is available. Either keep those plans on native HLS or make capability advertisement use the same engine that will be selected.

Useful? React with 👍 / 👎.

Comment thread internal/api/handlers/playback_v3.go Outdated
h.ChapterThumbnailQueuer.QueuePriorityFileAtPosition(ctx, task.file.ID, task.session.Position)
}
h.maybeQueueLazyPlaybackMarkers(ctx, &task.session, &task.file)
h.persistSeriesSelectionsV3(ctx, task.userID, task.profileID, &task.file, task.audioTrackIndex)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Prevent delayed start writes from undoing track changes

If the viewer changes audio while the asynchronous start task is still blocked on scrobbling, thumbnail work, or the worker queue, the track_change replan first persists the newly selected audio index, after which this delayed call writes the initial index back over it. The next episode then loads the old audio preference even though the user's replan succeeded; serialize these preference updates or skip the stale start write once a newer selection has committed.

Useful? React with 👍 / 👎.

Comment thread internal/api/handlers/playback_v3.go Outdated
Comment on lines +1496 to +1501
waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), playbackStartSideEffectsTimeoutV3)
defer cancel()
select {
case <-done:
case <-waitCtx.Done():
slog.WarnContext(ctx, "timed out waiting for playback start side effects", "component", "api", "session", sessionID)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Wait for queued start work before emitting stop events

Under load, when all four workers are occupied and this session's start task is still queued, the stop-side timeout begins immediately while the task's own 15-second timeout begins only after a worker dequeues it. The wait can therefore expire and emit a provider pause/stop before the queued task later emits ScrobbleStart, reversing provider history and allowing post-stop bookkeeping for an ended playback session. Tie stop ordering to task completion or cancel/remove the queued task rather than using an independent fixed wait.

AGENTS.md reference: AGENTS.md:L60-L64

Useful? React with 👍 / 👎.

Comment on lines +1605 to +1606
if opts.FastStart && bitmapBurnInActive(opts) && opts.HWAccel != "" && opts.HWAccel != HWAccelNone {
return 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Exclude reconstructed sessions from the one-fragment window

When an integrated hardware transcode is reconstructed after an API restart, NewRecipeCard has persisted the original FastStart: true, and doReconstructTranscode restores it without clearing it. This condition therefore misclassifies the reconstructed bitmap-burn-in generation as fresh and serves its manifest after only one fragment, despite the stated three-fragment restart cushion, leaving the player with no encoding headroom precisely during recovery. Track fresh-generation state separately or clear FastStart on reconstruction.

AGENTS.md reference: AGENTS.md:L12-L17

Useful? React with 👍 / 👎.

Comment thread internal/playback/transcode.go Outdated
Comment on lines +244 to +246
func StartupSegmentDuration(subtitleBurnIn bool, subtitleCodec string) int {
if subtitleBurnIn && NeedsBurnIn(subtitleCodec) {
return bitmapFastStartSegmentDuration

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep one-second fragments limited to hardware burn-in

When bitmap burn-in runs on CPU—either because hardware acceleration is disabled or because a hardware tone-map start falls back to software—this function still changes the segment duration from two seconds to one. Although startupSegmentRequirement retains three fragments for CPU, that now represents only three seconds of buffered output rather than the prior six-second cushion, so a slower CPU encode can expose playback much closer to the production edge and stall shortly after startup. Pass the resolved execution mode into this choice or restore two-second fragments for CPU paths.

AGENTS.md reference: AGENTS.md:L60-L64

Useful? React with 👍 / 👎.

@Quick104

Copy link
Copy Markdown
Contributor

Scope update: the general playback-startup follow-up previously added in 481dc4d3e has been removed from this PR by 6bbdb5ae8 and moved to #761.

PR #751 is again limited to the bitmap-subtitle startup/reload work. PR #761 is based directly on current main and owns the asynchronous protocol-v3 bookkeeping, capability/encoder warmup, fresh-hardware readiness window, Dolby Vision remux recipe fix, Chromium HDR HLS correction, and associated timing/coverage.

The shared-dev image still contains the combined iteration deployed during testing; it should be treated as preview evidence for #761, not as the current #751 branch artifact.

…liases

# Conflicts:
#	docs/feature-changelog.md
#	internal/api/handlers/playback_v3.go

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1c8048b796

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

legacySuffix := "?" + rawQuery
variableSuffix := "?{$" + manifestQueryVariable + "}"
savingsPerSegment := len(legacySuffix) - len(variableSuffix)
if savingsPerSegment <= 0 || int64(segmentCount)*int64(savingsPerSegment) < minManifestQuerySubstitutionSavings || strings.ContainsAny(rawQuery, "\"\r\n") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Negotiate HLS v8 before emitting variable references

For any signed playlist whose repeated query crosses this threshold, the server unconditionally switches to EXT-X-DEFINE and advertises HLS version 8, although the playback capability contract records only generic HLS support. A third-party or older native client limited to HLS v7 can therefore reject the playlist or leave {$silo_query} unexpanded, causing every segment request to fail authentication. Gate this representation on an explicit HLS-v8/variable-substitution capability, or retain literal query strings for clients that have not advertised it.

AGENTS.md reference: AGENTS.md:L19-L22

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1685bc128b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

let initialSubtitleFailure: PlaybackSessionErrorState | null = null;
const bitmapSubtitleTrackIndex = initialBitmapSubtitleTrackIndexByFileId?.[selectedFileId];
if (!decision.playback_plan && bitmapSubtitleTrackIndex !== undefined) {
initialSubtitleFailure = describeDecisionWithoutPlan(decision);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Report a successful fallback as a subtitle failure

When bitmap burn-in is the only reason HLS or transcode capacity is needed, the first request can return client_hls_unsupported or capacity_unavailable while the subtitle-free retry successfully direct-plays the file. Saving the original terminal description here makes WatchPage toast “This browser can't play the stream” or “The server is busy” while playback is visibly working. After a successful retry, replace arbitrary first-attempt terminal text with a subtitle-specific explanation that only the selected captions were disabled.

Useful? React with 👍 / 👎.

@Quick104
Quick104 merged commit fcf910f into main Aug 25, 2026
5 checks passed
@Quick104
Quick104 deleted the cursor/critical-bug-management-f2e3 branch August 25, 2026 23:34
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