Skip to content

fix(playback): align subtitle rendition cues when the source clock doesn't start at zero - #2649

Merged
Quick104 merged 3 commits into
mainfrom
fix/subtitle-rendition-start-time
Oct 17, 2026
Merged

Quick104 merged 3 commits into
mainfrom
fix/subtitle-rendition-start-time

Conversation

@Quick104

@Quick104 Quick104 commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2648
Related issue: N/A
Validation tasks: none

When a transcode carries an embedded text subtitle as an HLS subtitle rendition (#2620), cues go into the wrong subtitle segments if the source's clock doesn't start at 0. Players load each cue several segments after its video, so the subtitle shows late or not at all. With a large start offset, every cue falls into the last segment. MPEG-TS captures and files remuxed from them often start seconds or hours in. This affects Apple and Android clients that send hls_subtitle_renditions_v1.

The rendition's cue file keeps the source clock (-copyts), so a cue at 1 s in a file that starts at 7 s is written as 00:08.000. Subtitle segment N was cut from [N·d, (N+1)·d) measured from 0. Video segment N actually starts at the generation's first video frame plus (N−K)·d, where K is the segment the generation started at.

Approach

Each FFmpeg generation now reads its origin once: the first video PTS of its own first output segment, less the shift the X-TIMESTAMP-MAP already declares. Subtitle segments are cut from that origin. The read uses the ffprobe call that copy-mode manifests already make on generated output, extended to MPEG-TS and parsed as JSON. It opens one local segment and never the source. Concurrent requests share one read per generation, and the result is cached on the generation's cue span. If the origin can't be read, the segment falls back to today's grid. For a file whose clock starts at 0 the windows are the same as before.

Why measure the output instead of storing the source's start time, as the issue suggested: the origin differs between generations. For a file whose audio starts at 3 s and video at 7 s, the first generation's grid starts at 7 s (the first encoded frame), while a seek restart's grid starts at the container's 3 s plus the seek. One stored value can't describe both. Reading the output also needs no migration and no new recipe or token field, and it works for files scanned before this change.

Other details:

  • MPEG-TS rollover: MPEG-TS timestamps wrap at 2^33 ticks (about 26.5 h) while the cue file keeps counting. The window takes the cue clock's epoch, so captures whose clock passes the rollover still line up.
  • Restarts: a generation's segment is read only while no restart is under way and no later generation has rewritten it. An earlier generation that a forward seek kept still gets its own origin for backward seeks.

Transcode nodes serve the rendition from the same session code, so they get the fix without changes. Jellycompat doesn't use renditions. The clients need no change: the wire format, playlists, and timestamp map are the same. docs/architecture/playback-protocol-v3.md now describes the window.

Validation

  • Go build, gofmt, go vet ./..., make lint-changed (0 issues), make lint-router-recovery, make verify-playback-fixtures: pass. make test-go: pass except internal/mediasample TestRunStatsWithRealFFmpeg, which fails the same way on main with the local FFmpeg 6.1.1.
  • The real-FFmpeg rendition test now covers three sources: clock at 0, all streams at 7 s, and audio at 3 s with video at 7 s. Each runs from the start and after a seek, to MPEG-TS and fMP4. The test checks each subtitle segment against the source time its actual video segment covers. With the origin disabled (main's grid) the nonzero-start cases fail with 40 misplaced cues. With the fix all 12 pass.
  • Unit tests cover the MPEG-TS rollover (including a capture more than 13 h past an origin just before it) and signed ffprobe values, one ffprobe run for concurrent requests, backoff after a failed read, a restart overlapping a read, and an earlier generation kept by a forward seek. These run under -race.
  • Not reproduced on a live deployment: the sandbox host had no free container network for a new stack. The integration test runs the transcode's own FFmpeg command line and the session's segment serving code.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/issue-2648/

Risks

  • One ffprobe run on a local segment per transcode generation that serves subtitles. It is bounded by a 5 s timeout and backs off for 5 s after a failure, serving the old grid meanwhile.
  • A segment boundary can sit up to one frame after the computed one, because a forced keyframe lands on the first frame at or after its grid time. A cue that starts in that frame goes in the next segment, which players load ahead.
  • Two related defects stay out of scope:
    • When the muxer lifts negative timestamps, video moves by up to about a second while the X-TIMESTAMP-MAP shift stays fixed, so cues show that much early.
    • When video starts after the container, a seek restart's video grid differs from the first generation's.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code in T3 Code
  • Tool(s): Claude Code; Codex (cross-provider plan review and background review)
  • Model(s): claude-opus-5-5 (implementation, code review), gpt-6.1-sol (plan review)
  • Involvement: Fully AI-generated; human verification pending maintainer review
  • Adversarial review: two plan rounds by gpt-6.1-sol. Round 1 showed that a stored container start time is wrong when video starts after audio, so the approach changed to reading each generation's origin from its output. Round 2 found request-order dependence, MPEG-TS epoch handling, a parser that rejected TS output, and missing single-flight. All four were fixed. A multi-agent code review (claude-opus-5-5) found a restart race, cancellation of the shared read, and wraparound on long streams' last segment. All three were fixed. Background review by gpt-6.1-sol (reviewed 1b1f43b) found one issue: on MPEG-TS, the epoch was chosen per window, so a capture starting just before the timestamp rollover lost it more than 13 h in. Fixed in 0e1b645 by choosing the epoch once, on the generation's origin. Kody then found the opposite edge: a zero-clock stream whose first cue comes more than 13 h in was moved up an epoch. Fixed in 3439ccb by taking the latest epoch that keeps the origin no later than its first cue.

Note

Fix subtitle cue alignment in generated WebVTT segments for non-zero source clocks

  • Subtitle segments previously used a fixed segment-number grid, which misaligned cues when the source clock starts at a non-zero offset, streams start at different times, or a seek creates a generation-relative grid. The document builder now computes the actual source-time interval for each generated video segment and emits cues that overlap it.
  • A new probeSegmentVideoPTS probe reads the first video packet PTS from generated segments (MPEG-TS or fMP4) via ffprobe, sandboxed to the output directory. subtitleSpanOrigin observes the generation origin once per span, caches it, retries after five seconds on failure, and discards observations that overlap a restart or a later generation's overwrite in subtitle_rendition.go.
  • MPEG-TS origins are resolved onto the cue clock's unwrapped epoch, handling 33-bit timestamp rollover and signed ffprobe reports. fMP4 windows skip this rollover adjustment.
  • Falls back to the previous fixed-grid window when the origin cannot be observed. Expanded the real-FFmpeg integration test to validate cue placement across source offsets, seek generations, and both containers.
  • Behavioral Change: cue membership in generated subtitle segments can shift for all non-zero-origin streams; check subtitleSegmentDocument and subtitleWindowEpoch in subtitle_rendition.go if cue placement regresses.

Macroscope summarized 3439ccb.

…esn't start at zero

Subtitle segment N cut its cues from [N·d, (N+1)·d), but a generation's video
segment N covers [O + (N−K)·d, …): O is the generation's first video frame on
the source clock, which is the video's start time for the first generation and
the container's start plus the seek for a seek restart. On a source whose clock
starts at 7 s every cue landed several segments late, and with a large start
offset all of them fell into the open-ended last segment.

Each generation now reads O once from the first video PTS of its own first
output segment (the probe the copy path already used, extended to MPEG-TS and
parsed as JSON), caches it on its cue span, and cuts windows from it. MPEG-TS
windows take the cue clock's epoch across the 33-bit rollover. A generation
whose origin can't be read keeps the old grid.

Closes #2648

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added the size/XL 500–999 added + deleted lines (all files); change volume, not priority. label Oct 17, 2026
@silo-kody

silo-kody Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 1f5b2874-9b25-4a35-88f7-fa7fd3b3d5cb
📥 Commits

Reviewing files that changed from the base of the PR and between 1b1f43b and 3439ccb.

📒 Files selected for processing: 3
  • docs/architecture/playback-protocol-v3.md
  • internal/playback/subtitle_rendition.go
  • internal/playback/subtitle_rendition_test.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

📝 Walkthrough

Subtitle segment cue windows now use the source-time origin of each video generation. Origin probes support MPEG-TS and fMP4. Cue selection accounts for timestamp wrap, and falls back to a fixed grid when the origin is unavailable.

Changes: Subtitle timing alignment

Layer / File(s) Summary
Probe and cache generation origins
internal/playback/copy_manifest_origin.go, internal/playback/subtitle_rendition.go, internal/playback/transcode.go
The origin probe handles MPEG-TS segments and fMP4 fragments. Subtitle spans cache observations, limit retries after failures, and discard observations made stale by restarts or segment rewrites. Transcode cleanup preserves the configured HLS init segment.
Select cues by source-time window
internal/playback/subtitle_rendition.go, docs/architecture/playback-protocol-v3.md
Subtitle documents select cues using the generation’s source-time window. Cue parsing occurs before filtering, and MPEG-TS windows account for timestamp wrap. The documentation describes the updated timing rule and fallback.
Validate origins and cue membership
internal/playback/subtitle_rendition_test.go
Tests cover source offsets, MPEG-TS and fMP4 timestamps, concurrent observations, failed probes, generation changes, and cue membership across segments in FFmpeg integration cases.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant SubtitleSegmentVTT
  participant subtitleSpanOrigin
  participant ffprobe
  participant subtitleSegmentDocument
  SubtitleSegmentVTT->>subtitleSpanOrigin: Resolve generation origin
  subtitleSpanOrigin->>ffprobe: Probe first available video segment
  ffprobe-->>subtitleSpanOrigin: Return packet timestamp
  subtitleSpanOrigin-->>SubtitleSegmentVTT: Return origin or fallback
  SubtitleSegmentVTT->>subtitleSegmentDocument: Build document with cue window
  subtitleSegmentDocument-->>SubtitleSegmentVTT: Return overlapping cues
Loading

Suggested reviewers: rhainland

Merge Risk: ⚪ Minimal · up to 3439c

Subtitle windows for forward seeks align with the generated segment numbering. No actionable merge-blocking issue is established.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 43.48% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 4 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed The changes satisfy #2648. subtitleSegmentWindow uses the origin of the generation that wrote the cue file and the generation-relative segment offset. subtitleSpanOrigin probes one local video seg…
Out of Scope Changes check Passed The changes remain within #2648. The shared segment probe extension supports the origin measurement for MPEG-TS and fMP4. Restart protection, generation caching, cleanup handling, tests, and the playb…
Description check Passed The description clearly explains the subtitle cue alignment problem, the per-generation origin approach, MPEG-TS rollover handling, fallback behavior, validation, and risks.
Title check Passed The title clearly and concisely summarizes the main change: aligning playback subtitle cues when the source clock does not start at zero.
Full details: Linked Issues check

Explanation

The changes satisfy #2648. subtitleSegmentWindow uses the origin of the generation that wrote the cue file and the generation-relative segment offset. subtitleSpanOrigin probes one local video segment, removes the timestamp-map shift, caches the result, serializes concurrent reads, and falls back to the fixed grid after failure. The implementation handles MPEG-TS timestamp rollover. The reported unit and real-FFmpeg tests cover nonzero clocks, seek generations, MPEG-TS, fMP4, and fallback behavior.

Full details: Out of Scope Changes check

Explanation

The changes remain within #2648. The shared segment probe extension supports the origin measurement for MPEG-TS and fMP4. Restart protection, generation caching, cleanup handling, tests, and the playback protocol documentation support subtitle alignment. No unrelated client, playlist, or wire-format change is shown. The PR explicitly leaves timestamp lifting and video-after-audio restart behavior out of scope.

Full details: Docstring Coverage

Explanation

Docstring coverage is 43.48% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 4 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: playback Can't play, stalls, or wrong media priority: P1 Core-path bug; painful workaround — next after P0 labels Oct 17, 2026
Comment thread internal/playback/subtitle_rendition.go Resolved

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adversarial review (gpt-6.1-sol, reviewed 1b1f43b)

1 verified finding, reproduced locally with FFmpeg 6.1.1 and the production subtitle serving code.

AI disclosure: Codex, gpt-6.1-sol.

Comment thread internal/playback/subtitle_rendition.go Resolved
The epoch was chosen per window relative to the first cue, so a generation
whose observed origin sat an epoch below its cues lost the correction once
its windows ran more than half a timestamp range (about 13 h) past it, and
those segments came back empty. Resolve the epoch on the origin and add the
segment's offset after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Comment thread internal/playback/subtitle_rendition.go Resolved
…cue's side

The epoch was the first within half a timestamp range below the first cue,
which moved a zero-clock generation up an epoch when its first cue came more
than about 13 h in. A generation starts no later than its first cue (give or
take a cue already showing), so take the latest epoch that keeps it there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104
Quick104 merged commit 88b633c into main Oct 17, 2026
20 checks passed
@Quick104
Quick104 deleted the fix/subtitle-rendition-start-time branch October 17, 2026 23:00
rangoDJ added a commit to rangoDJ/silo-server that referenced this pull request Oct 19, 2026
Main added subtitle rendition cue spans (Silo-Server#2620, Silo-Server#2649) to TranscodeSession
beside this branch's group assembler and plan seek anchor. Keep both;
neither depends on the other.

Main's wider static checks (Silo-Server#2522) apply to this branch's code, which the
merge commit must pass:

- fMP4 decode times go through readFMP4DecodeTime, which rejects a
  version 1 time past MaxInt64. putFMP4DecodeTime rejects a negative one,
  and trimTrafStart range-checks the sample count it writes.
- Conversions that read the format's signed 32-bit fields, and the box
  size of one segment's boxes, carry reasoned nolints.
- Assembled segments read through filepath.Clean. Their 0644 writes and
  the plan record's, beside FFmpeg's own output, and the ffprobe call,
  carry reasoned nolints.
- strconv.Itoa for -hls_time.
- The planned-session test's polls and its length carry reasoned nolints.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
rangoDJ added a commit to rangoDJ/silo-server that referenced this pull request Oct 19, 2026
Main added subtitle rendition cue spans (Silo-Server#2620, Silo-Server#2649) to TranscodeSession
beside this branch's copyPlanRejected. Keep both; neither depends on the
other.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
zenjabba added a commit to zenjabba/silo-server that referenced this pull request Oct 21, 2026
Merge main at f75cdf3. The merge has no textual conflict, but main's
subtitle renditions (Silo-Server#2649) added liveProducedHead, which calls the old
three-value readManifestFile and compares the inherited playlist itself.
This branch moved that comparison into readManifestFile, so the new
caller now passes the inherited playlist and treats os.ErrNotExist as
"no progress yet", with the same result as before.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code impact: playback Can't play, stalls, or wrong media priority: P1 Core-path bug; painful workaround — next after P0 size/XL 500–999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Subtitle renditions put cues in the wrong segments when the source doesn't start at 0

1 participant