Skip to content

Subtitle appearance redesign + mid-playback toggle latency + override restore - #54

Merged
zZebrahz merged 15 commits into
mainfrom
subtitles
Jul 3, 2026
Merged

zZebrahz merged 15 commits into
mainfrom
subtitles

Conversation

@zZebrahz

@zZebrahz zZebrahz commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #53.

Holistic subtitle appearance redesign for the Apple clients plus a batch of playback-toggle and preference-restore fixes surfaced during on-device testing.

Appearance

  • Size the CoreMedia subtitle overlay to the displayed video rect (iOS/tvOS + macOS) so cues stay inside the frame in portrait / pillarboxed content; expose the video presentation size from PlayerCore and add a VideoDisplayRect aspect-fit helper.
  • Default background style to a filled box (Plex parity) instead of drop shadow.
  • Rebase the font-size preset ladder ~1.4× so large matches the old xxlarge, consistent across platforms.
  • Honor box opacity via libass BorderStyle 4; pack override-style colors in libass internal RRGGBBAA order (fixes the default box rendering as opaque dark red).

Mid-playback toggle

  • Route runtime embedded-subtitle selections through the seeked AVPlayerEmbeddedSubtitleExtractor so enabling a track mid-playback is near-instant instead of waiting for the buffered region to drain.
  • Anchor resume-time enable to pendingSkipBelowPTS so a selection applied before the playback clock is primed feeds from the right position (fixes "no subtitles until I scrub").
  • Clear the overlay layer on disable so a displayed cue doesn't linger indefinitely.

Preference restore

  • Carry the watch detail's effective subtitle mode + track signature on ItemDetail, re-match against the displayed version's tracks (same scoring as the player's SubtitleAutoResolver), and seed the detail-screen selector + playback launch index after each load, on next-up episodes, and on the post-player refresh. The remembered subtitle track now shows on re-entry instead of reverting to "Auto".

Testing

  • iOS (Silo) and tvOS (SiloTV) build clean; SiloTests full suite green (339 tests) at the time of the toggle work.
  • macOS changes syntax-checked only — the pre-existing SiloMac Nuke swiftmodule build breakage is unrelated and deferred.

Related

Summary by CodeRabbit

  • New Features

    • Subtitle preferences are now remembered and restored on detail screens and “Next Up” playback, improving consistency after dismiss/reload and across seasons/series.
    • Subtitle overlays align more precisely to the actual displayed video area, using tracked video presentation size and computed video insets.
  • Bug Fixes

    • Improved subtitle rendering and styling (background boxes, shadows, border styles) and corrected color/alpha handling.
    • Prevented stale subtitle cues when disabling tracks; enhanced embedded subtitle switching behavior.
  • Tests

    • Added coverage for subtitle styling headers, video display rect calculations, and expected font-size behavior.

zZebrahz added 13 commits July 3, 2026 10:10
Note: SiloMac does not currently build on this machine (pre-existing
Nuke swiftmodule incompatibility, also present on clean main), so this
change is syntax-checked but not compile-verified.
Point sizes now scale against the video rect (1080-line playfield)
instead of the full screen, which shrank the effective render size.
Rebase the ladder ~1.4x on all platforms.
BorderStyle 3 fills its per-glyph-run box with OutlineColour at full
opacity, so the user's background opacity (carried in BackColour) was
ignored and the box always rendered opaque. Switch to libass
BorderStyle 4: one background rect per event, filled with BackColour
(alpha honored), padded via the Shadow field.

Also give the drop-shadow style a visible 50% black shadow — its
BackColour alpha was previously fully transparent, rendering no
shadow at all.
…A order

ASS_Style struct colors use libass's internal byte-swapped format
(0xRRGGBBAA, inverted alpha in the low byte), not the ASS file
format. The old (alpha<<24)|BGR packing put the box opacity byte in
the red channel, so the translucent black default box rendered as
opaque dark red once BorderStyle 4 started drawing BackColour.

Also remove the compositor's dual-format color fallback: it existed
to rescue those mispacked colors (documented read looked transparent,
AABBGGRR read looked right) and could resurrect genuinely faded-out
glyphs as opaque. With the packing fixed, the documented RRGGBBTT
read is always correct.
…e CoreMedia path

The CoreMedia player demuxes subtitle packets in-band with video/audio
from a single forward-only demuxer that runs tens of seconds ahead of
the playhead; packets for unselected subtitle streams are discarded.
Enabling a track mid-playback only routed future packets — no seek —
so no cues appeared until the playhead crossed the toggle-time demux
head ("the buffer plays through").

Route runtime embedded selections through the existing
AVPlayerEmbeddedSubtitleExtractor instead: a dedicated subtitle-only
FFmpeg context that seeks to playhead-5s and feeds libass immediately,
throttled to 45s of read-ahead (same mechanism the AVPlayer route
already uses). The in-band pipeline still serves selections made during
open, where the demux head is at the playhead.

- extractor: configure(probe:) to skip track enumeration, stopFeeding()
  to release a slot without closing its libass track,
  selectedStreamIndex(for:) for selection state
- PlayerCore: lazy per-load extractor, re-seek on performSeek's final
  target, teardown on load reset + media teardown, selection state
  unified across both feed mechanisms for track list + stats HUD
…wPTS

The initial subtitle selection on a resumed playback races openAndDemux:
the playback clock isn't anchored to the resume position until buffering
primes, so the extractor read ~0 and fed cues from the start of the
file — no subtitles until the user scrubbed (which re-selected at the
real target). Use max(clock, pendingSkipBelowPTS), the same guard
performAudioTrackSwitch uses for the identical race, for both the
select start position and the extractor's read-ahead throttle clock.
…reMedia pump)

