Repository navigation
fix(playback): transcode H.264 sources with conflicting in-band PPS - #424
Conversation
H.264 streams that redefine the same pic_parameter_set_id in-band with different content cannot be safely stream-copied into an avc1/fMP4 HLS segment: the avcC advertises a single parameter set, so VideoToolbox (Safari/Chrome on macOS) decodes with the wrong PPS and desyncs mid-GOP, surfacing as PIPELINE_ERROR_DECODE / kVTVideoDecoderBadDataErr (-12909). At playback start, a bitstream scan (DetectMultiplePPSH264) runs for H.264 files on the probe-ensure path, grouping in-band PPS by id and flagging any id carrying more than one distinct definition. The result is a runtime-only flag (VideoTrack.MultiplePPS, json:"-") memoized per process — never written to the database, no schema change, recomputed on the first play after a restart. The v3 planner and legacy resolver disqualify a copy-unsafe source from the video stream-copy / remux ladder, routing it to a real transcode. Direct play of the original container is left intact: decoders that reparse in-band parameter sets (ExoPlayer, VLC, native) handle the source fine. Part of #135.
📝 WalkthroughWalkthroughThe change adds H.264 PPS conflict scanning, stores the result as runtime media metadata, wires FFmpeg into playback probing, and prevents unsafe video stream-copy routes in the resolver and Protocol v3 planner. ChangesH.264 copy-safety playback
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant PlaybackProbeEnsurer
participant DetectMultiplePPSH264
participant MediaFile
participant SourceDescriptorV3
participant PlanPlaybackV3
PlaybackProbeEnsurer->>DetectMultiplePPSH264: scan eligible H.264 file
DetectMultiplePPSH264-->>PlaybackProbeEnsurer: conflicting PPS result
PlaybackProbeEnsurer->>MediaFile: set runtime MultiplePPS metadata
MediaFile->>SourceDescriptorV3: derive VideoCopyUnsafe
SourceDescriptorV3->>PlanPlaybackV3: provide copy-safety flag
PlanPlaybackV3->>PlanPlaybackV3: select remux or transcode
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/scanner/pps.go`:
- Line 71: Update the PPS comparison logic around byID in the scanner to key
entries by PPS payload rather than the complete NAL unit, excluding the first
header byte containing nal_ref_idc. Ensure identical payloads with different
valid header priority values are treated as non-conflicting and preserve
conflict detection for differing payloads.
In `@internal/scanner/probe_repair.go`:
- Around line 149-152: Update the probe-repair error path around the visible
return so scan failures are represented as copy-unsafe for the current
resolution while remaining uncached for retry. Introduce or reuse a distinct
runtime state for “scan unknown/failed” rather than setting MultiplePPS, and
ensure the resolver and both callers preserve this conservative result instead
of falling back to video stream-copy when the ensured file is discarded.
🪄 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: a919df4f-9613-4cad-a286-673c3150d48f
📒 Files selected for processing (11)
cmd/silo/main.gointernal/models/media.gointernal/playback/capabilities_v3.gointernal/playback/plan_v3.gointernal/playback/protocol_v3.gointernal/playback/protocol_v3_test.gointernal/playback/resolver.gointernal/playback/resolver_test.gointernal/scanner/pps.gointernal/scanner/pps_test.gointernal/scanner/probe_repair.go
* refactor(playback): stop ending stream copies on the copy-safety verdict The H.264 multi-PPS verdict no longer withdraws a copy that is playing or refuses to rebuild one. A copy that plays has shown its decoder handles the source; one that fails reports it, and the recovery replan plans against the persisted verdict. Removes CopySafetyNotifier and its handler adapter, the race's notify and recheck passes, and the revival, reconstruct and rehome refusals. The race now only scans and persists. The plan_invalidated protocol stays, with no producer. * fix(playback): rescan a file whose scan request arrived mid-scan The race deduped a request for a file whose scan was already running and dropped it. When the file was rewritten in place during that scan, the scan came back stale and persisted nothing, so the replacement stayed unscanned until a later play asked again. A request that lands mid-scan now owes the running goroutine one more pass, as main's race did before the notifier was removed. That pass takes the known-verdict path, with no ffmpeg, unless the verdict is still unknown. * fix(playback): stop forcing a transcode for multi-PPS H.264 A source flagged multi-PPS skipped every video stream-copy route, so a client that could not direct-play it always got a full transcode, even when its decoder (Media3 on Android, the Apple app's FFmpeg fallback) plays a copy cleanly. That gate dates from #424, when the web player stopped on the first decode error. The planner now treats such a source like any other. A strict decoder (VideoToolbox in a browser) fails direct play and each copy, reports it, and the ordinary recovery walk ends at the encode. Downloads, which cannot recover, still encode these sources through the download policy. * test(playback): keep the start-path copy-safety race covered Restore TestStartPlaybackV2DoesNotBlockOnCopySafetyScan without the deleted RaceScan and VideoCopyUnsafeKnown stubs. Start still uses only the cached ensure and hands its plan to the racer, which is now the only way a play persists the verdict. The race dedupe test waits for the race to retire instead of a fixed sleep, so it would catch an extra follow-up scan. * fix(playback): keep strict browsers encode-first for multi-PPS H.264 Safari and Chrome on a Mac fail every copy of a copy-unsafe source. The recovery walk got them to the encode, but a track, quality or reconnect replan drops the attempted keys, so the planner offered the failed copies again in the middle of playback. Web clients other than Firefox now get the encode up front for these sources, as before; Firefox and the native apps keep the copy. The flagged-source test now also walks a strict decoder's recovery to the encode and covers the Safari, Chrome and Firefox user agents. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(playback): describe the copy-safety verdict as it now works Drop comments and docs that still describe the removed withdrawal of a playing copy, say that downloads never remux a flagged source rather than always encoding it (Resolve keeps the original when the client plays it), note that a failed synchronous scan also marks a source copy-unsafe, document the strict-browser exception, and bound the wait for the first scan in the mid-scan rescan test. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(playback): keep strict browsers off direct play of multi-PPS H.264 Safari and Chrome fail a multi-PPS H.264 source as is, not only copied. An MP4 they accept still got direct play, and a track, quality or reconnect replan offered it again after it failed. They now get neither direct play nor a copy of a flagged source; Firefox keeps both. The test covers an MP4 source for each browser. The docs now also say when a download keeps the original file and which plans start the scan. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Quick104 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Problem
Some H.264 movies fail to play in the web player with a hard decode error.
A subset of 1080p H.264 library titles, when played through the browser player on
macOS (both Safari and Chrome, which decode video in hardware via VideoToolbox),
throw a decode error a second or two into playback and never recover:
From the operator's side the session starts normally, the player re-requests the
first couple of segments (the browser retrying after a fatal media error), and
then the session is torn down. The exact same titles play correctly everywhere
else — the mobile and TV native apps, VLC, and Firefox — so nothing looks wrong
with the file itself, and it plays end-to-end when fully decoded offline. The
breakage is specific to the browser + hardware-decode path.
Solution
Root cause. The affected titles are H.264 streams that carry their encoding
parameter sets in-band, redefining the same parameter-set id repeatedly
with different contents across the opening frames (the per-frame reference
count changes). When the server stream-copies such a stream into an
avc1/fMP4HLS segment, the segment's single declared parameter set (
avcC) disagrees withthe per-frame ones. A strict decoder that honors
avc1— VideoToolbox — configuresonce from the declared set and desyncs when the stream switches mid-GOP, which is
exactly the
-12909decode failure. Decoders that re-parse in-band parameter setsper frame (ExoPlayer, VLC, Firefox's software path) are unaffected, which is why
only the browser hardware-decode surface breaks.
Making the container honest by tagging the copy
avc3(which advertises in-bandparameter sets) was evaluated and does not fix it: VideoToolbox only
reconfigures its decode session at IDR boundaries, and these streams switch
mid-GOP, so the honest tag changes nothing the decoder acts on. The reliable fix
is to stop stream-copying these sources and give the client a freshly encoded,
single-parameter-set stream instead.
Detection.
DetectMultiplePPSH264(internal/scanner/pps.go) runs atplayback start for H.264 sources: it stream-copies the opening seconds through
ffmpeg's
filter_unitsbitstream filter, groups the in-band parameter sets byid, and flags any id that carries more than one distinct definition. A source
that legitimately uses several distinct ids (each defined once) is not
flagged — only conflicting redefinitions of a single id are. The result is a
runtime-only flag (
models.VideoTrack.MultiplePPS, taggedjson:"-") memoizedper process in
PlaybackProbeEnsurer(internal/scanner/probe_repair.go). It isnever written to the database — no schema change, no migration — and is
recomputed on the first play after a restart (~0.2s, a stream-copy demux, run
once per file per process).
Routing. The v3 planner (
internal/playback/plan_v3.go) and the legacyresolver (
internal/playback/resolver.go) disqualify a copy-unsafe source fromthe video stream-copy / remux ladder, so it falls through to a real transcode
(
planVideoTranscodeV3/PlayTranscode). Direct play of the original containeris deliberately left intact: clients that reparse in-band parameter sets handle
the untouched source fine and should not be forced to transcode. The flag reaches
the planner through the existing source descriptor (
SourceDescriptorV3.VideoCopyUnsafein
internal/playback/capabilities_v3.go), so the planner stays pure.Risk / follow-ups
That is more server load for that class of file, but it is the correct trade
for reliability — the copy is simply not decodable on the browser path.
scope here.
restart rather than persisted. If the per-play warm-up cost ever matters, the
same detector result could be persisted on the file's probe metadata later.
(the web player uses HLS, so this path is not exercised in practice); it remains
a theoretical residual.
Verification
go build ./...,go vet ./internal/playback/... ./internal/scanner/..., andgo test ./internal/playback/... ./internal/scanner/...all pass.several distinct ids are treated as safe, while the same id redefined with
conflicting content is flagged (
internal/scanner/pps_test.go), plus theExp-Golomb id parser.
while an otherwise-identical copy-safe source still remuxes
(
internal/playback/protocol_v3_test.go,internal/playback/resolver_test.go).-12909decode error on an affected H.264 remux throughmacOS Chrome, confirmed the detector flags the source, and verified the resulting
session runs a real encode instead of a video stream-copy.
AI-use disclosure
Implemented with Claude Code.
Summary by CodeRabbit
Maintainer remediation (2026-07-29)
AI Disclosure
nal_ref_idcand a fail-open FFmpeg scan-error path; both were fixed with focused tests. Broader route, scan-lifecycle/concurrency, cache-identity, and naming findings remain report-only.Maintainer remediation verification
go test ./internal/playback/... ./internal/scanner/...— passedgo test -race ./internal/playback/... ./internal/scanner/...— passedgo build ./...andgo vet ./...— passedgolangci-lintpass for affected packages — 0 issues; the checked-in v2 config fails schema validation for the repo-wide commandmake verify-local-paths,git diff --check, frontend production build, frontend format check — passed/usr/lib/jellyfin-ffmpeg/ffmpeg; readiness and container health remained OKgo test ./...still failsTestHandleReplanPlaybackV3SeekFailureRecoveryNeverChangesMediaVersion; the focused changed-package suites above pass