Skip to content

fix(playback): plan keyframe playlists from FFmpeg's first muxed packet - #4079

Closed
Rhainland wants to merge 4 commits into
Silo-Server:mainfrom
Rhainland:fix/4049-audio-lead-keyframe-plan
Closed

Rhainland wants to merge 4 commits into
Silo-Server:mainfrom
Rhainland:fix/4049-audio-lead-keyframe-plan

Conversation

@Rhainland

@Rhainland Rhainland commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

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

Other clients: Apple N/A (no client-visible change); Android N/A (no client-visible change); Roku N/A (no client-visible change)

With playback.copy_keyframe_playlist on, a copy-video HLS session can serve a playlist whose segment durations don't match the segments FFmpeg writes. That happens when the audio starts before the video: an AAC track made by FFmpeg's encoder, which starts 1024 samples early, or any session that encodes the audio to AAC. FFmpeg's HLS muxer counts its segment targets from the first packet it muxes, which is then audio, while the planner counted from the first keyframe. A keyframe just under a target lands in a different segment. Since #2515, the first mismatch also turns planning off for that file for every audio selection, including ones that would have matched.

This change plans from the packet FFmpeg actually starts from. When that can't be predicted, the session serves FFmpeg's own playlist.

Approach

The planning read of a Matroska file (keyframes.Load) now also reads the block headers of the first cluster. From them it takes each track's start and CodecDelay, on the timeline of the Cues keyframes, and its sample rate. It also reads the video's B-frame reorder delay as its H.264 or HEVC headers declare it (the SPS in the avcC or hvcC CodecPrivate). keyframes.PlanMuxSegments uses the selected audio track and how the session handles it (copied, encoded to AAC, or another encoder) to work out which packet the muxer can start from:

  • The video's first keyframe when the video is muxed first, or the audio's first packet when the audio is. FFmpeg's AAC encoder adds 1024 samples of priming.
  • When B-frames make the video's first decode time uncertain, both.

It plans from every possible start and declines to plan when they disagree. It also declines when a keyframe sits within 0.5 ms of a target, and when another track starts before the selected audio (the muxer would then subtract a nonzero audio timestamp in another time base).

The rule follows FFmpeg's hlsenc.c (start_pts, reset to a lower video timestamp), and the CLI's first decode time for copied video (pts - video_delay / frame rate). FFmpeg's decoder takes that delay from the headers: H.264's max_num_reorder_frames when the VUI carries bitstream_restriction, HEVC's sps_max_num_reorder_pics. A first cluster without B-frames doesn't show it. When the headers declare no delay, or the first cluster reorders more than they declare, FFmpeg measures the delay from the frames it probes, so the planner treats it as unknown and keeps the video-first origin among the possible starts.

A Jellyfin client can switch audio mid-session, which restarts FFmpeg with the new track while the player keeps the plan it already has. Once a session's audio has differed from the audio it planned for, a mismatch no longer rejects the file version, because it says nothing about the Cues.

Some sessions the old planner served now fall back to FFmpeg's playlist when the possible starts disagree: audio re-encoded to Opus, AC3 or E-AC3 with a keyframe within 50 ms under a target, video whose headers don't declare its reorder delay (H.264 without bitstream_restriction, MPEG-2, MPEG-4 Part 2), B-frame video whose declared delay is close to the audio lead, encoded audio that isn't in the first cluster, AAC at 24 kHz or less with no output rate (implicit HE-AAC) encoded to AAC, and files where an unselected track starts before the selected audio.

Validation

  • Unit tests for how PlanMuxSegments picks the start (copied and encoded audio, B-frames, ties, other tracks starting first) and for the plan check after an audio switch, including a switch back.
  • FFmpeg-in-the-loop test comparing the plan with FFmpeg's HLS output for copied AAC, copied AC3, AC3 and AAC encoded to AAC, B-frames, and H.264 that declares B-frames but has none in the first cluster. It passes with FFmpeg 6.1.1 and jellyfin-ffmpeg 8.1.3; the cases before the last one also passed with 8.0.1. main's planner disagrees with FFmpeg for the AAC cases.
  • Local server built from main and from this branch, same database and synthetic files, sessions started through POST /api/v2/playback/start: on main the planned playlist mismatched FFmpeg for copied AAC and for AC3 encoded to AAC, and the mismatch disabled planning for the file's later AC3 playbacks. On this branch every session served exactly FFmpeg's durations with no rejection, including a 23.976 fps B-frame file with copied and encoded AAC.
  • Go gate: build, gofmt, go mod tidy -diff, go vet, make lint-changed, make lint-router-recovery, make test-go, verify-playback-fixtures, verify-local-paths, verify-case-collisions, verify-size-ratchet, verify-bidi pass. The web half and the API contract targets were not run: nothing under web/ or the API changed.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-4079/

The page has the review's sandbox check of the final head. The playlist is served to players, so here are the API results the author's local check compared, for a 50 fps MKV with keyframes at 0, 1.98, 4, 6, 8, 10, 11.98 s and AAC starting at -0.021 s (the AC3 copy of the same video starts at -0.005 s):

main, AAC copied
served playlist:  4 2 2 2 1.98 2.02 2 2 2
ffmpeg playlist:  1.98 2.02 2 2 2 1.98 2.02 2 2 2
main, AC3 encoded to AAC
served playlist:  4 2 2 2 1.98 2.02 2 2 2
ffmpeg playlist:  1.98 2.02 2 2 2 1.98 2.02 2 2 2

this branch, AAC copied
served playlist:  1.98 2.02 2 2 2 1.98 2.02 2 2 2
ffmpeg playlist:  1.98 2.02 2 2 2 1.98 2.02 2 2 2
this branch, AC3 copied
served playlist:  4 2 2 2 1.98 2.02 2 2 2
ffmpeg playlist:  4 2 2 2 1.98 2.02 2 2 2
this branch, AC3 encoded to AAC
served playlist:  1.98 2.02 2 2 2 1.98 2.02 2 2 2
ffmpeg playlist:  1.98 2.02 2 2 2 1.98 2.02 2 2 2

Risks

The setting is off by default. A file the new rules can't predict keeps FFmpeg's playlist, which is the behaviour without the setting. The planning read now also reads the first cluster's block headers, near the start of the file, which the coverage check usually samples already.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or how I checked a change nobody sees.

AI Disclosure

  • Harness: Claude Code (via T3 Code); Codex CLI for code review
  • Tool(s): Claude Code, Codex CLI
  • Model(s): claude-opus-5-5; gpt-6.1-sol (code review)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: dual-code-review (Claude Opus 5.5 and GPT 6.1 Sol, medium effort, run independently on the branch diff, then on each fix). GPT found nothing. Opus found that a Jellyfin mid-session audio switch keeps the plan for the old audio and a mismatch then rejected the file for every audio selection, which is now skipped once the audio has changed (a first version compared the audio at check time, which a switch back defeated; fixed). Opus also flagged a duplicated cluster walk (now shared), an unused NoAudio field (removed) and the node API doc (updated). Dismissed: H.264 without bitstream_restriction getting a level-based B-frame delay (FFmpeg only does that under strict compliance), and a failed audio-switch restart leaving the change flag set (needs a failed FFmpeg spawn and bad Cues together, and only skips one rejection).

Note

Fix keyframe playlist planning to use FFmpeg's first muxed packet origin

Copy-video keyframe playlists were planned from the first video keyframe alone, but FFmpeg's segment targets are measured from the first muxed packet, which may be audio. The new keyframes.PlanMuxSegments planner resolves possible origins from the first video keyframe, the selected audio's first packet, and declared video reorder depth.

  • Adds parsing of Matroska track metadata, audio sampling rates, and the first media cluster to feed planning (matroska.go, ids.go)
  • Adds AVC and HEVC codec-header reorder-depth parsing via a bounded RBSP bit reader (reorder.go)
  • The planner declines to return a plan when the origin is ambiguous (unknown AAC sample rate, another track starting first, keyframe too close to a target); the session then keeps FFmpeg's own playlist
  • Behavioral Change: a segment mismatch after the session's audio selection changes no longer rejects the file version for later playbacks; the session stops checking its plan instead (copy_keyframe_plan.go, transcode.go)

Macroscope summarized 0906c9d.

FFmpeg's HLS muxer counts segment targets from the first packet it muxes,
which is audio when the audio starts before the video (an AAC track, or any
AAC encode). The keyframe planner counted from the first keyframe, so a
keyframe just under a target cut a segment FFmpeg's plan didn't have.

The planning read now also takes each track's start and the video's
B-frame reordering from the first cluster, and PlanMuxSegments plans from
every start the muxer could take. When those give different plans, or an
audio start can't be predicted, the session keeps FFmpeg's playlist.

Closes Silo-Server#4049
@silo-triage silo-triage Bot added the size/XL 500–999 added + deleted lines (all files); change volume, not priority. label Nov 13, 2026
@silo-kody

silo-kody Bot commented Nov 13, 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 Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

The keyframe planner now accounts for audio that can reach FFmpeg’s HLS muxer before video. Matroska indexing records track timing and video reorder data. Playback passes audio settings into planning and handles mismatches after audio-track changes.

Changes: Audio-aware keyframe planning

Layer / File(s) Summary
Matroska track and cluster indexing
internal/matroska/ids.go, internal/matroska/tracks.go, internal/playback/keyframes/matroska.go, internal/playback/keyframes/coverage.go, internal/playback/keyframes/reorder.go, internal/playback/keyframes/matroska_test.go
Matroska parsing records audio sampling rates, track entries, and first-cluster positions. Cluster walking exposes block metadata for track-start analysis. Codec-header parsing determines video reorder depth when supported. Tests cover leading audio-only clusters, timestamp scales, and reorder parsing.
Mux-aware segment planning
internal/playback/keyframes/mux.go, internal/playback/keyframes/plan.go, internal/playback/keyframes/plan_test.go, internal/playback/keyframes/ffmpeg_test.go
PlanMuxSegments evaluates possible mux start-time origins and returns a plan only when the resulting starts agree. Tests compare plans with FFmpeg and cover audio timing, encoding, track ordering, and video reordering.
Playback audio integration and mismatch handling
internal/playback/copy_keyframe_plan.go, internal/playback/transcode.go, internal/playback/prepare_tracks.go, internal/playback/copy_keyframe_plan_test.go, docs/transcode-node-api.md
Playback planning passes the selected audio configuration to PlanMuxSegments. Audio changes are tracked, and mismatch checks do not reject the file after a detected audio switch. Tests and documentation cover the updated behavior.

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

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant planCopySegments
  participant readPlanIndex
  participant PlanMuxSegments
  planCopySegments->>readPlanIndex: Read Matroska index and track timing
  readPlanIndex-->>planCopySegments: Return keyframes and track metadata
  planCopySegments->>PlanMuxSegments: Plan starts using selected audio settings
  PlanMuxSegments-->>planCopySegments: Return segment starts or no plan
Loading

Suggested reviewers: rangodj, quick104

Merge Risk: Moderate · up to 0906c

Keyframe playlist planning for copied audio can still produce segment boundaries that differ from FFmpeg's when the selected audio first appears in a later Matroska cluster that starts before the video. The feature is off by default and the mismatch fallback limits the damage, but the case should be declined before merge.

Security architecture risk: Minimal · up to 0906c

The inspected change preserves conservative playlist fallback, bounded metadata parsing, and file-version isolation. No introduced or worsened risk materially affecting security, failure containment, rollback, or ownership was established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — A party able to influence a played media file can influence these parser inputs. The shared consequence inspected here is planning eligibility for that path, size, and modification-time version across viewers on the same process. The audio-switch exception changes session attribution without clearing existing shared rejections.

Trust Boundaries and Controls

  • observed — Unreadable reorder headers remain unknown rather than becoming a trusted zero-delay declaration. Unknown delay preserves the video-first possibility, and disagreement among candidate origins declines planning. Encoded codec-private data is not interpreted as a plain codec header.

Resilience and Maintainability Implications

  • observed — Failure containment retains the existing separation between a session's published playlist and future planning eligibility. A mismatch does not replace the playlist already given to its player, and completion tracking prevents regeneration of segments known never to have been written.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: planning keyframe playlists from the first packet FFmpeg muxes, which matches the matroska, mux planner, and copy-plan changes in the summary. It is a single, specific…
Linked Issues check Passed Directly linked issue #4049 requires that, with playback.copy_keyframe_playlist enabled, the planned playlist matches FFmpeg's segments for every audio selection, or that planning is skipped when FFmp…
Out of Scope Changes check Passed Each changed area connects to #4049 or supports its implementation. internal/matroska (ids.go, tracks.go) adds audio sampling-rate fields that the AAC planning rule needs. matroska.go and mux.go add f…
Description check Passed The description is closely related to the changeset. It explains the problem with copy_keyframe_playlist when audio starts before video, and the approach of planning from FFmpeg's first muxed packet. …
Full details: Title check

Explanation

The title names the main change: planning keyframe playlists from the first packet FFmpeg muxes, which matches the matroska, mux planner, and copy-plan changes in the summary. It is a single, specific sentence with the conventional fix(playback) prefix and no file lists or vague terms.

Full details: Linked Issues check

Explanation

Directly linked issue #4049 requires that, with playback.copy_keyframe_playlist enabled, the planned playlist matches FFmpeg's segments for every audio selection, or that planning is skipped when FFmpeg's cuts cannot be predicted. The whole-PR summary (merge base 7edef3d to head 0906c9d) shows the following. (1) keyframes.PlanMuxSegments (mux.go) takes the mapped audio from the session's transcode options and derives the possible mux origins: the video's first keyframe, the audio's first packet with AAC priming of 1024 samples, or both when B-frame reorder delay is uncertain. Track starts and reorder depth come from first-cluster block headers and codec-header SPS data (matroska.go, mux.go, reorder.go). (2) PlanMuxSegments returns no plan when the origins disagree, when a keyframe lies within 0.5 ms of a target, when another track starts before the selected audio, or when the reorder delay is unknown. (3) planCopySegments logs a fallback and creates no plan when PlanMuxSegments returns no plan (copy_keyframe_plan.go). (4) The FFmpeg-in-the-loop test compares the planner with FFmpeg output for copied AAC, copied AC3, encoded AAC, and B-frame cases, and the PR reports that these pass with FFmpeg 6.1.1 and jellyfin-ffmpeg 8.1.3. The PR also reports local server comparisons that match FFmpeg durations. Residual gap: after a mid-session Jellyfin audio switch, the player can keep the playlist planned for the earlier audio. The PR and the PR reviewer both describe this as a separate follow-up. The PR changes only the file-level rejection for that case. This is a partial limit on the issue's 'every audio selection' wording, but the issue's stated cause (planner cut points for the selected audio) is addressed. The conclusion rests on the summary, PR description, and test descriptions. I did not read the source hunks directly, so the exact code paths are not independently verified.

Full details: Out of Scope Changes check

Explanation

Each changed area connects to #4049 or supports its implementation. internal/matroska (ids.go, tracks.go) adds audio sampling-rate fields that the AAC planning rule needs. matroska.go and mux.go add first-cluster track starts, reorder metadata, and the planner. reorder.go adds the SPS parsers that supply declared B-frame delay. coverage.go moves cluster parsing into walkCluster so that the planner and coverage check share one walk; this is a refactor that supports the planner. plan.go and plan_test.go add explicit-origin planning used by PlanMuxSegments. copy_keyframe_plan.go and transcode.go add the planning fallback and the audio-switch change flag. prepare_tracks.go adds the audioCodecOpus constant used by the Opus fallback rule. The docs update describes the new planning rules. The added fallbacks for Opus, AC3, E-AC3, and H.264 without bitstream_restriction are stated behavior changes that follow from the need to predict the muxer start. No change was found that lacks a connection to the issue. The same source-reading limit as above applies.

Full details: Description check

Explanation

The description is closely related to the changeset. It explains the problem with copy_keyframe_playlist when audio starts before video, and the approach of planning from FFmpeg's first muxed packet. It names the affected files and functions, including keyframes.PlanMuxSegments, the Matroska cluster reads, and the audio-switch handling. It also lists validation steps, FFmpeg comparison results, and risks. The description is detailed and specific, so it passes the lenient check.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@silo-triage silo-triage Bot added bug Something isn't working impact: playback Can't play, stalls, or wrong media priority: P2 Limited scope, workaround exists, or polish labels Nov 13, 2026
Comment thread internal/playback/keyframes/matroska.go Outdated
Comment on lines +124 to +127
first := m.firstCluster
if first < 0 {
first = m.segStart + m.clusters[0]
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug high

The first video cue is mistaken for the first media cluster

Starting at a later cluster can omit earlier audio packets and produce incorrect playlist boundaries when metadata precedes media. Locate the actual first cluster instead of falling back to m.clusters[0].

Prompt for LLM
File internal/playback/keyframes/matroska.go, lines 124-127:

The first video cue is mistaken for the first media cluster

When Cues, Info and Tracks precede the media, the metadata scan stops before seeing any cluster, so the first video cue can point to a later cluster rather than the first one. Reading that later cluster as the start loses earlier audio packets and can produce a playlist with incorrect segment boundaries; locate the actual first cluster instead of falling back to the first cue.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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.

Fixed in 5470533: when the Cues, Info and Tracks come before the media, the planning read now walks the top-level elements on to the file's real first cluster instead of using the first cluster a video cue points at. If it can't reach one (an unknown-size element, or the segment ends), it doesn't plan. A new test covers Cues first with an audio-only first cluster.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for the update. The fix described in 54705335a addresses the original concern: it locates the actual first cluster rather than relying on the first video cue, and falls back when it cannot safely locate one. The new audio-only first-cluster test covers the reported scenario.

I haven’t independently verified the commit or run the test.

Comment thread internal/playback/keyframes/mux.go Outdated
Comment on lines +226 to +227
if ticks, ok := starts[e.Number]; ok {
t.Start, t.HasStart = float64(ticks)*scale-t.CodecDelay, true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug medium

Audio track timestamp scaling is omitted from mux-origin calculation

A non-default audio TrackTimestampScale can lead to the wrong first muxed packet and incorrect segment durations; readMatroska only rejects the video track's scale. Account for the selected audio track's scale or decline to plan it.

Prompt for LLM
File internal/playback/keyframes/mux.go, lines 226-227:

Audio track timestamp scaling is omitted from mux-origin calculation

Audio tracks with a non-default `TrackTimestampScale` have their block timestamps converted using only the segment scale, although only the video track's scale is rejected by `readMatroska`. This can select the wrong first muxed packet and serve incorrect planned segment durations; account for the selected audio track's scale or decline to plan it.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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.

Fixed in 5470533: the planning read now declines (ErrNoIndex) when any track has a TrackTimestampScale other than 1, so the session uses FFmpeg's playlist. This matches how a scaled video track was already handled.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for the fix. Declining to plan when any track has a non-default TrackTimestampScale addresses the concern by falling back to FFmpeg’s playlist, consistent with the existing handling for scaled video tracks.

I haven’t independently verified commit 54705335a.

Comment on lines +3409 to +3412
if s.copyPlan != nil && copyPlanAudio(s.opts) != s.copyPlan.audio {
// FFmpeg's cuts can move with the audio (#4049), so from now on a
// mismatch doesn't fault the file's Cues (checkCopyPlan).
s.copyPlanAudioChanged = true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug high

Audio switches retain segment durations planned for the previous track

Switching audio can change FFmpeg's segment boundaries while the playlist retains old durations, causing mismatches and incorrect seeking. Replan s.copyPlan for the new audio or start a new transport.

Prompt for LLM
File internal/playback/transcode.go, lines 3409-3412:

Audio switches retain segment durations planned for the previous track

Switching audio restarts FFmpeg with potentially different segment boundaries while the session continues serving the durations planned for the previous audio, causing playlist/segment mismatches and incorrect seeking. Replan the playlist for the new audio or start a new transport rather than retaining the old plan.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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.

Not changing. Before this PR an audio switch already restarted FFmpeg under a plan that didn't account for the audio, so this isn't new. The PR doesn't make it worse: it plans for the initial audio and stops a post-switch mismatch from disabling planning for the file. Replanning mid-session wouldn't help a client that already holds the full VOD playlist, which ends with ENDLIST. Starting a new transport on an audio switch is a separate jellycompat change.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Agreed. The audio-switch mismatch is pre-existing, and replanning the server-side playlist would not fix clients that already hold the completed VOD playlist. This PR improves the initial plan and prevents a post-switch mismatch from incorrectly disabling planning for the file.

I withdraw the suggestion for this PR. Starting a new transport on an audio switch belongs in a separate jellycompat change.

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.

Tracked in #4175 (the local in-place switch). #4044 covers the node-backed switch. The fix changes lines this PR changes, so it follows this PR.

🤖 Claude Code (claude-opus-5-5)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for clarifying. The audio-switch mismatch remains a known limitation: #4175 tracks the local in-place switch, and #4044 tracks the node-backed switch. Given the overlapping changes, the fix will follow this PR.

@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

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 43fe38f9-1c95-48b7-ad0e-014dffc23e4d
Commits

Reviewing files that changed from the base of the PR and between 061bbd1 and 4961496.

Files selected for processing: 13

  • docs/transcode-node-api.md
  • internal/matroska/ids.go
  • internal/matroska/tracks.go
  • internal/playback/copy_keyframe_plan.go
  • internal/playback/copy_keyframe_plan_test.go
  • internal/playback/keyframes/coverage.go
  • internal/playback/keyframes/ffmpeg_test.go
  • internal/playback/keyframes/matroska.go
  • internal/playback/keyframes/mux.go
  • internal/playback/keyframes/plan.go
  • internal/playback/keyframes/plan_test.go
  • internal/playback/prepare_tracks.go
  • internal/playback/transcode.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.

Comment thread internal/playback/copy_keyframe_plan.go Resolved
Comment thread internal/playback/keyframes/matroska.go Resolved
Comment thread internal/playback/keyframes/mux.go Resolved
Comment thread internal/playback/keyframes/mux.go Resolved
Comment thread internal/playback/keyframes/mux.go Resolved
The planning read now walks on to the file's first cluster when the Cues,
Info and Tracks precede the media, instead of taking the first cluster a
video cue points at, which can skip an audio-only cluster.

PlanMuxSegments declines to plan when a track carries a TrackTimestampScale
the starts don't apply, when the audio is encoded to AAC at an unknown or
resampled rate, and treats a first cluster with fewer than three video
frames as not ruling out a B-frame delay.
@silo-kody

silo-kody Bot commented Nov 13, 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 ❌
⚠️ 4 Kody Rule(s) were not evaluated

These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:

  • Preserve optional store capabilities through production wrappers
  • Detach mandatory cleanup from request cancellation and bound its lifetime
  • Preserve durable media identity and share identity-evidence precedence
  • Bound decoder throughput trades and share direct-play eligibility

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

Review of 5470533. The approach holds: on jellyfin-ffmpeg 8.1.3 (the version the image ships) and FFmpeg 6.1.1, main's planner disagrees with FFmpeg whenever copied or encoded AAC leads the video, and this branch matches, for both fMP4 and MPEG-TS segments. I found six problems in the new origin model, all on the inline comments below. Five can make a planned session serve a playlist that doesn't match FFmpeg's segments, and that mismatch then turns planning off for the file. The worst one, B-frame delay that the first cluster doesn't show, makes the branch wrong on files main plans correctly. I'm fixing all six in a commit on this branch, so there's no need to change anything yourself.

🤖 Claude Code (claude-opus-5-5)

Comment thread internal/playback/keyframes/mux.go Resolved
Comment thread internal/playback/keyframes/mux.go Resolved
Comment thread internal/playback/keyframes/mux.go Resolved
Comment thread internal/playback/keyframes/mux.go Resolved
Comment thread internal/playback/keyframes/mux.go Resolved
Comment thread internal/playback/keyframes/matroska.go Resolved
…nning

FFmpeg decodes copied video ahead of its first keyframe by the reorder
delay its H.264 or HEVC headers declare, which a first cluster without
B-frames doesn't show. Read that delay from the avcC/hvcC CodecPrivate,
and treat it as unknown when the headers don't declare it, so the planner
keeps the video-first origin and declines when the origins disagree.

Also put track starts on the Keyframes timeline when the video has a
CodecDelay, treat an AAC track at 24kHz or less with no output rate as an
unknown rate (implicit SBR), decline when encoded audio has no start in
the first cluster or another track starts any earlier than the audio,
and bound the walk to the first cluster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@silo-triage silo-triage Bot added size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. and removed size/XL 500–999 added + deleted lines (all files); change volume, not priority. labels Nov 14, 2026
@silo-kody

silo-kody Bot commented Nov 14, 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/keyframes/reorder.go Outdated
if len(avcC) < 8+n || n < 4 || avcC[8]&0x1f != 7 {
return 0, false
}
b := &rbspReader{data: unescapeRBSP(avcC[9 : 8+n])}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Kody Rules high

The first AVC SPS may not describe the active video stream

An incorrect reorder count can produce segment boundaries that differ from FFmpeg's. Resolve the active SPS from the first decoded access units, or decline planning when its reorder count cannot be established.

Also found in:

  • internal/playback/keyframes/mux.go:276-276
  • internal/playback/keyframes/reorder.go:217-217

Kody rule violation: Decline media plans when timing evidence is insufficient

Prompt for LLM
File internal/playback/keyframes/reorder.go, line 50:

The first AVC SPS may not describe the active video stream

The first SPS in an avcC record is not necessarily the SPS selected by the stream’s slices. If another SPS is active and signals a different reorder count, this can establish an incorrect timing assumption and produce segment boundaries that differ from FFmpeg’s. Resolve the active SPS from the first decoded access units, or decline planning when the active reorder count cannot be established.

**Also found in:**
- `internal/playback/keyframes/mux.go:276-276`
- `internal/playback/keyframes/reorder.go:217-217`

Kody rule violation: [Decline media plans when timing evidence is insufficient](https://kodus.siloserver.org/settings/code-review/1247142351/kody-rules/009cbe08-bfc1-4b8e-b4ec-4a9c63908227?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Comment thread internal/playback/keyframes/reorder.go Outdated
Comment on lines +46 to +50
n := int(binary.BigEndian.Uint16(avcC[6:8]))
if len(avcC) < 8+n || n < 4 || avcC[8]&0x1f != 7 {
return 0, false
}
b := &rbspReader{data: unescapeRBSP(avcC[9 : 8+n])}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug high

The reorder delay can come from an inactive SPS

A reorder count that differs from the active decoder delay can cause muxOrigins to select incorrect HLS segment boundaries. Resolve the SPS referenced by the video stream, or decline planning when SPS records have different reorder counts.

Prompt for LLM
File internal/playback/keyframes/reorder.go, lines 46-50:

The reorder delay can come from an inactive SPS

The first SPS in `avcC` or `hvcC` need not be the SPS referenced by the first video frame, so its reorder count can differ from the active decoder delay and cause `muxOrigins` to select the wrong HLS segment boundaries. Resolve the SPS referenced by the video stream, or decline planning when multiple SPS records have different reorder counts.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

An avcC or hvcC record with several SPSs doesn't say which one the stream
uses, so treat its delay as unknown. Read the bitstream restriction through
max_dec_frame_buffering against the RBSP length up to its stop bit, as
FFmpeg does: FFmpeg ignores a restriction the SPS cuts short.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@silo-kody

silo-kody Bot commented Nov 14, 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 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Review summary

Superseded by #1770, which merged to main during this review; see #4079 (comment). The scores below describe the branch before that merge and no longer apply.

Reviewed head: 5470533. Fixes pushed through 0906c9d.

Fit: 8/10 · Readiness: 9/10 — conditional

The change fixes a real correctness bug in the right place. The keyframe planner now predicts where FFmpeg's HLS muxer starts counting, and it declines when it can't. It stays behind the off-by-default playback.copy_keyframe_playlist setting, and declining falls back to FFmpeg's own playlist, the behaviour without the setting. Fit is held below 9 by cost: the planner now models FFmpeg internals (mux origin, encoder priming, decoder reorder delay), and that model has to keep matching FFmpeg as it changes. Telling FFmpeg where to cut would remove the model, but that is a larger packaging change. Readiness is 9: the fixes below were checked in live planned sessions on a sandbox as well as against FFmpeg directly. The verdict stays conditional because of Fit.

Addressed on this branch

  • B-frame delay the first cluster doesn't show (major). The planner now reads the reorder delay the H.264 or HEVC headers declare, from the avcC or hvcC CodecPrivate. When the headers declare none, declare it in more than one SPS, or cut the restriction short, the delay is unknown and the planner keeps the video-first origin. The parser agrees with ffprobe's has_b_frames on 11 x264 and x265 encodes, including High 10, 4:4:4 with custom scaling matrices, and 10-bit HEVC. As a side effect, plain -bf 2 files, which the branch declined before, now plan.
  • Track starts now sit on the keyframe timeline when the video has a CodecDelay.
  • The planner now declines in three more cases: another track starts even slightly before the selected audio, encoded audio has no start in the first cluster, or an AAC track at 24 kHz or less has no output rate (implicit HE-AAC).
  • The walk to the first cluster is bounded like the tail walk.

Live check

Evidence: https://evidence.siloserver.org/r/silo-server/pr-4079/

On a sandbox built first from 5470533 and then from 0906c9d (jellyfin-ffmpeg 8.1.3), sessions started through POST /api/v2/playback/start with the setting on.

  • The file whose headers declare B-frames it doesn't use, with AC3 encoded to AAC: on 5470533 the session served 1.98, 2.02, … while FFmpeg wrote 4, 2, …, and the server stopped planning the file. On 0906c9d it serves 4, 2, …, matching FFmpeg.
  • Encoded 8 kHz audio that misses the first cluster: on 5470533 the session served 4, 2 while FFmpeg wrote 1.96, 2.04, 2. On 0906c9d it declines and serves FFmpeg's own playlist.
  • Copied AAC that starts 21 ms before the video ([bug] Keyframe plan doesn't match FFmpeg's cuts when audio leads the video #4049): both builds serve FFmpeg's 1.98, 2.02, ….

Tests that failed before the fixes

  • On main's planner, the same FFmpeg runs disagree with the plan for copied AAC and for AC3 or AAC encoded to AAC, in both fMP4 and MPEG-TS. This branch matches. The PR's FFmpeg-in-the-loop test calls the new PlanMuxSegments, so it doesn't build on main; I compared the two planners directly instead.
  • These failed on 5470533 and pass now:
    • the FFmpeg-in-the-loop case B-frames signaled, none in the first cluster (6 segments planned, 5 written);
    • TestReadPlanIndexPutsStartsOnTheKeyframeTimeline;
    • the another track starts just before and encoded audio after the first cluster rows of TestPlanMuxSegments.
  • TestSignaledReorder failed on 241085c and passes now.
  • The FFmpeg tests pass with FFmpeg 6.1.1 and jellyfin-ffmpeg 8.1.3, the build the image ships.
  • Ruled out by running: audio 2.5 s ahead of the first keyframe, and the 5.1-to-stereo downmix filter shifting the first AAC packet. Both planned to match FFmpeg.

Left for the maintainers

  • Audio switch (predates this PR). After a Jellyfin mid-session audio switch, the session keeps serving the playlist planned for the old audio while FFmpeg restarts with the new one. This PR only stops that mismatch from disabling planning for the file. The earlier threads agree the real fix is a new transport on the switch, which belongs in a separate jellycompat change. Tracked in [bug] Jellyfin audio switch on a local keyframe-planned copy session keeps the playlist planned for the previous audio #4175, which follows this PR; [bug] Jellyfin audio switch on a node-backed planned copy session drops the planned playlist #4044 covers the node-backed switch.
  • copyPlanAudioChanged is set before the old FFmpeg run's exit check, and it isn't cleared when a failed restart rolls back. Either way, one genuine Cues mismatch can skip its rejection, and the next fresh playback checks again. That is low impact, and the description already accepts the rollback case.
  • A session rebuilt without its plan record replans for its current audio. After an audio switch, that plan can differ from the one the player holds. This is the same class as the audio-switch item.

Validation, manual, and clients

  • Validated features: I couldn't check them. The validation board query failed for lack of the read:project token scope. The changed code runs only with playback.copy_keyframe_playlist on, which is off by default. Validation tasks: none is plausible but unverified.
  • User manual: unaffected. The manual doesn't document this experimental setting.
  • Clients: server-only. The API and client requests are unchanged, so no Apple, Android or Roku follow-up is needed.
  • Review method: a multi-agent code review, then two cross-provider rounds (GPT-6.1 Sol), one on the original head and one on the fixes. Every finding was verified or refuted against the code or an FFmpeg run before it was fixed or dropped.

🤖 Claude Code (claude-opus-5-5)

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

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6bf7c73a-13aa-413d-8f8b-15dae2b7b559
Commits

Reviewing files that changed from the base of the PR and between 5470533 and 0906c9d.

Files selected for processing: 6

  • internal/playback/keyframes/ffmpeg_test.go
  • internal/playback/keyframes/matroska.go
  • internal/playback/keyframes/matroska_test.go
  • internal/playback/keyframes/mux.go
  • internal/playback/keyframes/plan_test.go
  • internal/playback/keyframes/reorder.go

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

if !track.HasStart {
// None in the first cluster: it starts after the video, unless an
// encoder's priming brings it forward by an unknown amount.
return []float64{k0}, audio.Encoder == AudioCopied

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.

Major · Functional Correctness · Quick win

Do not infer video-first ordering from missing audio in the first cluster.

The first cluster can omit both selected audio and video. For example, it can contain only an unselected audio track. Selected copied audio can then start at 0 in the next cluster, before video starts at 0.021.

For keyframes [0.021, 2.01, 4.021, 6.021], this branch accepts origin 0.021 and skips the 2.01 cut. FFmpeg receives selected audio first at 0 and cuts at 2.01 instead. Candidate agreement cannot detect this error because the branch supplies only the video origin. (raw.githubusercontent.com)

Decline planning unless the available metadata establishes that the missing copied audio starts after video.

@Quick104

Copy link
Copy Markdown
Contributor

This PR is superseded: #1770, merged to main today, changed keyframe-planned copies so FFmpeg cuts at every keyframe (a tiny -hls_time) and the session joins those groups into the planned segments itself. The planned boundaries no longer depend on which packet FFmpeg's HLS muxer counts its targets from, so the audio-lead problem this branch models can't move them. Main also accounts for audio that starts before the video (inputStart) and rebuilds segments when the audio changes (audioRecipeKey). This branch now conflicts with main in the same files, so I recommend closing it.

#4049 is still open; main resolves it, so it can be closed too. The review commits I pushed here (241085c, 0906c9d) go with the branch.

Thank you for the work, @Rhainland.

🤖 Claude Code (claude-opus-5-5)

@Quick104

Copy link
Copy Markdown
Contributor

Closing: superseded by #1770, as explained above.

🤖 Claude Code (claude-opus-5-5)

@Quick104 Quick104 closed this Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working impact: playback Can't play, stalls, or wrong media priority: P2 Limited scope, workaround exists, or polish size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Keyframe plan doesn't match FFmpeg's cuts when audio leads the video

2 participants