Disabling a track drops it from libass without a final render pass, and
the CoreMedia overlay pump bailed out when no track was active — so
whatever cue was composited on the CALayer at disable time stayed on
screen indefinitely. Clear the overlay while no track is active, exactly
as the AVPlayer route's pump already does; the per-tick clear also
covers an in-flight session-queue render re-pushing a stale image just
after the drop.
Explicit subtitle picks are persisted server-side, but the detail
screens held the selection in per-visit @State and always reopened on
"Auto" — the override looked lost on re-entry (audio was immune only
because its selector falls back to the per-version
effectiveAudioTrackIndex).

Carry the watch detail's effective subtitle mode + track signature on
ItemDetail during playback enrichment, re-match the signature against
the displayed version's track list (same scoring as the player's
SubtitleAutoResolver), and seed the selector state after each detail
load — including next-up episodes and the post-player refresh, so a
track picked inside the player shows up when the player dismisses.
Seeded picks also flow to playback launch as an explicit index, making
restore exact instead of relying on the in-player fuzzy match.
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@zZebrahz, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 53 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9d0cbdfd-6d24-49bb-897c-f6c0c54a30b9

📥 Commits

Reviewing files that changed from the base of the PR and between a8fd931 and 5bb1550.

📒 Files selected for processing (3)
  • iosApp/iosApp/Screens/Detail/DetailPlaybackFormatting.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift
  • iosApp/iosApp/Screens/Player/PlaybackPrefsResolver.swift
📝 Walkthrough

Walkthrough

This PR updates subtitle styling, sizes subtitle overlays from the displayed video rect, adds runtime embedded-subtitle switching, restores server-persisted subtitle selections in detail screens, and adjusts test project settings. Supporting tests cover subtitle styling and video rect computation.

Changes

Subtitle Redesign, Latency, and Override Restore

Layer / File(s) Summary
Subtitle styling: box background, colors, font ladder
iosApp/iosApp/Screens/Player/Subtitles/SubtitleStylingOverride.swift, iosApp/iosApp/Screens/Player/Subtitles/SubtitleAppearance.swift, iosApp/iosApp/Screens/Player/Subtitles/SubtitleRenderer.swift, iosApp/Tests/SubtitleStylingOverrideTests.swift
Updates background, shadow, border, and color parameterization; changes default subtitle background and font sizing; simplifies render-color decoding; and adds tests for header generation and color packing.
Video-relative subtitle overlay sizing
iosApp/iosApp/Screens/Player/Subtitles/VideoDisplayRect.swift, iosApp/iosApp/Screens/Player/CoreMedia/PlayerSurface.swift, iosApp/iosApp/macOS/PlayerSurface.swift, iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift, iosApp/iosApp/Screens/Player/Subtitles/SubtitleOverlayView.swift, iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerSurface.swift, iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift, iosApp/Tests/VideoDisplayRectTests.swift
Adds displayed-video rect computation, publishes video presentation size from PlayerCore, and sizes subtitle overlays from the computed rect or insets on iOS, tvOS, and macOS.
Runtime embedded-subtitle extraction for latency
iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift, iosApp/iosApp/Screens/Player/Subtitles/AVPlayerEmbeddedSubtitleExtractor.swift
Adds runtime extractor lifecycle wiring, routes embedded subtitle selection through the extractor with anchored timing, and updates selection state and overlay clearing when tracks change.
Server-remembered subtitle override restore
iosApp/iosApp/Networking/Models.swift, iosApp/iosApp/Screens/Detail/DetailPlaybackFormatting.swift, iosApp/iosApp/Screens/Detail/ItemDetailView.swift, iosApp/iosApp/Screens/Detail/ItemDetailViewModel.swift, iosApp/iosApp/tvOS/Screens/Detail/TVItemDetailView.swift
Adds effective subtitle mode and signature to item metadata, resolves server-preferred subtitle indices from stored signatures, and seeds subtitle selection state in phone and tvOS detail views.
Xcode test target build configuration
iosApp/project.yml
Enables testability for Debug and sets the iPhone test target SDK and platforms.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PlayerCore
  participant PlayerSurfaceHostView
  participant SubtitleOverlayView
  participant SubtitleRenderer
  participant VideoDisplayRect

  PlayerCore->>PlayerCore: publishVideoPresentationSize()
  PlayerCore->>PlayerSurfaceHostView: onVideoPresentationSizeChange(size)
  PlayerSurfaceHostView->>VideoDisplayRect: compute(videoSize, bounds, gravity)
  PlayerSurfaceHostView->>SubtitleOverlayView: set frame / videoInsets
  SubtitleOverlayView->>SubtitleRenderer: updateFrameSize(videoInsets)
  PlayerCore->>SubtitleRenderer: renderOnSessionQueue(videoInsets)
Loading
sequenceDiagram
  participant ItemDetailView
  participant ItemDetailViewModel
  participant DetailPlaybackFormatting
  participant AVPlayerEmbeddedSubtitleExtractor
  participant PlayerCore

  ItemDetailView->>ItemDetailViewModel: loadDetail / enrichPlaybackMetadata
  ItemDetailViewModel-->>ItemDetailView: ItemDetail(effectiveSubtitleMode, effectiveSubtitleTrackSignature)
  ItemDetailView->>DetailPlaybackFormatting: serverPreferredSubtitleIndex(version, signature, mode)
  DetailPlaybackFormatting-->>ItemDetailView: preferredSubtitleTrackIndex

  PlayerCore->>AVPlayerEmbeddedSubtitleExtractor: configure(source, probe:false)
  PlayerCore->>AVPlayerEmbeddedSubtitleExtractor: select anchored embedded track
  AVPlayerEmbeddedSubtitleExtractor-->>PlayerCore: selectedStreamIndex(slot)
Loading

Possibly related issues

Possibly related PRs

  • Silo-Server/silo-apple#30: Both PRs modify SubtitleRenderer.swift at the core render path, including frame and output handling.
  • Silo-Server/silo-apple#50: Both PRs work on server-backed subtitle selection persistence and restoration from detail metadata.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the PR’s main themes: subtitle appearance, mid-playback toggling, and restoring subtitle overrides.
Linked Issues check ✅ Passed The changes address the issue’s three goals: appearance redesign, mid-playback toggle latency, and preference restore.
Out of Scope Changes check ✅ Passed The added tests and XcodeGen tweaks support the subtitle work and do not appear unrelated to the PR objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 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 marked this pull request as draft July 3, 2026 19:07
@zZebrahz

zZebrahz commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

Need to run one last validation on tvOS

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (1)
iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift (1)

3490-3503: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Publish the presentation size on the MPEG2/software path
setupSoftwareVideoDecoder(...) only opens the decoder context, so PlayerSurface keeps seeing .zero and subtitles fall back to full-bounds sizing for MPEG2 streams. Initialize and publish the video presentation size before returning from this branch.

🤖 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 `@iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift` around lines 3490 -
3503, The MPEG2 software decode branch in PlayerCore is returning after only
opening the decoder, so the presentation size never gets published and
PlayerSurface stays at .zero. Before calling
setupSoftwareVideoDecoder(codecpar:codecparPtr:), initialize and publish the
video presentation size using the codecpar dimensions in this
AV_CODEC_ID_MPEG2VIDEO case, following the same pattern used by the hardware
paths so subtitles and layout can size correctly.
🤖 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 `@iosApp/iosApp/Screens/Detail/DetailPlaybackFormatting.swift`:
- Around line 220-255: The bestSignatureMatch logic in DetailPlaybackFormatting
and SubtitleAutoResolver can pick a subtitle track even when there is no
meaningful match signal. Update bestSignatureMatch so it only returns a
candidate when at least one strong indicator matches, such as language, label,
or an explicit non-default metadata match, instead of awarding points for
default false-to-false forced/hearingImpaired equality. Keep the scoring in
SubtitleAutoResolver and this DetailPlaybackFormatting helper aligned so both
paths require a real signal before selecting a track.

In `@iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift`:
- Around line 107-114: The `videoPresentationSize` update in
`PlayerCore.publishVideoPresentationSize()` is happening off-main while
`PlayerSurfaceHostView.attach(player:)` reads the same property on the UI
thread, creating an unsynchronized shared access. Move the stored-property
assignment for `videoPresentationSize` into the existing
`DispatchQueue.main.async` block so both the write and the
`onVideoPresentationSizeChange` callback run on main.

---

