Skip to content

fix(playback): transcode H.264 sources with conflicting in-band PPS - #424

Merged
Quick104 merged 2 commits into
mainfrom
fix/hls-copy-multi-pps-transcode
Jul 29, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/hls-copy-multi-pps-transcode

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

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:

Playback error: PipelineStatus::PIPELINE_ERROR_DECODE:
Error Domain=NSOSStatusErrorDomain Code=-12909 "(null)" (-12909): VTDecompressionOutputCallback

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/fMP4
HLS segment, the segment's single declared parameter set (avcC) disagrees with
the per-frame ones. A strict decoder that honors avc1 — VideoToolbox — configures
once from the declared set and desyncs when the stream switches mid-GOP, which is
exactly the -12909 decode failure. Decoders that re-parse in-band parameter sets
per 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-band
parameter 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 at
playback start for H.264 sources: it stream-copies the opening seconds through
ffmpeg's filter_units bitstream filter, groups the in-band parameter sets by
id, 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, tagged json:"-") memoized
per process in PlaybackProbeEnsurer (internal/scanner/probe_repair.go). It is
never 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 legacy
resolver (internal/playback/resolver.go) disqualify a copy-unsafe source from
the video stream-copy / remux ladder, so it falls through to a real transcode
(planVideoTranscodeV3 / PlayTranscode). Direct play of the original container
is 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.VideoCopyUnsafe
in internal/playback/capabilities_v3.go), so the planner stays pure.

Risk / follow-ups

  • Affected sources now transcode for every client instead of stream-copying.
    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.
  • Detection is H.264-only. HEVC uses a different parameter-set model and is out of
    scope here.
  • The flag is runtime-only by design: it is recomputed on the first play after a
    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.
  • Direct progressive-MP4 playback of an affected source in a browser is not gated
    (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/..., and
    go test ./internal/playback/... ./internal/scanner/... all pass.
  • New unit tests cover the bitstream analysis: a single repeated parameter set and
    several distinct ids are treated as safe, while the same id redefined with
    conflicting content is flagged (internal/scanner/pps_test.go), plus the
    Exp-Golomb id parser.
  • New planner and resolver tests assert a copy-unsafe source routes to a transcode
    while an otherwise-identical copy-safe source still remuxes
    (internal/playback/protocol_v3_test.go, internal/playback/resolver_test.go).
  • Manually reproduced the -12909 decode error on an affected H.264 remux through
    macOS 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

  • Bug Fixes
    • Improved playback reliability for H.264 videos with conflicting parameter sets.
    • Unsafe video-copy paths now automatically fall back to full transcoding, preventing potential playback desynchronization.
    • Safe sources continue using efficient remuxing where supported.
  • Performance
    • Copy-safety analysis results are reused during runtime to avoid repeated scans.
  • Tests
    • Added coverage for safe and unsafe playback decisions and H.264 parameter-set detection.

Maintainer remediation (2026-07-29)

AI Disclosure

  • Tool(s): Codex in T3 Code
  • Model(s): gpt-5.6-sol
  • Involvement: AI-assisted maintainer remediation
  • Adversarial review: The two-axis Standards/Spec review found false PPS conflicts caused by comparing nal_ref_idc and 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/... — passed
  • go test -race ./internal/playback/... ./internal/scanner/... — passed
  • go build ./... and go vet ./... — passed
  • New-code golangci-lint pass for affected packages — 0 issues; the checked-in v2 config fails schema validation for the repo-wide command
  • make verify-local-paths, git diff --check, frontend production build, frontend format check — passed
  • Dev backend live probe under the shared lock: file 22072449 remuxed with the valid FFmpeg path, selected transcode and logged the fail-closed warning with an intentionally missing FFmpeg path, then remuxed again after restoring /usr/lib/jellyfin-ffmpeg/ffmpeg; readiness and container health remained OK
  • Known unrelated baseline: go test ./... still fails TestHandleReplanPlaybackV3SeekFailureRecoveryNeverChangesMediaVersion; the focused changed-package suites above pass

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

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

H.264 copy-safety playback

Layer / File(s) Summary
PPS conflict detection
internal/scanner/pps.go, internal/scanner/pps_test.go
FFmpeg extracts PPS NAL units for H.264 files; Annex-B parsing and Exp-Golomb decoding identify conflicting definitions, with parser coverage added.
Probe orchestration and metadata
internal/models/media.go, internal/scanner/probe_repair.go, cmd/silo/main.go
PlaybackProbeEnsurer receives the FFmpeg path, scans eligible files with cached results, and returns runtime MultiplePPS metadata without mutating the original file.
Resolver copy-safety routing
internal/playback/resolver.go, internal/playback/resolver_test.go
Resolver remux decisions now require copy-safe video; tests cover both transcode and remux outcomes.
Protocol v3 descriptor and planning
internal/playback/protocol_v3.go, internal/playback/capabilities_v3.go, internal/playback/plan_v3.go, internal/playback/protocol_v3_test.go
Protocol v3 carries VideoCopyUnsafe, excludes unsafe sources from progressive remux, and tests safe and unsafe planning paths.

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
Loading

Possibly related PRs

Suggested labels: v1

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.17% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: routing H.264 sources with conflicting PPS to transcode.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/hls-copy-multi-pps-transcode

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.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 17, 2026

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

📥 Commits

Reviewing files that changed from the base of the PR and between b96e359 and 4d2b2f7.

📒 Files selected for processing (11)
  • cmd/silo/main.go
  • internal/models/media.go
  • internal/playback/capabilities_v3.go
  • internal/playback/plan_v3.go
  • internal/playback/protocol_v3.go
  • internal/playback/protocol_v3_test.go
  • internal/playback/resolver.go
  • internal/playback/resolver_test.go
  • internal/scanner/pps.go
  • internal/scanner/pps_test.go
  • internal/scanner/probe_repair.go

Comment thread internal/scanner/pps.go Resolved
Comment thread internal/scanner/probe_repair.go Resolved
@Quick104
Quick104 merged commit a760102 into main Jul 29, 2026
1 check passed
@Quick104
Quick104 deleted the fix/hls-copy-multi-pps-transcode branch July 29, 2026 13:49
Quick104 added a commit that referenced this pull request Nov 23, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants