Skip to content

feat(playback): improve web subtitles and track selection - #362

Merged
Quick104 merged 35 commits into
mainfrom
fix/subtitles
Jul 10, 2026
Merged

Quick104 merged 35 commits into
mainfrom
fix/subtitles

Conversation

@zZebrahz

@zZebrahz zZebrahz commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Subtitle delivery and web playback had several related reliability and UX gaps:

  • PGS sidecar requests could repeatedly pay for a slow whole-file demux, while the web player lacked a reliable final path for bitmap subtitles
  • plain-text cues could freeze or select the wrong language after stream reloads, seeks, quality changes, or the 4K fallback selected another file version
  • audio selection had the same alternate-version hazard: carrying a raw ordinal into a differently ordered file could select another language
  • pre-play selections did not consistently persist or round-trip forced-subtitle behavior
  • subtitle placement, HUD interaction, and codec-derived subtitle/audio labels produced confusing or cluttered presentation

Changes

Extraction and playback

  • add a bounded, concurrency-safe cache for extracted PGS subtitle tracks, including background warming and cached window reads for clients that consume .sup sidecars
  • support PGS/DVD/DVB in the web player through server-side bitmap burn-in, with client capability negotiation for burn-in-only formats
  • preserve progressive flushing through request logging and metrics wrappers while retaining the latest main branch's ResponseController unwrapping
  • align encoded transcode starts with declared segment boundaries and keep subtitle timing stable across copy-mode restarts
  • rebuild plain-text subtitle tracks after stream URL changes and recover cleanly from failed subtitle window fetches

Selection reliability

  • pin generated subtitle URLs to the media file whose track inventory produced them, preventing an index from being reinterpreted as another language after an effective-file switch
  • remap bitmap burn-in selections by stable track traits when the 4K guard selects an alternate version
  • remap audio selections by stable signature and language when alternate versions order or encode tracks differently
  • roll back failed burn-in selections instead of leaving the UI in a broken active state
  • persist explicit pre-play subtitle choices and allow Auto to clear the saved override
  • preserve the effective forced-subtitle preference when replacing a stored track selection

Web experience

  • apply configurable size, position, and background controls to plain-text cues (SRT/VTT); subtitle delay applies to plain text and ASS/SSA
  • preserve authored ASS/SSA styling through JASSUB and authored PGS/DVD/DVB appearance through FFmpeg bitmap burn-in
  • scale and position plain-text cues against the rendered video, keep Lower Third within its 16:9 reference frame, and anchor Bottom to the player window
  • lift plain-text cues above the visible HUD and hide the HUD immediately when the pointer leaves the player
  • show stable saved subtitle selections in the pre-play controls
  • display language plus friendly subtitle format names such as English · SRT, suppress codec-only duplicate titles, and keep forced/default/accessibility state in compact badges
  • format audio summaries language-first (for example English · EAC3 · 5.1) while keeping meaningful container titles in the detail line

All /api/v1 changes are additive. Existing PGS .sup sidecar URLs remain available; DVD/DVB burn-in-only tracks are advertised only when the client explicitly declares support.

Part of #296.
Part of #297.

Validation

  • go test ./internal/api/middleware
  • docker run --rm silo-server:pr-review go test ./internal/api/handlers ./internal/jellycompat -run '<focused review regressions>' -count=1
  • GOCACHE=/tmp/silo-go-cache go test ./internal/playback ./internal/userdb
  • cd web && pnpm run lint — 0 errors; 159 existing warnings
  • cd web && pnpm run format:check
  • cd web && pnpm exec vitest run src/lib/subtitleAppearance.test.ts src/pages/ItemDetail/components/prePlaySelection.test.ts src/player/hooks/usePlaybackSession.test.ts src/player/hooks/useSubtitleTracks.test.tsx src/player/hooks/useTranscodeQuality.test.tsx src/player/utils/subtitleCodecs.test.ts
  • cd web && pnpm run build
  • make verify-local-paths
  • git diff --check origin/main...HEAD

Risk and follow-up

  • bitmap burn-in requires video encoding and therefore carries the expected transcode cost
  • size, position, and background controls affect plain-text cues only; delay also affects ASS/SSA, while ASS/SSA and bitmap tracks retain their authored appearance
  • bitmap PGS/DVD/DVB delay is not adjustable because the subtitles are composited into the encoded video
  • the PGS cache adds bounded disk usage and uses source path, modification time, and track identity for invalidation
  • cross-version audio remapping prefers exact signature, then language, then the effective file default when no equivalent track exists
  • subtitle layout and compact-label changes are web-only and should receive a final visual pass at narrow and fullscreen player sizes

AI-use disclosure

AI-assisted implementation and review: OpenAI Codex helped diagnose the live playback failures, implement the fixes, resolve the rebase overlap, and run the validation above. Human testing covered the affected web playback and track-selection flows.

Summary by CodeRabbit

  • New Features
    • Added server-side bitmap subtitle burn-in support, including PGS, DVD, and DVB formats.
    • Added subtitle extraction caching for faster repeat playback and windowed subtitle requests.
    • Subtitle and audio selections can now be saved and reset for movies and series.
    • Improved subtitle sizing, positioning, track labels, and playback synchronization.
  • Bug Fixes
    • Preserved forced-subtitle preferences when updating other subtitle settings.
    • Improved subtitle and audio track matching across alternate media versions.
    • Improved seek alignment and recovery during stream or audio-track changes.
    • Streaming responses now flush correctly for smoother playback.

zZebrahz added 28 commits July 9, 2026 20:10
…d sparse cue windows

- Rebase already-loaded cues in place when streamOriginSeconds changes
  (copy-mode session restart) instead of leaving them offset by the delta.
- Stop inferring end-of-input from where a window's cues stop; only the
  known media duration marks EOF, so a dialogue gap no longer silently
  ends prefetching for the rest of playback.
- Anchor the first window fetch to the intended start position (resume
  target or pending seek) while the element still reports currentTime=0,
  and reset coverage on forward seeks past the fetched window.
…t boundary

A mid-segment start (resume, seek restart, audio switch) spawned ffmpeg at
the raw seek position while labeling its first segment with the grid number,
whose synthetic-manifest start is up to one segment earlier. hls.js aligns
the first fragment's content to that declared position, shifting the whole
session's timeline late by seek mod segment_duration (0-2s): subtitles
trail dialogue by a constant per-session offset and progress/resume
positions drift by the same amount.

Snap the ffmpeg start position down to the segment boundary for encoded
sessions so declared and produced timelines match exactly; the player
still seeks to the precise requested position. Copy-mode sessions serve
ffmpeg's real manifest and keep the raw seek.
…ppers

Streamed subtitle extracts (and any progressive response) flush per chunk
via an http.Flusher assertion, but none of the status-capturing middleware
wrappers implemented Flush, so the assertion failed and cues sat in Go's
response buffer until ffmpeg finished. On large remuxes where a 600s window
takes 20s+ to demux, captions appeared only when the whole window completed
instead of within the first seconds.

Give every wrapper a Flush() (satisfies plain assertions, including chi's
Compress) and Unwrap() (satisfies http.ResponseController). The jellycompat
image-proxy tag rewriter flushes only in passthrough mode since it buffers
JSON bodies for rewriting. Regression test asserts the API chain forwards
Flush end to end.
…ings

Port the tvOS/iOS bitmap-cue styling to the web player. libpgs now decodes
in worker mode but draws to a hidden source canvas on the main thread; a
compositor detects cue regions from the frame's alpha channel and re-places
them on a visible overlay canvas per the shared subtitle appearance
settings: size scale (with the 0.85 authored-size compensation), vertical
position preset (dialogue-band cues only — floating signs keep authored
placement, matching the Apple implementation), and the background box.
Font family, text color, and outline are baked into the source pixels and
remain inapplicable.
…nce frame

The initial port used silo-apple's 30/1080 bottom margin and video-relative
lower-third/top anchors; the web text overlay anchors to a 16:9 reference
frame with 7%/18% offsets that extends into the letterbox for wide content.
Use the same anchors so PGS dialogue lands exactly where SRT text does.
Replace the authored-size ladder (0.85 × font-size ratio) with per-cue
text-line matching: the region detector reports the tallest text line inside
each cue, and the compositor scales the cue so one line of bitmap text
renders at the same pixel height as the SRT overlay's font at the current
preset. Authored size differences between discs no longer leak through;
upscaling is capped at 2.5× to keep small bitmaps from going blurry.
…latency

PGS extracts always demuxed the source from byte 0, so starting a large
remux mid-file meant minutes before the first bitmap cue. The web player
now opts in to windowed extraction (?windowed=1&position=&duration=) and
re-points libpgs at a fresh window on seeks and near coverage end; ffmpeg
input-side -ss with -copyts keeps absolute source timestamps. Without the
explicit opt-in the endpoint behaves byte-identically, so Apple/Android
and other single-fetch consumers are unaffected. ASS remains
unconditionally non-windowed (its header only exists at offset 0).
Every selection of an embedded PGS track re-ran a full ffmpeg extract
that demuxes the entire source file from byte 0 — minutes for a large
remux — and responses were Cache-Control: no-store, so repeat
selections, re-watches, and multiple viewers all paid full price.

Add a disk cache for full-track .sup extracts under
<transcode_dir>/subtitle-cache, created lazily:

- Keyed by source path hash + subtitle stream ordinal + source
  mtime+size (encoded in the filename), so a replaced source file
  implicitly invalidates its entries; the source is stat'ed on every
  lookup.
- Cache miss: ffmpeg stdout is teed to the response (first viewer
  still streams progressively, first-byte latency unchanged) and into
  a temp file that is fsynced and atomically renamed into the cache
  on clean ffmpeg exit. Any error — ffmpeg failure, client disconnect,
  tee write failure, or the source changing mid-extract — discards
  the temp file, so a partial entry is never served.
- Cache hit: served via http.ServeContent (Range support,
  Content-Length, Last-Modified from the source mtime) with a
  revalidatable Cache-Control instead of no-store.
- Concurrent requests for the same in-flight track run their own
  uncached extract (mutex + in-flight key set) rather than blocking
  on another client's connection.
- Scan-on-commit LRU eviction under a 2 GiB cap (recency tracked by
  bumping entry mtime on hit; atime is unreliable under relatime),
  plus sweep of crash-orphaned .part temp files.
- Windowed PGS requests (?windowed=) bypass the cache in both
  directions: their output covers only a slice of the track.

Both the integrated API handler and the standalone proxy subtitle
path share the same playback.SubtitleCache.ServeSUPExtract helper.
VTT (already windowed and fast) and ASS (small) stay uncached. No
API surface change.

AI-use disclosure: implemented with Claude Code.
Silence errcheck on the cache-hit defer and the test's simulated
disk-full Close.

AI-use disclosure: implemented with Claude Code.
…rack

Windowed PGS requests bypassed the cache entirely, so every window fetch
re-demuxed the multi-GB original file. Now a windowed miss kicks off a
detached background warm (full-track extract into the cache, at most 2
concurrent server-wide, coalesced with client-driven fills), and once the
entry exists windowed extracts read the 15-80MB cached .sup instead —
seeks and re-enables become near-instant after the first load. Verified
empirically that ffmpeg preserves absolute PTS when windowing a sup input.
When a PGS track is enabled (or a seek lands outside the fetched window),
extraction takes seconds and dialogue could play unsubtitled. The player
now pauses until the renderer's parsed data covers the playhead — tracked
via libpgs' parsed-timestamp watermark, the exact predicate it renders
by — showing a "Loading subtitles…" indicator after 500ms. User
play/pause always wins over the hold, a 20s safety timeout prevents
stranding playback, and background prefetch never pauses. If future
libpgs versions reshape the observed internals the hook degrades to the
old play-through behavior.
Draining a windowed extract from the source reads the full interleaved
container across the window (~1GB per 100s of remux on measured
hardware); a 3600s window cost ~12GB of reads per fetch while cold. Once
the server cache is warm a window costs milliseconds regardless of size,
so smaller windows only add trivially cheap re-fetches.
The web player rendered PGS client-side via libpgs, which required
extracting the .sup track — a cold ffmpeg demux that took seconds even
windowed, since c:s copy still reads the whole interleaved container up
to the playhead. Every other server (Plex, Jellyfin default, Emby) burns
image subtitles into the video instead, and that is the only path with
no per-seek extraction cost.

Selecting a bitmap subtitle (PGS/DVD/DVB) now restarts the transcode
with subtitle_burn_in at the current aligned position, reusing the same
restart machinery as an audio/quality switch so the segment-boundary
timeline alignment holds. The server composites the decoded subtitle
onto the video with an overlay filter_complex graph (libass's subtitles=
filter is text-only); overlay runs at native resolution before any
target scaling, and hardware pipelines round-trip through CPU like the
text path. Burn-in forces a video encode, so copy-video recipes are
upgraded to h264 both client- and server-side.

Text subtitles keep the instant, styled, client-side path. The .sup
streaming endpoints, cache, and windowing are retained for the Apple
client, which renders PGS natively. The now-dead web PGS stack
(usePGSSubtitles, pgsPlacement, libpgs dep) is removed.

Tradeoff: bitmap subtitles no longer honor web appearance settings
(baked into the video) and toggling one restarts the transcode
(~1-2s buffering), matching Plex behavior.
Selecting an SRT track that turned off bitmap burn-in restarted the
transcode, and the client TextTrack built in that same moment was
orphaned when the <video> element reloaded, so the subtitles never
rendered (and a seek could not recover the dead track). Rebuild the
text track once the new stream settles, gated on the burn-in-off
transition so quality/audio switches and copy-mode seek restarts keep
their subtitles without a needless re-extract.
The text subtitle overlay sat at z-20, above the controls layer (z-10),
so cues painted over the bottom HUD and cluttered the control bar. Drop
it to z-[5] — above the video, below the controls — so the HUD paints
over the cues while it is visible. When controls are hidden the whole
controls layer is opacity-0, so cues remain fully visible.
…ible

Rather than hiding bottom-anchored cues behind the HUD, raise them just
above the control bar (measured height + a small gap) whenever the bar
is visible in the foreground player, then settle them back when it
hides. The bar is a roughly fixed pixel height while the cue offset
scales with the player, so the bar is measured via ResizeObserver
rather than hardcoded. Top-anchored cues never collide with the bottom
HUD, so they stay put. z-[5] is retained as a safety so any residual
overlap tucks behind the bar.
Starting playback with a persisted bitmap subtitle fired transcode/start
twice within milliseconds: the auto-start effect dispatched before
subtitle auto-selection restored the burn-in, whose effect then forced a
second start. The first request was already on the wire (no abort signal
was passed to fetch), so the server spawned an ffmpeg only to kill it
for the second start — visible in production as an ffmpeg exit error
~1ms after every such session start, and slowing time to first frame.

Defer the network dispatch by one macrotask so back-to-back restart
calls in a tick collapse into a single request carrying the final
parameters; state updates stay synchronous. Pass the abort signal into
playerFetch so a superseded in-flight request is actually cancelled,
and drop any deferred dispatch on unmount so a stray transcode/start
cannot land after the session's exit DELETE.
Movie pre-play subtitle selectors were missing the effective defaults
(including per-item overrides saved from a previous play) that episodes
and watch payloads already resolve. Extract applyToItemDetail/
applyToWatchDetail helpers and apply defaults for movies in
buildMediaItemDetail. The SubtitlesPopover now also eagerly loads
downloaded subtitles when the saved preference points at one so the
closed trigger's Auto summary reflects the override.
Replace fixed rem font sizes with px values defined at a 720px 16:9
reference height, scaled proportionally with the actually-rendered
video (object-fit: contain) so subtitles keep the same relative size
as the window grows or shrinks, with a 12px legibility floor. Rename
useSubtitlePositionStyle to useSubtitleLayout, returning both the
position style and the font scale, and add unit tests for the
appearance helpers.
…verride

A manual in-player subtitle selection persists as an 'always' override
for that movie/series, but nothing in the UI could undo it — auto
selection stayed pinned to the chosen track forever. Choosing 'Auto' in
the pre-play subtitles popover now also deletes the stored preference
(movie content ID / episode series ID) and invalidates item details so
profile-level auto selection applies again.
Choosing a track (or Off) in the pre-play subtitles popover only lived
in component state: it applied to that playback session but vanished on
returning to the detail page. Persist it through PUT /subtitle-prefs —
the same 'always'/'off' override a manual in-player selection saves —
keyed by movie content ID or episode series ID, and invalidate item
details so the effective defaults reflect it immediately.
…ummaries

A stored per-item override displayed as 'Auto: <language>', hiding both
that an override exists and which track it is. The pre-play subtitle
pill now shows the resolved track directly (name with (SDH)/(Forced)
markers plus format, skipping markers the name already carries), the
matching list row gets the checkmark instead of Auto, and the Auto row
reads 'Reset to profile defaults'. Subtitle, audio, edition, and
version pill summaries also truncate much later (max-w-44/sm:max-w-64).
…ndow fetches