Outside diff comments:
In `@iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift`:
- Around line 3490-3503: The MPEG2 software decode branch in PlayerCore is
returning after only opening the decoder, so the presentation size never gets
published and PlayerSurface stays at .zero. Before calling
setupSoftwareVideoDecoder(codecpar:codecparPtr:), initialize and publish the
video presentation size using the codecpar dimensions in this
AV_CODEC_ID_MPEG2VIDEO case, following the same pattern used by the hardware
paths so subtitles and layout can size correctly.
🪄 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: b32e97c8-42ff-4783-ad90-20a777c483b6

📥 Commits

Reviewing files that changed from the base of the PR and between 7a054f3 and 49fbe7a.

📒 Files selected for processing (16)
  • iosApp/Tests/SubtitleStylingOverrideTests.swift
  • iosApp/Tests/VideoDisplayRectTests.swift
  • iosApp/iosApp/Networking/Models.swift
  • iosApp/iosApp/Screens/Detail/DetailPlaybackFormatting.swift
  • iosApp/iosApp/Screens/Detail/ItemDetailView.swift
  • iosApp/iosApp/Screens/Detail/ItemDetailViewModel.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/PlayerSurface.swift
  • iosApp/iosApp/Screens/Player/Subtitles/AVPlayerEmbeddedSubtitleExtractor.swift
  • iosApp/iosApp/Screens/Player/Subtitles/SubtitleAppearance.swift
  • iosApp/iosApp/Screens/Player/Subtitles/SubtitleRenderer.swift
  • iosApp/iosApp/Screens/Player/Subtitles/SubtitleStylingOverride.swift
  • iosApp/iosApp/Screens/Player/Subtitles/VideoDisplayRect.swift
  • iosApp/iosApp/macOS/PlayerSurface.swift
  • iosApp/iosApp/tvOS/Screens/Detail/TVItemDetailView.swift
  • iosApp/project.yml

…er box

- tvOS overlays now cover the full frame and pass the video rect to
  libass via ass_set_margins; the Bottom preset enables use_margins so
  regular cues render below the picture in the letterbox bar (60px off
  the frame edge), and Lower Third takes Bottom's old anchor at the
  video's bottom edge. Native ASS and the secondary slot stay inside
  the video area. iOS/macOS placement unchanged.
- Rebase the tvOS font-size ladder ~1.3x (Large is now the old X-Large+).
- Halve subtitle box padding on iOS and tvOS.
@zZebrahz
zZebrahz marked this pull request as ready for review July 3, 2026 20:40
- Require a strong signal (language or label match) before
  bestSignatureMatch returns a candidate, in both the detail seeding
  and player auto-resolver paths. Forced/HI/codec equality alone is
  meaningless (false == false holds for nearly every track) and could
  hijack Auto with an arbitrary first track.
- Main-confine PlayerCore.videoPresentationSize: compare-and-assign
  inside the main hop instead of writing from the demux/control path,
  matching the UI-thread read in PlayerSurfaceHostView.attach.
@zZebrahz
zZebrahz merged commit 405765b into main Jul 3, 2026
1 check passed
@zZebrahz
zZebrahz deleted the subtitles branch July 3, 2026 20:52

@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: 5bb1550892

ℹ️ 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".

// this slot.
if let newId, SubtitleTrackIdSpace.isSidecar(newId) {
embeddedSubtitlePipeline.tearDownEmbeddedSlot(slot: slot)
runtimeSubtitleExtractor?.stopFeeding(slot: slot)

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 Clear stale runtime captions before opening sidecars

When the current subtitle was selected through the new runtime extractor (for example after a mid-playback embedded-track toggle), stopFeeding only cancels that extractor generation and deliberately leaves the libass track installed. openSidecar fetches asynchronously and only replaces the slot once the sidecar content arrives, so switching to an uncached or failing sidecar can keep rendering the old embedded captions during the fetch or indefinitely on failure; the AVPlayer route clears the extractor slot before opening a sidecar. Clear/close the slot before starting the sidecar fetch.

Useful? React with 👍 / 👎.

Quick104 added a commit that referenced this pull request Jul 4, 2026
Conflict in AVPlayerBackend.pumpSubtitleOverlay: kept this branch's
text/bitmap split (textOverlayMayHaveFrame + pumpBitmapCues) and grafted
in main's videoInsets plumbing to renderOnSessionQueue.

Semantic follow-through: main's a8fd931 makes the tvOS subtitle overlay
full-frame (video rect communicated via videoInsets), which broke this
branch's assumption that overlay bounds == videoRect for bitmap cue
placement. pumpBitmapCues now maps normalized PGS/DVD cue rects into the
video rect derived from the insets (zero on iOS/macOS, so unchanged
there), and the render key tracks the video rect instead of raw bounds.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0146hwg1Q15YdeUhd9f37NWA
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.

Subtitle appearance redesign + mid-playback toggle latency + override restore (iOS/tvOS/macOS)

1 participant