Repository navigation
fix(player): draw ASS subtitles on the video's own clock - #733
Conversation
Typeset signs trailed the picture by two to four frames. The overlay sampled a running clock every 16 ms on the main actor, rendered each sample through SwiftAssRenderer's float pipeline, and showed it as a SwiftUI image, so a tracked mask lagged the signage it covers. Render each sign at the exact timestamp of the frame AetherEngine reports and queue it on an AVSampleBufferDisplayLayer whose control timebase is the video's clock. Floor libass time to the millisecond, as FFmpeg does. Composite libass masks straight into pooled premultiplied BGRA buffers capped at 1080p, feed libass incrementally by cue id, and fence each selection by a generation the session sets on the layer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
📝 Walkthrough
Merge Risk: ⚪ Minimal · up to No actionable merge-blocking issue remains from the reviewed changes; the PR is mergeable after normal checks. Pre-merge checks |
|
|
The Evidence section describes the result but has no captures or linked artifacts showing subtitle synchronization. Add before-and-after captures and a short recording of the same moving-sign fixture for the affected tvOS, iOS, and macOS players, naming each build or commit. Include the current-head rerun results when available; the existing measurements are from an earlier revision. |
| let frame = Frame(stamp: time.item, source: time.source.seconds) | ||
| guard frame.presentation.isFinite, frame.source.isFinite else { return } | ||
| state.withLock { tables in | ||
| var table = tables[.native, default: Table()] |
There was a problem hiding this comment.
Array copy-on-write occurs on each frame insertion because each report copies a Table out of tables while the dictionary retains its frames array, forcing nominally append-only recording to allocate and copy the entire retained schedule—up to 20,000 muxed-ahead frames—in O(N) time per frame under the shared lock. Mutate the dictionary's table in place or use uniquely owned reference storage protected by that lock.
Prompt for LLM
File iosApp/iosApp/Screens/Player/Subtitles/ASSFrameSchedule.swift:
Line 95:
Array copy-on-write occurs on each frame insertion because each report copies a `Table` out of `tables` while the dictionary retains its `frames` array, forcing nominally append-only recording to allocate and copy the entire retained schedule—up to 20,000 muxed-ahead frames—in O(N) time per frame under the shared lock. Mutate the dictionary's table in place or use uniquely owned reference storage protected by that lock.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
| var time = ((start / interval).rounded(.down) + 1) * interval | ||
| // The division can round down a whole step when `start` is on the grid. | ||
| if time - start < interval / 2 { time += interval } |
There was a problem hiding this comment.
Fallback frame synthesis skips the next valid timestamp when it falls less than half an interval after start: at 25 fps and 0.035 s, it skips 0.040 s and starts at 0.080 s, causing Remote-HLS signs to retain the previous canvas through the skipped frame. Advance an additional interval only when the candidate is at or before start, not merely close to it.
if time <= start { time += interval }Prompt for LLM
File iosApp/iosApp/Screens/Player/Subtitles/ASSOverlayPresenter.swift:
Line 363 to 365:
Fallback frame synthesis skips the next valid timestamp when it falls less than half an interval after `start`: at 25 fps and 0.035 s, it skips 0.040 s and starts at 0.080 s, causing Remote-HLS signs to retain the previous canvas through the skipped frame. Advance an additional interval only when the candidate is at or before `start`, not merely close to it.
Suggested Code:
if time <= start { time += interval }
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
| let start = cueTime(forPresentation: now, timing) ?? 0 | ||
| let end = cueTime(forPresentation: now + Self.lookaheadSeconds, timing) ?? start | ||
| if try applyCues(window: start...max(start, end) + interval), renderedThrough != nil { |
There was a problem hiding this comment.
Late-cue invalidation starts at the running clock rather than the displayed frame's timestamp: when that frame is stamped 0 s, now is 0.035 s, and a newly received sign ends at 0.020 s, renderer.update rejects the sign as outside the window and never refills the frame, although the sign belongs on the displayed picture. Start the invalidation window at the current frame's cue timestamp.
Prompt for LLM
File iosApp/iosApp/Screens/Player/Subtitles/ASSOverlayPresenter.swift:
Line 242 to 244:
Late-cue invalidation starts at the running clock rather than the displayed frame's timestamp: when that frame is stamped 0 s, `now` is 0.035 s, and a newly received sign ends at 0.020 s, `renderer.update` rejects the sign as outside the window and never refills the frame, although the sign belongs on the displayed picture. Start the invalidation window at the current frame's cue timestamp.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
Recording a frame copied its table out of the schedule's dictionary and back, so every report copied all retained frames, up to 20,000, under the lock. Tables are now mutated in place. Two smaller timing fixes from review: a late cue refills the frame on screen even when the clock has moved past that frame's stamp, and the remote-HLS fallback no longer skips the grid frame just after an off-grid start. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8eedee4f02
ℹ️ 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".
| sink.enqueue(clear, at: frame.stamp, generation: generation) | ||
| report.queuedCanvases += 1 | ||
| } | ||
| queuedPixels = false |
There was a problem hiding this comment.
Retry the clear canvas when allocation fails
When the last subtitle ends while transparentCanvas() cannot allocate a pixel buffer, this branch still sets queuedPixels to false. Subsequent frames normally return .unchanged, so the presenter never retries the clear and the previous subtitle canvas can remain visible indefinitely under memory pressure. Keep the pixel state set until a clear buffer is successfully enqueued.
Useful? React with 👍 / 👎.
| stats.reportedFrames += report.reportedFrames | ||
| stats.renderSeconds += report.renderSeconds | ||
| if report.renderedFrames > 0 { | ||
| stats.slowest = max(stats.slowest, report.renderSeconds / Double(report.renderedFrames)) |
There was a problem hiding this comment.
Track the actual slowest frame instead of a step average
When frames within one presenter step have different render costs, this calculation records that step's average as slowest. A single expensive frame among several cheap frames is therefore substantially underreported, making the new performance diagnostic unable to identify the stalls it is intended to expose. Carry the maximum individual render duration in Step and aggregate that value here.
Useful? React with 👍 / 👎.
When the last sign ends and the transparent canvas cannot be allocated, the frame now renders again next step instead of leaving the sign up. The overlay log's slowest time is the slowest single frame rather than the slowest step's average. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bd62b0e1ab
ℹ️ 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".
| } else { | ||
| frames.insert(frame, at: index) | ||
| } | ||
| if frames.count > capacity { frames.removeFirst(frames.count - capacity) } |
There was a problem hiding this comment.
Avoid shifting the full frame schedule on every report
When no ASS overlay is visible, nothing calls prune, but the observers continue recording every video frame. After 20,000 frames—about 14 minutes at 24 fps or 5.5 minutes at 60 fps—each new report executes removeFirst(1), shifting the entire 20,000-element array under the lock on every frame for the rest of playback. Use a ring buffer or evict entries in batches so ordinary long playback without ASS subtitles does not incur sustained O(capacity) work per frame.
Useful? React with 👍 / 👎.
Nothing prunes the schedule while no overlay is showing, so once a long playback filled it, every frame report shifted all 20,000 retained frames under the lock. Past capacity it now drops the oldest quarter at once. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 70fee03977
ℹ️ 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".
| frames += upcomingFrames(after: current?.presentation ?? now, through: horizon, timing) | ||
| } | ||
|
|
||
| for (frame, reported) in frames.prefix(Self.maximumFramesPerStep) { |
There was a problem hiding this comment.
Scale the render cadence for high-rate playback
With supported 240-fps content playing at the exposed 3× speed, the 30 ms loop sleep advances about 22 video frames, but this cap processes at most 12; on the next step renderedThrough is therefore more than two frames behind, so the refill branch jumps to the frame currently on screen and never renders the intervening ASS animation frames. The ten-canvas pool can shorten the covered interval further. Make the step limit or wake cadence account for frame rate and playback rate so frame-exact signs remain continuous at supported settings.
Useful? React with 👍 / 👎.
Problem
Related issue: N/A
Validation tasks: changes #314 C1, C4; changes #313 C1, C4
Typeset ASS signs lag the picture. A translated label and the mask behind it should track the signage they cover, but on Apple TV they trail the camera by a few frames, so the original text shows through whenever the shot moves. A user reported it on JoJo's Bizarre Adventure S03E17 (inid4c + SFX) and Laid-Back Camp the Movie (neoHEVC).
The overlay sampled a running clock on the main actor every 16 ms, then rendered each sample through SwiftAssRenderer's float pipeline. It showed the result as a SwiftUI image. Signs therefore landed two to four frames late, and a full-screen sign at 4K took longer to render than a frame lasts. This change renders each sign for the exact frame it belongs to, and the video's own clock shows it with that frame.
Approach
ASSOverlayPresenterrenders about 0.3 s ahead, at the exact timestamps of the frames AetherEngine reports (setNativeVideoFrameTimeObserver,setSoftwareVideoFrameTimeObserver). It queues each canvas on anAVSampleBufferDisplayLayerwhose control timebase is the video's clock: the player item's timebase, or Aether's software synchronizer. Core Animation shows each canvas with its frame, so render time and main-thread load no longer move it. Remote HLS, where Aether reports no frames, spaces frames by the source frame rate.ASSImageCompositorblends libass masks straight into premultiplied BGRA pixel buffers from a pool. Canvases are capped at 1920×1080 pixels, and a 4K output scales them up.ASSSubtitleRendereradds cues by Aether cue id and keeps aged-out events for a backward seek. A retracted or changed cue, or the first cues of a held reload, restart the event list without rebuilding libass.This affects the iOS, tvOS, and macOS players. No server or Android change is needed. Aether's subtitle drain also delivers dense cues late after a seek or at startup. That fix is the stacked pin-bump PR.
Validation
Unit tests: the renderer, compositor, frame-schedule, cue-feed, presenter, and media-authorization tests pass on a tvOS simulator, 31 tests. The full SiloTV suite passes on a fresh simulator, 2,644 tests with 0 failures, with this branch's code under chore(deps): take the dense ASS subtitle drain fix from AetherEngine #734's engine pin, which adds no tests. iOS and macOS build.
Simulator playback: a synthetic 60 s file at 1080p and 23.976 fps carries about 24,700 frame-timed sign events. Their masks cover red blocks burned into the video, and every frame's red pixels were counted. The share of frames showing red fell from 49.6% on
mainto 2.2–2.4% with this branch, and to 1.0–1.3% with chore(deps): take the dense ASS subtitle drain fix from AetherEngine #734 as well. The table shows the worst of four runs on this branch's commits:The red frames left with this PR alone are Aether's: the first 1.5 s, and in two of four runs a few single frames whose sign had not arrived. Aether's drain ran about 4 s ahead and decodes at most 512 packets a second, below this file's peak of 620 events a second, so on a busy host it fell behind. With chore(deps): take the dense ASS subtitle drain fix from AetherEngine #734, only the first 0.5 s shows red. Rendering averaged 4.3 to 9.1 ms per frame, with 15.0 ms the slowest single frame, in a Debug build at 1920×1080.
Not verified: Aether's native AVPlayer path, because the simulator always plays H.264 through Aether's software path. Unit tests with fake clocks cover the native and remote-HLS clocks. A physical Apple TV and the reporter's files are also unverified.
Evidence
Evidence: https://evidence.siloserver.org/r/silo-apple/pr-733/
Surface and build: SiloTV Debug on the tvOS simulator, with
mainatbf4f7156before and this branch after, playing the fixture above. The video and the overlay each draw their frame number.Risks
Checklist
AI Disclosure
gpt-6.1-soldid four rounds of read-only review of the full patch. Round 1 raised six findings, all fixed: native and software frame reports shared one generation counter, cue ids were reused after a held reload, render time was rounded, the selection fence had a gap, two conversions could trap, and the clock lead outlived its player item. Round 2 raised two findings, both fixed: a late presenter load could reopen the fence, and a held reload kept deleted events. Round 3 raised three findings, all fixed: a held reload that ended with no cues kept the old events, a late step could render with the new generation and the old timing, and a snapshot could hide stale queued frames. Round 4 confirmed those fixes and found nothing further. The Kody bot then found three more, fixed in8eedee4f: recording a frame copied the whole frame table, the remote-HLS fallback skipped the grid frame after an off-grid start, and a late cue for the frame on screen could be missed. The Codex bot then flagged two more, fixed inbd62b0e1: a failed clear-canvas allocation left the last sign up, and the logged slowest time was a step's average rather than a single frame. One more, fixed in70fee039: with no overlay showing, a full frame schedule shifted all its frames on every report.🤖 Generated with Claude Code