Three failure modes could silently freeze or stop web text subtitles:

- A stream restart (seek-triggered transcode restart, quality/audio
  switch) reloads the <video> element and can orphan the programmatic
  TextTrack — cuechange stops firing and the last cue freezes on screen.
  Only the PGS-burn-in-off transition rebuilt the track. Now every
  settled stream URL change bumps the generation, and the rebuild
  carries loaded cues (converted back to source time) and window
  coverage over so it costs no refetch.
- The sliding-window fetcher committed windowEnd before the fetch ran,
  so a failed or hung window counted as covered and was never retried —
  subtitles silently stopped for up to 10 minutes. Coverage now commits
  only after the window streams in fully; failures leave the range
  uncovered and retry after a 5s backoff.
- A hung extraction (one fetch in flight at a time, no deadline) blocked
  every future window for the session. Reads now arm a 30s stall timer
  that aborts a response which stops delivering chunks; slow-but-
  progressing streams keep resetting it.

Diagnosed from a session where ffmpeg took 69s to stream one subtitle
window and a transcode restart landed mid-fetch, freezing the active cue.
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: afa5da4a-a535-4835-81de-2a2f1f61a114

📥 Commits

Reviewing files that changed from the base of the PR and between c690fc7 and f1fe48e.

📒 Files selected for processing (16)
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_subtitle_urls_test.go
  • internal/api/handlers/playback_test.go
  • internal/api/handlers/stream.go
  • internal/api/handlers/stream_test.go
  • internal/api/middleware/flush_test.go
  • internal/api/middleware/metrics.go
  • internal/api/middleware/request_logger.go
  • internal/jellycompat/image_proxy_tags.go
  • internal/jellycompat/image_proxy_tags_test.go
  • web/src/pages/ItemDetail/components/prePlaySelection.test.ts
  • web/src/player/components/VideoPlayer.tsx
  • web/src/player/hooks/usePlaybackSession.ts
  • web/src/player/hooks/useTranscodeQuality.test.tsx
  • web/src/player/hooks/useTranscodeQuality.ts
  • web/src/player/types.ts

📝 Walkthrough

Walkthrough

The PR adds server-side bitmap subtitle burn-in, cached and windowed PGS extraction, subtitle source-file remapping, aligned transcode restarts, persistent subtitle preferences, improved frontend subtitle rendering, and HTTP flush propagation through response-writer wrappers.

Changes

Subtitle playback and transcoding

Layer / File(s) Summary
Subtitle extraction and caching
internal/playback/subtitle_cache.go, internal/playback/subtitle_stream.go, internal/api/handlers/stream.go, internal/proxy/server.go
PGS extraction supports windowed requests, cached full-track .sup files, source-file validation, background warming, and cache-backed serving.
Bitmap burn-in and transcode contracts
internal/api/handlers/playback.go, internal/playback/transcode.go, internal/playback/recipecard.go, internal/transcodenode/server.go, internal/streamtoken/token.go
Subtitle media-file identifiers and codecs flow through playback and transcode requests; bitmap tracks are remapped and burned in through overlay filter graphs with aligned seek positions.
Frontend subtitle playback lifecycle
web/src/player/hooks/*, web/src/player/components/VideoPlayer.tsx, web/src/lib/subtitleAppearance.ts
The player sends bitmap burn-in capability data, coalesces burn-in restarts, preserves subtitle cues across stream reloads, retries failed windows, and scales subtitle layout to the rendered video.
Subtitle preference persistence and selection
internal/api/handlers/subtitle_prefs.go, web/src/hooks/queries/subtitles.ts, web/src/pages/ItemDetail/*, web/src/player/utils/subtitleCodecs.ts
Forced-subtitle overrides are preserved, selections can be saved or reset for movies and series, and subtitle/audio summaries and labels are reformatted.
Streaming response compatibility
internal/api/middleware/*, internal/activitylog/middleware.go, internal/jellycompat/*
Response wrappers now forward Flush(), expose wrapped writers where needed, and commit implicit 200 OK responses before flushing.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.17% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and describes the main subtitle and track-selection focus of the changeset.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/subtitles

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@zZebrahz zZebrahz changed the title feat(subtitles): improve web playback, caching, and preferences feat(playback): improve web subtitles and track selection Jul 10, 2026
@zZebrahz
zZebrahz marked this pull request as ready for review July 10, 2026 03:51

@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: c690fc7b4d

ℹ️ 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 internal/api/handlers/playback.go Resolved

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/api/handlers/stream.go (1)

216-220: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Missing file == nil guard risks a nil-pointer panic.

GetByID returns (nil, nil) for a not-found file in this codebase — every other caller guards it (HandleSubtitleFonts Line 383, HandleChangeAudioTrack Line 1937, HandleStartTranscode Line 2500). Here only err is checked, so a (nil, nil) result falls through to len(file.ExternalSubtitles) at Line 222 and panics.

🛡️ Proposed fix
 	file, err := h.fileResolver.GetByID(r.Context(), fileID)
-	if err != nil {
+	if err != nil || file == nil {
 		writeError(w, http.StatusNotFound, "not_found", "Media file not found")
 		return
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/stream.go` around lines 216 - 220, Guard the result of
fileResolver.GetByID in the relevant stream handler by treating both an error
and a nil file as not found. Update the existing condition to check err != nil
|| file == nil before accessing file.ExternalSubtitles, and return the same
not-found response.
internal/api/handlers/playback.go (1)

2110-2136: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Align the offloaded audio-switch restart seek before sending it to the node. This branch still forwards req.Position as SeekSeconds, while the other transcode-start paths snap to alignedSeekSeconds(...). Using the raw position here can start ffmpeg mid-segment and drift playback by seek mod segmentDuration; pass the aligned seek instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/playback.go` around lines 2110 - 2136, Use
alignedSeekSeconds(...) rather than the raw req.Position when assigning
SeekSeconds in the TranscodeStartRequest construction within the audio-switch
restart branch. Ensure the same segment-duration alignment used by the other
transcode-start paths is applied before sending the request to the node.
🧹 Nitpick comments (1)
web/src/pages/ItemDetail/components/prePlaySelection.test.ts (1)

54-75: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test for the forced marker path in formatSubtitlePillSummary.

The hearingImpaired path is tested but the forced: true branch (line 89 of prePlaySelection.ts) is not covered. A single test case would verify the "(Forced)" marker renders correctly.

🧪 Suggested test addition
   it("keeps accessibility markers in the compact summary", () => {
     expect(
       formatSubtitlePillSummary({
         label: "SDH",
         languageLabel: "English",
         codec: "subrip",
         hearingImpaired: true,
       }),
     ).toBe("English (SDH) · SRT");
   });
+
+  it("keeps forced markers in the compact summary", () => {
+    expect(
+      formatSubtitlePillSummary({
+        label: "Forced",
+        languageLabel: "English",
+        codec: "subrip",
+        forced: true,
+      }),
+    ).toBe("English (Forced) · SRT");
+  });
 });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/pages/ItemDetail/components/prePlaySelection.test.ts` around lines 54
- 75, Add a test in the formatSubtitlePillSummary describe block covering
forced: true, using representative subtitle metadata and asserting the result
includes the "(Forced)" marker alongside the language and formatted codec.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/api/middleware/metrics.go`:
- Around line 77-80: Update statusWriter.Flush to mark the response as written
with the implicit 200 status before calling the underlying http.Flusher.Flush;
reuse the existing status-tracking fields and behavior in
statusWriter.WriteHeader to ensure later WriteHeader calls cannot overwrite the
status already sent.

In `@internal/api/middleware/request_logger.go`:
- Around line 108-111: Update requestStatusWriter.Flush to mark the response as
having written the implicit HTTP 200 status before calling the underlying
http.Flusher.Flush; ensure wroteHeader and the recorded status are set
consistently so later WriteHeader calls cannot replace the status logged for the
already-committed response.

In `@internal/jellycompat/image_proxy_tags.go`:
- Around line 60-66: Update compatImageProxyTagResponseWriter.Flush to infer
passthrough from the response Content-Type headers before returning, forwarding
pre-body flushes for non-JSON responses such as text/event-stream while
retaining buffering for JSON responses. Reuse the same content-type
classification logic as Write, if available, to keep behavior consistent.

In `@web/src/player/components/VideoPlayer.tsx`:
- Around line 1574-1578: Update hideControlsOnMouseLeave and its duplicate at
the alternate location to hide controls only when playback is active; preserve
visibility while paused so the play button remains available. Reuse the existing
playing-state indicator and keep timer cleanup behavior unchanged.

In `@web/src/player/hooks/useTranscodeQuality.ts`:
- Around line 482-489: Update setSubtitleBurnIn to use a ref containing the
latest requested quality instead of the render-time activeQualityId when calling
switchQuality, ensuring coalesced burn-in restarts preserve pending quality
changes. Keep the ref synchronized wherever quality is requested, and add a
regression test covering a quality switch and subtitle burn-in occurring in the
same tick, verifying the requested quality is retained.

---

Outside diff comments:
In `@internal/api/handlers/playback.go`:
- Around line 2110-2136: Use alignedSeekSeconds(...) rather than the raw
req.Position when assigning SeekSeconds in the TranscodeStartRequest
construction within the audio-switch restart branch. Ensure the same
segment-duration alignment used by the other transcode-start paths is applied
before sending the request to the node.

In `@internal/api/handlers/stream.go`:
- Around line 216-220: Guard the result of fileResolver.GetByID in the relevant
stream handler by treating both an error and a nil file as not found. Update the
existing condition to check err != nil || file == nil before accessing
file.ExternalSubtitles, and return the same not-found response.

---

Nitpick comments:
In `@web/src/pages/ItemDetail/components/prePlaySelection.test.ts`:
- Around line 54-75: Add a test in the formatSubtitlePillSummary describe block
covering forced: true, using representative subtitle metadata and asserting the
result includes the "(Forced)" marker alongside the language and formatted
codec.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cdd76878-7eb7-438f-a9a3-5b7c2950ca00

📥 Commits

Reviewing files that changed from the base of the PR and between eb2b9da and c690fc7.

⛔ Files ignored due to path filters (1)
  • web/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (57)
  • internal/activitylog/middleware.go
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_subtitle_urls_test.go
  • internal/api/handlers/playback_test.go
  • internal/api/handlers/stream.go
  • internal/api/handlers/stream_test.go
  • internal/api/handlers/subtitle_prefs.go
  • internal/api/handlers/subtitle_prefs_test.go
  • internal/api/middleware/flush_test.go
  • internal/api/middleware/metrics.go
  • internal/api/middleware/request_logger.go
  • internal/api/router.go
  • internal/catalog/detail.go
  • internal/jellycompat/image_proxy_tags.go
  • internal/jellycompat/logging.go
  • internal/playback/audio_select.go
  • internal/playback/audio_select_test.go
  • internal/playback/prepare_file.go
  • internal/playback/recipecard.go
  • internal/playback/recipecard_test.go
  • internal/playback/subtitle_cache.go
  • internal/playback/subtitle_cache_test.go
  • internal/playback/subtitle_stream.go
  • internal/playback/subtitle_stream_test.go
  • internal/playback/subtitles.go
  • internal/playback/transcode.go
  • internal/playback/transcode_args_test.go
  • internal/proxy/server.go
  • internal/streamtoken/token.go
  • internal/transcodenode/server.go
  • web/package.json
  • web/src/hooks/queries/subtitles.ts
  • web/src/lib/subtitleAppearance.test.ts
  • web/src/lib/subtitleAppearance.ts
  • web/src/pages/ItemDetail/EpisodeContent.test.tsx
  • web/src/pages/ItemDetail/EpisodeContent.tsx
  • web/src/pages/ItemDetail/MovieContent.test.tsx
  • web/src/pages/ItemDetail/MovieContent.tsx
  • web/src/pages/ItemDetail/components/AudioTracksPopover.tsx
  • web/src/pages/ItemDetail/components/SubtitlesPopover.tsx
  • web/src/pages/ItemDetail/components/VersionDropdown.tsx
  • web/src/pages/ItemDetail/components/prePlaySelection.test.ts
  • web/src/pages/ItemDetail/components/prePlaySelection.ts
  • web/src/player/components/SubtitleMenu.tsx
  • web/src/player/components/VideoPlayer.tsx
  • web/src/player/hooks/usePGSSubtitles.test.tsx
  • web/src/player/hooks/usePGSSubtitles.ts
  • web/src/player/hooks/usePlaybackSession.test.ts
  • web/src/player/hooks/usePlaybackSession.ts
  • web/src/player/hooks/useSubtitleLayout.ts
  • web/src/player/hooks/useSubtitleTracks.test.tsx
  • web/src/player/hooks/useSubtitleTracks.ts
  • web/src/player/hooks/useTranscodeQuality.test.tsx
  • web/src/player/hooks/useTranscodeQuality.ts
  • web/src/player/types.ts
  • web/src/player/utils/subtitleCodecs.test.ts
  • web/src/player/utils/subtitleCodecs.ts
💤 Files with no reviewable changes (3)
  • web/package.json
  • web/src/player/hooks/usePGSSubtitles.test.tsx
  • web/src/player/hooks/usePGSSubtitles.ts

Comment thread internal/api/middleware/metrics.go Resolved

@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: 3494118f46

ℹ️ 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 internal/api/handlers/playback.go Resolved
@Quick104
Quick104 merged commit e57faa1 into main Jul 10, 2026
2 of 3 checks passed
@Quick104
Quick104 deleted the fix/subtitles branch July 10, 2026 12:21
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 10, 2026
Quick104 added a commit that referenced this pull request Jul 10, 2026
* fix(player): keep text subtitles in sync across copy-mode restarts and sparse cue windows

- Rebase already-loaded cues in place when streamOriginSeconds changes
  (copy-mode session restart) instead of leaving them offset by the delta.
- Stop inferring end-of-input from where a window's cues stop; only the
  known media duration marks EOF, so a dialogue gap no longer silently
  ends prefetching for the rest of playback.
- Anchor the first window fetch to the intended start position (resume
  target or pending seek) while the element still reports currentTime=0,
  and reset coverage on forward seeks past the fetched window.

* fix(playback): align encoded transcode start with the declared segment boundary

A mid-segment start (resume, seek restart, audio switch) spawned ffmpeg at
the raw seek position while labeling its first segment with the grid number,
whose synthetic-manifest start is up to one segment earlier. hls.js aligns
the first fragment's content to that declared position, shifting the whole
session's timeline late by seek mod segment_duration (0-2s): subtitles
trail dialogue by a constant per-session offset and progress/resume
positions drift by the same amount.

Snap the ffmpeg start position down to the segment boundary for encoded
sessions so declared and produced timelines match exactly; the player
still seeks to the precise requested position. Copy-mode sessions serve
ffmpeg's real manifest and keep the raw seek.

* fix(api): forward http.Flusher through response-writer middleware wrappers

Streamed subtitle extracts (and any progressive response) flush per chunk
via an http.Flusher assertion, but none of the status-capturing middleware
wrappers implemented Flush, so the assertion failed and cues sat in Go's
response buffer until ffmpeg finished. On large remuxes where a 600s window
takes 20s+ to demux, captions appeared only when the whole window completed
instead of within the first seconds.

Give every wrapper a Flush() (satisfies plain assertions, including chi's
Compress) and Unwrap() (satisfies http.ResponseController). The jellycompat
image-proxy tag rewriter flushes only in passthrough mode since it buffers
JSON bodies for rewriting. Regression test asserts the API chain forwards
Flush end to end.

* feat(player): PGS subtitles honor size, position, and background settings

Port the tvOS/iOS bitmap-cue styling to the web player. libpgs now decodes
in worker mode but draws to a hidden source canvas on the main thread; a
compositor detects cue regions from the frame's alpha channel and re-places
them on a visible overlay canvas per the shared subtitle appearance
settings: size scale (with the 0.85 authored-size compensation), vertical
position preset (dialogue-band cues only — floating signs keep authored
placement, matching the Apple implementation), and the background box.
Font family, text color, and outline are baked into the source pixels and
remain inapplicable.

* fix(player): anchor PGS position presets to the text overlay's reference frame

The initial port used silo-apple's 30/1080 bottom margin and video-relative
lower-third/top anchors; the web text overlay anchors to a 16:9 reference
frame with 7%/18% offsets that extends into the letterbox for wide content.
Use the same anchors so PGS dialogue lands exactly where SRT text does.

* feat(player): size PGS cues to match the text subtitle line height

Replace the authored-size ladder (0.85 × font-size ratio) with per-cue
text-line matching: the region detector reports the tallest text line inside
each cue, and the compositor scales the cue so one line of bitmap text
renders at the same pixel height as the SRT overlay's font at the current
preset. Authored size differences between discs no longer leak through;
upscaling is capped at 2.5× to keep small bitmaps from going blurry.

* feat(subtitles): opt-in windowed PGS extraction to cut mid-file load latency

PGS extracts always demuxed the source from byte 0, so starting a large
remux mid-file meant minutes before the first bitmap cue. The web player
now opts in to windowed extraction (?windowed=1&position=&duration=) and
re-points libpgs at a fresh window on seeks and near coverage end; ffmpeg
input-side -ss with -copyts keeps absolute source timestamps. Without the
explicit opt-in the endpoint behaves byte-identically, so Apple/Android
and other single-fetch consumers are unaffected. ASS remains
unconditionally non-windowed (its header only exists at offset 0).

* feat(playback): cache extracted PGS subtitle tracks

Every selection of an embedded PGS track re-ran a full ffmpeg extract
that demuxes the entire source file from byte 0 — minutes for a large
remux — and responses were Cache-Control: no-store, so repeat
selections, re-watches, and multiple viewers all paid full price.

Add a disk cache for full-track .sup extracts under
<transcode_dir>/subtitle-cache, created lazily:

- Keyed by source path hash + subtitle stream ordinal + source
  mtime+size (encoded in the filename), so a replaced source file
  implicitly invalidates its entries; the source is stat'ed on every
  lookup.
- Cache miss: ffmpeg stdout is teed to the response (first viewer
  still streams progressively, first-byte latency unchanged) and into
  a temp file that is fsynced and atomically renamed into the cache
  on clean ffmpeg exit. Any error — ffmpeg failure, client disconnect,
  tee write failure, or the source changing mid-extract — discards
  the temp file, so a partial entry is never served.
- Cache hit: served via http.ServeContent (Range support,
  Content-Length, Last-Modified from the source mtime) with a
  revalidatable Cache-Control instead of no-store.
- Concurrent requests for the same in-flight track run their own
  uncached extract (mutex + in-flight key set) rather than blocking
  on another client's connection.
- Scan-on-commit LRU eviction under a 2 GiB cap (recency tracked by
  bumping entry mtime on hit; atime is unreliable under relatime),
  plus sweep of crash-orphaned .part temp files.
- Windowed PGS requests (?windowed=) bypass the cache in both
  directions: their output covers only a slice of the track.

Both the integrated API handler and the standalone proxy subtitle
path share the same playback.SubtitleCache.ServeSUPExtract helper.
VTT (already windowed and fast) and ASS (small) stay uncached. No
API surface change.

AI-use disclosure: implemented with Claude Code.

* fix(playback): check Close error returns in subtitle cache paths

Silence errcheck on the cache-hit defer and the test's simulated
disk-full Close.

AI-use disclosure: implemented with Claude Code.

* feat(playback): warm PGS cache in background and window from cached track

Windowed PGS requests bypassed the cache entirely, so every window fetch
re-demuxed the multi-GB original file. Now a windowed miss kicks off a
detached background warm (full-track extract into the cache, at most 2
concurrent server-wide, coalesced with client-driven fills), and once the
entry exists windowed extracts read the 15-80MB cached .sup instead —
seeks and re-enables become near-instant after the first load. Verified
empirically that ffmpeg preserves absolute PTS when windowing a sup input.

* feat(player): hold playback while PGS subtitle cues load

When a PGS track is enabled (or a seek lands outside the fetched window),
extraction takes seconds and dialogue could play unsubtitled. The player
now pauses until the renderer's parsed data covers the playhead — tracked
via libpgs' parsed-timestamp watermark, the exact predicate it renders
by — showing a "Loading subtitles…" indicator after 500ms. User
play/pause always wins over the hold, a 20s safety timeout prevents
stranding playback, and background prefetch never pauses. If future
libpgs versions reshape the observed internals the hook degrades to the
old play-through behavior.

* perf(player): shrink uncached PGS window to 600s

Draining a windowed extract from the source reads the full interleaved
container across the window (~1GB per 100s of remux on measured
hardware); a 3600s window cost ~12GB of reads per fetch while cold. Once
the server cache is warm a window costs milliseconds regardless of size,
so smaller windows only add trivially cheap re-fetches.

* feat(subtitles): burn in PGS/bitmap subtitles for the web player

The web player rendered PGS client-side via libpgs, which required
extracting the .sup track — a cold ffmpeg demux that took seconds even
windowed, since c:s copy still reads the whole interleaved container up
to the playhead. Every other server (Plex, Jellyfin default, Emby) burns
image subtitles into the video instead, and that is the only path with
no per-seek extraction cost.

Selecting a bitmap subtitle (PGS/DVD/DVB) now restarts the transcode
with subtitle_burn_in at the current aligned position, reusing the same
restart machinery as an audio/quality switch so the segment-boundary
timeline alignment holds. The server composites the decoded subtitle
onto the video with an overlay filter_complex graph (libass's subtitles=
filter is text-only); overlay runs at native resolution before any
target scaling, and hardware pipelines round-trip through CPU like the
text path. Burn-in forces a video encode, so copy-video recipes are
upgraded to h264 both client- and server-side.

Text subtitles keep the instant, styled, client-side path. The .sup
streaming endpoints, cache, and windowing are retained for the Apple
client, which renders PGS natively. The now-dead web PGS stack
(usePGSSubtitles, pgsPlacement, libpgs dep) is removed.

Tradeoff: bitmap subtitles no longer honor web appearance settings
(baked into the video) and toggling one restarts the transcode
(~1-2s buffering), matching Plex behavior.

* fix(player): rebuild text subtitle track when turning off PGS burn-in

Selecting an SRT track that turned off bitmap burn-in restarted the
transcode, and the client TextTrack built in that same moment was
orphaned when the <video> element reloaded, so the subtitles never
rendered (and a seek could not recover the dead track). Rebuild the
text track once the new stream settles, gated on the burn-in-off
transition so quality/audio switches and copy-mode seek restarts keep
their subtitles without a needless re-extract.

* fix(player): render web subtitles behind the control HUD

The text subtitle overlay sat at z-20, above the controls layer (z-10),
so cues painted over the bottom HUD and cluttered the control bar. Drop
it to z-[5] — above the video, below the controls — so the HUD paints
over the cues while it is visible. When controls are hidden the whole
controls layer is opacity-0, so cues remain fully visible.

* feat(player): lift web subtitles above the control bar while it's visible

Rather than hiding bottom-anchored cues behind the HUD, raise them just
above the control bar (measured height + a small gap) whenever the bar
is visible in the foreground player, then settle them back when it
hides. The bar is a roughly fixed pixel height while the cue offset
scales with the player, so the bar is measured via ResizeObserver
rather than hardcoded. Top-anchored cues never collide with the bottom
HUD, so they stay put. z-[5] is retained as a safety so any residual
overlap tucks behind the bar.

* fix(player): coalesce same-tick transcode restarts into one dispatch

Starting playback with a persisted bitmap subtitle fired transcode/start
twice within milliseconds: the auto-start effect dispatched before
subtitle auto-selection restored the burn-in, whose effect then forced a
second start. The first request was already on the wire (no abort signal
was passed to fetch), so the server spawned an ffmpeg only to kill it
for the second start — visible in production as an ffmpeg exit error
~1ms after every such session start, and slowing time to first frame.

Defer the network dispatch by one macrotask so back-to-back restart
calls in a tick collapse into a single request carrying the final
parameters; state updates stay synchronous. Pass the abort signal into
playerFetch so a superseded in-flight request is actually cancelled,
and drop any deferred dispatch on unmount so a stray transcode/start
cannot land after the session's exit DELETE.

* fix(catalog): resolve effective subtitle defaults for movie item details

Movie pre-play subtitle selectors were missing the effective defaults
(including per-item overrides saved from a previous play) that episodes
and watch payloads already resolve. Extract applyToItemDetail/
applyToWatchDetail helpers and apply defaults for movies in
buildMediaItemDetail. The SubtitlesPopover now also eagerly loads
downloaded subtitles when the saved preference points at one so the
closed trigger's Auto summary reflects the override.

* feat(player): scale subtitle font size with the rendered video

Replace fixed rem font sizes with px values defined at a 720px 16:9
reference height, scaled proportionally with the actually-rendered
video (object-fit: contain) so subtitles keep the same relative size
as the window grows or shrinks, with a 12px legibility floor. Rename
useSubtitlePositionStyle to useSubtitleLayout, returning both the
position style and the font scale, and add unit tests for the
appearance helpers.

* fix(player): satisfy strict index checks in transcode quality test

* feat(player): let the pre-play Auto option clear the saved subtitle override

A manual in-player subtitle selection persists as an 'always' override
for that movie/series, but nothing in the UI could undo it — auto
selection stayed pinned to the chosen track forever. Choosing 'Auto' in
the pre-play subtitles popover now also deletes the stored preference
(movie content ID / episode series ID) and invalidates item details so
profile-level auto selection applies again.

* feat(player): persist pre-play subtitle selections as the item override

Choosing a track (or Off) in the pre-play subtitles popover only lived
in component state: it applied to that playback session but vanished on
returning to the detail page. Persist it through PUT /subtitle-prefs —
the same 'always'/'off' override a manual in-player selection saves —
keyed by movie content ID or episode series ID, and invalidate item
details so the effective defaults reflect it immediately.

* feat(ui): show the saved subtitle override and richer pre-play pill summaries

A stored per-item override displayed as 'Auto: <language>', hiding both
that an override exists and which track it is. The pre-play subtitle
pill now shows the resolved track directly (name with (SDH)/(Forced)
markers plus format, skipping markers the name already carries), the
matching list row gets the checkmark instead of Auto, and the Auto row
reads 'Reset to profile defaults'. Subtitle, audio, edition, and
version pill summaries also truncate much later (max-w-44/sm:max-w-64).

* fix(player): recover text subtitles from stream reloads and failed window fetches

Three failure modes could silently freeze or stop web text subtitles:

- A stream restart (seek-triggered transcode restart, quality/audio
  switch) reloads the <video> element and can orphan the programmatic
  TextTrack — cuechange stops firing and the last cue freezes on screen.
  Only the PGS-burn-in-off transition rebuilt the track. Now every
  settled stream URL change bumps the generation, and the rebuild
  carries loaded cues (converted back to source time) and window
  coverage over so it costs no refetch.
- The sliding-window fetcher committed windowEnd before the fetch ran,
  so a failed or hung window counted as covered and was never retried —
  subtitles silently stopped for up to 10 minutes. Coverage now commits
  only after the window streams in fully; failures leave the range
  uncovered and retry after a 5s backoff.
- A hung extraction (one fetch in flight at a time, no deadline) blocked
  every future window for the session. Reads now arm a 30s stall timer
  that aborts a response which stops delivering chunks; slow-but-
  progressing streams keep resetting it.

Diagnosed from a session where ffmpeg took 69s to stream one subtitle
window and a transcode restart landed mid-fetch, freezing the active cue.

* fix(playback): keep subtitle selections stable across file changes

* fix(web): clarify subtitle labels and positioning

* fix(player): hide HUD when pointer leaves

* fix(web): tidy subtitle track badges

* fix(playback): remap audio tracks across file versions

* fix(web): tidy audio track labels

* docs(playback): clarify bitmap subtitle appearance

* fix(playback): preserve selection state on restart

* fix(http): preserve response state across flushes

* fix(web): preserve pending quality for burn-in

* fix(playback): preserve subtitle inventory identity

---------

Co-authored-by: Quick <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants