Skip to content

feat(playback): restart keyframe-planned copy streams mid-stream - #1770

Merged
Quick104 merged 100 commits into
Silo-Server:mainfrom
rangoDJ:fix/copy-remux-vod-playlist-1466-part3
Nov 14, 2026
Merged

Quick104 merged 100 commits into
Silo-Server:mainfrom
rangoDJ:fix/copy-remux-vod-playlist-1466-part3

Conversation

@rangoDJ

@rangoDJ rangoDJ commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #1466 (part 3 of the copy-remux VOD playlist)
Part 2 (#1760) has merged into main. The later parser repairs on #1756 are separate and are not included here. This PR adds mid-stream restarts and group assembly on that base.
Builds on #2515 (fix for #2453), now merged: plans come from the file's Cues, without the full keyframe check. Here the check that the plan matches the file moves into the group assembler: a group that starts where the plan has no keyframe, or a planned keyframe FFmpeg skips, stops the run and rejects the file version (keyframes.Reject), so later playbacks keep FFmpeg's playlist.
Validation tasks: none
No passed case is affected: with the setting off, every changed path behaves as on main. The related copy-remux cases (#1250 C5, #1252 C3 and C5, #1246 C1, and the matching Apple and Android Series cases) are Not run.

With part 2, a keyframe-planned stream can only restart from the beginning. FFmpeg's HLS muxer counts its cuts from where it starts, so a seek restart would cut at keyframes the playlist doesn't list. Instead, a seek ahead of FFmpeg waits for it to copy that far, and a seek back past pruned segments recopies from the start. On slow storage either can outlast a player's segment timeout. This PR lets a planned stream restart anywhere, as the design on #1466 describes.

Approach

  • FFmpeg cuts at every keyframe. A planned run uses a tiny hls_time, so each file it writes, gop<run>_NNNNNN.m4s, holds one keyframe group. A group's boundaries don't depend on where FFmpeg started.
  • The session joins groups into the planned segments. A copyGroupAssembler watches the run's groups:
    • it reads where each group starts (its video tfdt plus the first sample's composition offset) and maps it to a keyframe of the plan;
    • once every keyframe of a planned segment has its group, it writes seg_NNNNN.m4s and removes the groups;
    • the joined segment keeps every moof/mdat pair and the first styp, and drops sidx, whose byte ranges would be wrong. Fragment offsets are moof-relative, so this is a plain concatenation.
  • One timeline across runs. A run from the file's start is shifted by the source's B-frame delay and a seek restart isn't. Without a fix that leaves a step, 59 ms in the test, where their segments meet. The assembler measures each run's shift and rewrites tfdt in the segments it writes, moving every run onto the first run's timeline.
  • Audio priming before zero. A run that encodes audio from the file's start can need a negative shift: switching at 0:00 to a track whose AAC priming comes before the video. A tfdt can't go below zero, so the assembler drops that fragment's audio samples that end by zero and starts the fragment at the first one it keeps. The samples it keeps stay where the timeline puts them, so there is no discontinuity; only the first one or two audio frames go. A video fragment that would go below zero is still an error.
  • Restarts. A missing segment within ten of the assembled head is waited for. Anything else restarts FFmpeg at that segment, seeking to the keyframe before it so a seek that lands a keyframe early still covers it. Segments already assembled belong to the plan rather than a run, so they survive restarts. If the audio recipe changes (another track), they're dropped.
  • Rebuilds keep the planned playlist.
    • A planned session's persisted recipe (RecipeOpts) keeps the first run's start, not the start of the latest restart. The plan, not the run, is the session's timeline, so a session rebuilt after an audio switch plans the same segments from the verified index again. A segment request then restarts FFmpeg at the player's position.
    • A plan record written by feat(playback): serve copy remux from a complete keyframe playlist #1760 holds only durations. A rebuild plans again from the verified index and keeps the plan if its durations match, upgrading the record. If they don't match, or the index gives no plan, the rebuild fails with ErrKeyframePlanChanged: no session can serve that playlist, so the player needs a new playback session rather than a silent switch to FFmpeg's playlist.
  • Progress, readiness and pruning come from the plan. SegmentProgress, the startup readiness check behind WaitForManifest, and the pruner's retention window read the assembler and the plan's durations instead of FFmpeg's playlist. The planned mode now needs fMP4; MPEG-TS copy (webOS Dolby Vision) keeps FFmpeg's playlist.

Validation

Run in WSL2:

  • End to end with real FFmpeg. An MKV with irregular keyframes runs from the start; every assembled segment's start matches the plan. The test then deletes the second half (as if pruned) and restarts mid-stream at segment 9. The restarted run reassembles those segments to the plan, leaves the earlier ones untouched, and lines up with them within 2 ms. No group files are left, and the whole assembled stream decodes without errors. This passes with FFmpeg 8.0.1 and with jellyfin-ffmpeg 8.1.3.
  • Early audio switch with real FFmpeg (TestPlannedCopySessionSwitchesAudioAtTheStart). The source has B-frame-free H.264 and two FLAC tracks, the first starting 100 ms late, and audio is encoded to AAC. The test switches to the other track at 0:00, and segment 0 must assemble and decode cleanly. It fails without the priming fix (negative decode time, segment 0 never assembled) and passes with it on FFmpeg 8.0.1 and jellyfin-ffmpeg 8.1.3.
  • Rebuild regressions:
    • TestRecipeOptsKeepsAPlannedSessionAtItsStart: a planned session restarted at segment 2 persists a recipe that still plans.
    • TestResolveCopyPlanMigratesADurationsOnlyRecord: a feat(playback): serve copy remux from a complete keyframe playlist #1760 record with matching durations becomes a full plan record. Mismatched durations, or an index that gives no plan, fail with ErrKeyframePlanChanged.
    • TestShiftFMP4DecodeDropsAudioBeforeZero: the priming trim, its data offsets, and a fragment wholly before zero.
  • Unit tests cover the fMP4 helpers (video track and first presentation time, joining, tfdt shifting), the plan's keyframe ranges, restart seek and retention floor, the missing-segment decisions, and the restart target.
  • Existing suites pass: internal/playback/..., internal/jellycompat, and the internal/api/handlers tests for the changed recipe call.
  • Lint: golangci-lint on the changed packages, from current main, is clean.
  • A local server, with a Safari-style HLS client request, restarts a planned stream mid-stream and serves the planned segment (see Evidence). Not yet played in Safari or on a device. Before turning the setting on by default: Safari native HLS through a long episode with seeks, hls.js, Media3, and Jellyfin Web through Jellycompat, on real library files.

Evidence

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

The page has the latest checks, at c428fd3d2 and e3f7b2669. Two dev-builder sandboxes, one built from main and one from this branch, get the same Safari-style native HLS start on a 2-hour H.264 MKV, with the setting on. A request for segment 978 (minute 73) one second after start takes 29.1 s on main, which waits for the copy from the start, and 0.40 s and 0.86 s on this branch, which restarts FFmpeg at the keyframe before the segment. Restarted segments sit on the from-start run's timeline (0.082 s after their playlist position, like segments 0, 100 and 200) and decode cleanly. It does not establish real-player playback.

Recovery and audio-switch fixes

None of the three fixes changes anything on screen: they are server-side recovery paths behind the same off-by-default setting, so there is no new screenshot to take. The settings screenshots below still show the only visible change. The effect of each fix is in the server's output.

Early audio switch. The TestPlannedCopySessionSwitchesAudioAtTheStart source, switching to the second audio track at 0:00.

Before (da00acbbf):

WARN keyframe playlist: assemble segment component=playback segment=0 error="malformed fMP4 box: negative decode time"
copy_keyframe_plan_test.go:849: after switching: segment 0 was never assembled

After: segment 0 assembles, and init plus segment 0 decode with ffmpeg -xerror and no output.

ok  github.com/Silo-Server/silo-server/internal/playback  18.004s   (FFmpeg 8.0.1)
ok  github.com/Silo-Server/silo-server/internal/playback  17.756s   (jellyfin-ffmpeg 8.1.3)

Rebuild after an audio switch. Before, the recipe persisted the restart's seek and segment. A rebuild without its plan record read that as a mid-stream start, recorded planned:false, and served FFmpeg's growing playlist to a player holding the VOD one. After, the recipe keeps the first run's start, and the rebuild plans the same segments.

#1760 plan records. Before, a durations-only record failed the new field checks and the session silently went unplanned. After, it is upgraded from the verified index when the durations match, and otherwise the rebuild fails with ErrKeyframePlanChanged.

Mid-stream restart (earlier pushes)

The author's original timing comparison and captures below are historical, at the source revisions they name, and have not been repeated for the current head.

The same requests on the same server data, first on #1760 (part 2, this PR's base), then on this branch, both with Complete playlists for copied video on. #1760's Evidence section shows the change from main: the setting and the complete playlist.

The source is a 20-minute MKV with irregular keyframes (H.264 video, AC3 5.1 audio). A Safari-style client that plays only HLS starts playback at 0:00 (server_remux_hls, video copied), gets the 369-segment planned playlist (1200.000 s, #EXT-X-ENDLIST), and one second later requests segment 277, which starts at 902.708 s, far ahead of what FFmpeg has copied.

Before (#1760): the request waits for FFmpeg to copy from the beginning to minute 15.

transcode segment missing  segment=seg_00277.m4s produced_head=16 wait_timeout_ms=30000 reason=planned_segment_ahead
GET seg_00277.m4s -> 200 after 19.96 s, first video frame at 902.737 s

After (this branch): FFmpeg restarts at the keyframe before the segment.

transcode segment missing  segment=seg_00277.m4s produced_head=16 wait_timeout_ms=3500 restart_on_timeout=true reason=planned_segment_restart
ffmpeg restart cmd: ffmpeg ... -ss 897.417 -noaccurate_seek -i ...
GET seg_00277.m4s -> 200 after 0.41 s, first video frame at 902.737 s

Both segments start on the same frame, where the playlist places them, and init plus segment decode without errors.

The setting is the one #1760 adds, in Playback → Advanced, off by default:

Before (main) Added (off by default) Turned on
Admin Playback Advanced settings on main, without the setting Admin Playback Advanced settings with Complete playlists for copied video, off Complete playlists for copied video turned on

Surface and build: native playback API, local builds of #1760 at 7801c3dbf and this branch at 2965f56ab against one database, with generated test media.

Risks

  • Off by default. Nothing changes until an admin turns the setting on.
  • More files. One file per keyframe group exists briefly until its segment is assembled.
  • A group that can't be placed stops that run's assembly, logged with the group. A later restart starts a fresh run.
  • The timeline shift is applied when writing, so a segment is never served partly shifted.
  • The priming trim drops at most the first audio frame or two of a run that starts at the file's beginning. It applies only when the shift would put audio before zero, and only to fragments FFmpeg bases on their moof, as it writes them.
  • A feat(playback): serve copy remux from a complete keyframe playlist #1760 session whose plan can't be reproduced fails its rebuild instead of falling back silently, so its player starts a new playback session.

Review fixes and remaining work

At da00acbbf, groups select the nearest keyframe within timestamp tolerance, and the process monitor drains final group assembly before reporting completion. The focused regressions, playback/config race tests, changed-package lint, and Jellyfin FFmpeg 8.1.3 restart/decode tests pass. Two local Jellycompat Dolby Vision tests also fail on current main and remain baseline failures.

The three open review concerns are fixed in this push, with the policies the author chose:

  • Reconstruction after an audio switch: the rebuild keeps the plan and its timeline.
  • Records from the previous version: they migrate from the verified index, or the rebuild is rejected explicitly.
  • Negative AAC timestamps after an early audio switch: the priming before zero is trimmed, keeping the timeline continuous rather than starting a new HLS timeline.

The setting remains off by default.

User manual: Silo-Server/siloserver.org#198 tracks /docs/playback: the experimental/off-by-default setting, fMP4 eligibility, background keyframe verification/first-play fallback, and seek/recovery behavior. The setting and background verification landed in #1760; #1770 proposes the fMP4 assembly and mid-stream recovery changes. The required manual-impact issue is open. Documentation of #1770-specific shipped behavior waits for merge and playback verification; player/Safari acceptance remains untested. Apple and Android need playback verification, but no new client API implementation was identified. Jellycompat uses the shared path.

Review fixes at 7a7654722, c428fd3d2 and e3f7b2669

main is merged in at fc62fd380. The one conflict was in TranscodeSession.restart, and both sides were kept. A maintainer review of that merge found three defects on the planned path, all fixed on this branch:

  • A prune notice that arrived after a restart rebuilt the segment no longer unmarks it.
  • A native request for a lost planned session whose plan record can't be served again now ends the session (410 playback_session_ended). Before, it answered 404 and left the rebuilt session holding a stream slot.
  • A seek restart no longer waits while the replaced run's backlog is assembled. FFmpeg can copy hundreds of segments ahead of the assembler on fast storage. In the live check, the restart started 10 s late.
  • A restarted run whose first groups fit more than one keyframe (evenly spaced keyframes near the seek) holds them until later groups show which, instead of taking the later one and rejecting a valid file.
  • A queued restart for a segment the new run already passed and pruned now restarts. Before, it waited for a file nothing would write and ended in a 404.

Each fix has a regression test that fails without it.

Review fixes at 798c2ab5e

A maintainer review of df73a7d8b found ten defects on the planned path; one commit on this branch fixes them (see the review threads):

  • Subtitle renditions on planned sessions follow the run's own progress, and their timing after a mid-stream restart is measured from the planned segment.
  • A run is anchored from its first two groups, so a seek that lands on an earlier keyframe still places them.
  • Audio wholly before zero after an early switch is dropped.
  • A run that stops assembling stops FFmpeg and fails the session.
  • A failed ffprobe on a rebuild records nothing.
  • The timeline offset is kept in the plan record.
  • ErrKeyframePlanChanged is terminal: 410 playback_session_ended natively, 404 on jellycompat.

A planned restart also waits, up to 3 s, for the run it replaces to set the session's timeline, so a session rebuilt without its output directory keeps the from-start timeline. The setting's description, which still says a seek ahead waits, is fixed in Silo-Server/silo-translations#19; once that release is out, this branch syncs it with scripts/sync-translations.

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

  • Review fixes: Codex (gpt-6.1-sol, xhigh), six read-only GPT-6.1 Sol review agents, and one read-only Claude Opus 5.5 (claude-opus-5-5, high) round. The two bounded repairs were written by Codex and checked with focused tests and sandbox evidence.

  • Recovery and priming fixes: Claude Code (claude-opus-5-5), with the author's choice of policies, checked with focused tests and real FFmpeg in WSL2.

  • Merge of main and the fixes at 7a7654722, c428fd3d2 and e3f7b2669: Claude Code (claude-opus-5-5), with one read-only review round by Codex (gpt-6.1-sol, xhigh). Checked with focused tests, real FFmpeg in the sandbox image, and live sandbox requests.

  • Harness: Claude Code (Claude desktop app, Code tab)

  • Tool(s): Claude Code, GitHub CLI, FFmpeg/ffprobe (upstream 8.0.1 and jellyfin-ffmpeg 8.1.3) in WSL2

  • Model(s): claude-opus-5-5

  • Involvement: Fully AI-generated, human verified

  • Adversarial review: Self-review. It checked that a restart keeps assembled segments but removes the previous run's groups; that pruned segments are rebuilt when a later run reaches them; and that the startup readiness check and the throttler read the assembler rather than a playlist that no longer exists. It also checked that the measured timeline step between runs is removed rather than assumed away, and that MPEG-TS copy stays on FFmpeg's playlist. For this push, it checked that the priming trim moves every trun's data offset in a moof that shrinks, and refuses fragments not based on their moof.

🤖 Generated with Claude Code

Summary

Adds an opt-in, keyframe-planned VOD playlist for eligible copy-remux playback, allowing FFmpeg to restart mid-stream without changing the segment list already provided to the player. This is intended to address Safari playback stalls caused by growing, partial HLS playlists.

Changes

  • Adds the experimental Complete playlists for copied video playback setting (playback.copy_keyframe_playlist), disabled by default.
  • Generates complete playlists for fMP4 video-copy sessions that start at the beginning and have a verified Matroska/WebM keyframe index, known video end, and usable source start time. Ineligible sources and sessions retain FFmpeg’s existing playlist behavior.
  • Checks keyframe indexes in the background and caches results. Playback falls back to the growing playlist while verification is pending. Planned playlist duration ends with the video rather than longer audio or subtitle tracks.
  • Supports missing-segment recovery by waiting for nearby output or restarting FFmpeg near the requested segment. Output from different runs is assembled into the same planned segments and aligned to a shared timeline.
  • Preserves assembled segments across restarts when the audio recipe is unchanged, supports rebuilding pruned segments, and uses planned segment durations for retention.
  • Records each session’s planning decision and carries the setting through playback recipes, stream tokens, local and remote playback, and Jellyfin-compatible sessions.
  • Rejects remote executors that do not acknowledge a requested keyframe-playlist option; requests without the option remain compatible with older nodes.

Tests Added

Adds coverage for keyframe parsing, verification and caching; segment planning and manifests; recovery decisions; persisted planning decisions; recipe and token preservation; remote acknowledgment; and fMP4 assembly and timestamp alignment. FFmpeg integration tests cover irregular keyframes, shifted source timestamps, delayed video starts, mid-stream restarts, and decoding assembled output.

Automated Review Findings

Two high-severity findings were reported:

  • Pruned segments retain assembled flags, which can overstate restart progress and throttle FFmpeg before missing segments are regenerated.
  • The FFmpeg comparison does not validate the final segment’s duration or compare total playlist duration with measured output duration.

Note

Support mid-stream restarts for keyframe-planned copy streams

  • Planned-copy sessions now assemble fMP4 keyframe groups written by FFmpeg into planned segments, replacing the old FFmpeg-playlist inspection path (checkCopyPlan, checkCopyPlanOutput, and related helpers are removed). See copy_group_assembler.go and copy_keyframe_plan.go.
  • Restarts use the copy plan: TranscodeSession.restart seeks to the restart keyframe and starts a new assembler run at the requested segment. A new seen-generation timestamp on RestartSegmentLocked / RestartSegmentSince skips a restart when a newer run already covers the segment.
  • Plan records are expanded to persist keyframes and the input start, with migration of older durations-only records; unrebuildable plans return the new ErrKeyframePlanChanged, which handlers map to a session-ended response. Subtitle spans and progress reporting now derive timing from the assembler and plan.
  • Risk: old durations-only plan records for MPEG-TS copy or mismatched durations now fail with ErrKeyframePlanChanged and end the session (HTTP 410/404) instead of serving; check migrateCopyPlanRecord in copy_keyframe_plan.go and the error mappers in playback_missing.go and streams.go.

Macroscope summarized e3f7b26.

rangoDJ and others added 10 commits September 30, 2026 19:42
A complete VOD playlist for copied video needs the segment boundaries
before FFmpeg starts (Silo-Server#1466). This reads the video keyframe times from a
Matroska file's Cues, following the seek head to Cues stored after the
clusters and never reading the clusters, and plans segment starts with
the rule FFmpeg's HLS muxer uses for copied video: cut at the first
keyframe at or after the target, then move the target on one segment.

Tests check the reader against ffprobe and the plan against the
segments FFmpeg writes, on a file with irregular keyframes; they skip
without ffmpeg.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copy-remux HLS served FFmpeg's growing playlist, and Safari's native
player can fall back to a partial copy of it and stop mid-episode
(Silo-Server#1466). Behind the new playback.copy_keyframe_playlist setting (off by
default), a copy stream that starts at the beginning is served as one
complete VOD playlist, planned from the source's Matroska Cues.

From the start of the file FFmpeg's HLS muxer cuts copied video at the
planned keyframes, so its seg_NNNNN files are the planned segments. A
seek restart would cut elsewhere, so until mid-stream restarts land a
planned session waits for segments ahead of FFmpeg and restarts from
the beginning when one is gone. The flag is frozen into recipe cards,
stream tokens, transcode-node requests and Jellycompat's play-session
source so rebuilt sessions keep the playlist.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The transcode-node start request gained keyframe_playlist; the system
info fixture carries the contract digest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ists

Review fixes for the keyframe playlist:

- Matroska recommends but doesn't require a cue for every video keyframe,
  and a plan missing one would cut segments where FFmpeg doesn't. The
  reader now checks a few clusters spread through the file, and the
  cluster after each, reading only block headers, and reports
  ErrIncompleteIndex (an ErrNoIndex) if any video keyframe has no cue.
- A transcode node attests that it understood a requested keyframe
  playlist; both remote start paths reject a node that doesn't, as they
  do for the throttle and copy recipes.
- Jellycompat records the flag only for copy streams, after subtitle
  delivery can turn a copy into a transcode, and compares it only for
  copy streams, so encoded sessions still match their recipes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…o fix/copy-remux-vod-playlist-1466-part2

# Conflicts:
#	contracts/api/v2/fixtures/get_system_info_ok.json
#	internal/config/admin_settings.go
Sampling a few clusters can't prove the Cues list every video keyframe:
an uncued keyframe in an unsampled cluster would still let the plan cut
where FFmpeg doesn't. VerifyMatroska now walks every cluster's block
headers and requires a cue for each video keyframe and a keyframe for
each video cue; a cluster too large to read completely fails the check.

Because that reads every block header, Load runs it once per file in the
background: the first playback gets ErrUnverified (an ErrNoIndex) and
FFmpeg's playlist, and later playbacks use the verified index from the
cache. LoadVerified runs the check itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Track in-flight full checks apart from the evictable result cache and
  cap the queue; a file that finds it full is checked on a later
  playback, so cycling through many files can't pile up goroutines.
- Cache malformed files as having no index; only errors reading the
  file are retried, so a damaged MKV isn't rescanned on every playback.
- The v3 paths request a keyframe playlist only for copied video, so an
  older transcode node isn't rejected for an encoded job.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A planned copy stream could only restart from the beginning, since
FFmpeg's HLS muxer counts its cuts from where it starts (Silo-Server#1466). Now a
planned run cuts at every keyframe into one-group files, and the
session joins them into the planned segments: it maps each group's
first video presentation time to a keyframe of the plan, and once a
segment's keyframes all have groups it writes seg_NNNNN.m4s (keeping
moof/mdat pairs and the first styp, dropping sidx).

Group boundaries don't depend on where FFmpeg starts, so a missing
segment restarts FFmpeg at it, and assembled segments survive
restarts. Each run's timeline shift is measured and tfdt rewritten so
every run lines up with the first. Progress, startup readiness and the
pruner's retention come from the plan and the assembler. MPEG-TS copy
keeps FFmpeg's playlist.

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

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

Adds an opt-in keyframe-planned HLS playlist for copied video. The change adds Matroska keyframe indexing, segment planning and assembly, playback recovery and manifest handling, and setting propagation through local and remote transcode flows.

Changes: Keyframe-Planned Copy HLS

Layer / File(s) Summary
Setting and playback propagation
contracts/api/v2/*, internal/config/*, internal/api/handlers/playback_v3.go, internal/jellycompat/*, internal/playback/recipecard.go, internal/streamtoken/token.go, internal/transcodenode/server.go, web/src/pages/admin-settings/PlaybackSettings*
Adds the playback.copy_keyframe_playlist setting and carries its value through configuration, playback negotiation, recipes, stream tokens, API contracts, and remote transcode requests. Remote startup validates the node’s reported setting.
Keyframe index and segment planning
internal/playback/keyframes/*
Adds Matroska keyframe reading and cue verification, a cache for index results, and helpers to derive segment starts and durations. Tests cover cue layouts, index validation, caching, and FFmpeg comparisons.
Planned segment assembly and playback
internal/playback/copy_fmp4*, internal/playback/copy_group_assembler.go, internal/playback/copy_keyframe_plan*, internal/playback/transcode.go, internal/playback/segment_pruner.go
Plans copy segments from keyframes, assembles FFmpeg output groups into planned segments, and serves planned manifests with plan-based progress and recovery. Tests cover manifest behavior, segment timing, assembly, and restart continuity.

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

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant PlaybackRequest
  participant StartTranscode
  participant FFmpeg
  participant CopyGroupAssembler
  participant PlannedManifest
  PlaybackRequest->>StartTranscode: Start eligible copied-video session
  StartTranscode->>FFmpeg: Start keyframe group output
  FFmpeg->>CopyGroupAssembler: Write completed group files
  CopyGroupAssembler->>CopyGroupAssembler: Assemble planned segments
  PlannedManifest->>CopyGroupAssembler: Check assembled progress
  CopyGroupAssembler-->>PlannedManifest: Provide planned segment readiness
Loading

Suggested reviewers: pukabyte

Merge Risk: Low · up to 524c5

With complete playlists for copied video enabled, sessions can keep less back buffer than configured when segments have uneven lengths. A short backward seek may then restart FFmpeg. The feature is off by default, so the impact is bounded. This is a small fix to follow up.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 524c5

The optional playback mode adds meaningful restart and recovery behavior. Being disabled by default, retaining fallback playback, and checking remote compatibility limit exposure. No introduced authorization bypass was identified, but some recovery and lifecycle guarantees remain incompletely verified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Influence over selected library-media bytes reaches the new in-process Matroska reader when the mode is enabled. Verification and caching are process-wide, so resource effects can extend beyond one session. Controls bound individual Cues payloads to 64 MiB, metadata payloads to 16 MiB, cluster children to 20,000, queued checks to 16, and background full verification to one worker; these are not a proof of a total memory or execution-time bound.

Trust Boundaries and Controls

  • observed — The inspected remote start path retains input-path approval and serializes session replacement against reconstruction. Replacements use a separate temporary output directory while an existing session is live, limiting concurrent writers and protecting the live output during startup failure.

Resilience and Maintainability Implications

  • observed — Terminal Close cancels and reaps the process before removing its output directory. CloseProcess intentionally preserves shared output for the winning owner. The inspected remote stop path also deletes reconstruction authority, preventing a successful stop from leaving a durable recipe that can recreate the session.
Pre-merge checks: Passed 4

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.
Title check Passed The title "feat(playback): restart keyframe-planned copy streams mid-stream" matches the main change. The changeset adds mid-stream restart and group assembly for keyframe-planned copy-remux playback,…
Description check Passed The description describes the changeset in detail. It covers the opt-in playback.copy_keyframe_playlist setting, the copyGroupAssembler and keyframe-planned copy streams, mid-stream restarts, the fMP4…
Full details: Title check

Explanation

The title "feat(playback): restart keyframe-planned copy streams mid-stream" matches the main change. The changeset adds mid-stream restart and group assembly for keyframe-planned copy-remux playback, including the copyGroupAssembler, recovery logic, and planned-session restarts. The title is specific and concise, and it names the primary change.

Full details: Description check

Explanation

The description describes the changeset in detail. It covers the opt-in playback.copy_keyframe_playlist setting, the copyGroupAssembler and keyframe-planned copy streams, mid-stream restarts, the fMP4 timestamp priming fix, rebuild and migration behavior for plan records, and the ErrKeyframePlanChanged error. It also lists validation steps and risks. This matches the raw summary of the files changed, so the check passes.

Finishing Touches

🧪 Generate unit tests (beta)

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

Autopilot is currently an internal CodeRabbit preview.

@kody-ai

kody-ai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the `@kody start-review` command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Providing Context (Files & MCPs)

Add these hints in your PR description (or a comment) to unlock deeper checks:

  • Ticket / Acceptance Criteria: `Refs: ABC-123` (Linear/Jira/Asana/ClickUp/Trello) or a direct ticket link.
  • Bugfix Validation: a Sentry/Datadog/Bugsnag event link (or paste the stack trace/error message).
  • Endpoint Risk: mention the route (e.g., `POST /api/payments`) or controller/action name.
  • Attach a repo file as context: use an explicit marker like `@file:docs/guide.mdx#L10-L50` (replace with your real path).
  • API Contract Docs: include `@file:openapi.yaml` or `@file:swagger.json` when changing routes/schemas.
  • Definition of Done / Standards: include `@file:DOD.md` or `@file:CONTRIBUTING.md` if your repo has them.
  • Design System Source of Truth: include `@file:ui/index.ts` (replace with your DS entrypoint path).
  • Feature Flags: include the flag key/name and `@file:flags.ts` / `@file:config.json` (and optionally the PostHog flag name).
  • Edge/CDN Rules: link the Cloudflare rule/zone or describe the intended redirect/header behavior.
  • Attach an MCP tool output: use `@mcp<provider|tool>` (replace with an installed MCP provider + tool, e.g., `@mcp<sentry|events.search>`).
Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

rangoDJ and others added 2 commits October 1, 2026 15:25
The background check cleared its in-flight marker before storing its
result, and admission didn't look at stored results, so a Load in
between could queue the same file again. The result and the marker now
change under one lock, and a file with a stored result isn't queued.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread internal/playback/copy_keyframe_plan.go Resolved
Comment thread internal/playback/transcode.go Resolved
A load that missed the cache, then found the check already done when it
tried to queue one, still reported ErrUnverified. It now looks again
and returns the stored result.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread internal/playback/transcode.go Resolved
rangoDJ and others added 7 commits October 1, 2026 15:33
The plan took the probed duration as the stream's end on the
container's timeline, but the duration counts from the file's start and
container timestamps can start later than zero. For such a file the
last segment came out negative and the plan was dropped. The end is now
the first keyframe plus the duration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n zero

FFmpeg's output starts at zero (-start_at_zero) while the plan's
keyframe times are the container's, so for a source whose timestamps
start later the first group matched no keyframe and the run stopped
assembling. Group times are now measured from the first keyframe. The
end-to-end test also runs on a copy of its source shifted 7s later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…emux-vod-playlist-1466-part3

# Conflicts:
#	internal/playback/copy_keyframe_plan.go
- Record whether a session serves a keyframe playlist in its output
  directory. A session rebuilt from its recipe follows the record, so it
  can't switch playlists once the file's index has been verified.
- Reject segment numbers outside a planned playlist in recovery, and
  clamp restarts into it, so a bad request can't panic the executor.
- Report the current run's last group as the playlist's time, so the
  throttler can pause FFmpeg for a planned stream.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The plan ended the last segment at the catalog's runtime. That is the
container's duration, which can include an audio or subtitle track
running past the video. FFmpeg ends its last segment with the copied
video even when the selected audio is longer (checked with FFmpeg 8.0.1
and jellyfin-ffmpeg 8.1.3), so the plan advertised media that doesn't
exist.

VerifyMatroska already reads every block, so it now records when the
video's last frame ends: its timestamp plus the track's default frame
duration, or the gap to the frame before. The plan ends there, and
falls back to FFmpeg's playlist when that is unknown. The FFmpeg
comparison test now has an unselected audio track that runs 20s past
the video, and checks the last segment too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…emux-vod-playlist-1466-part3

# Conflicts:
#	internal/playback/copy_keyframe_plan.go
#	internal/playback/copy_keyframe_plan_test.go
@kody-ai

kody-ai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the `@kody start-review` command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Providing Context (Files & MCPs)

Add these hints in your PR description (or a comment) to unlock deeper checks:

  • Ticket / Acceptance Criteria: `Refs: ABC-123` (Linear/Jira/Asana/ClickUp/Trello) or a direct ticket link.
  • Bugfix Validation: a Sentry/Datadog/Bugsnag event link (or paste the stack trace/error message).
  • Endpoint Risk: mention the route (e.g., `POST /api/payments`) or controller/action name.
  • Attach a repo file as context: use an explicit marker like `@file:docs/guide.mdx#L10-L50` (replace with your real path).
  • API Contract Docs: include `@file:openapi.yaml` or `@file:swagger.json` when changing routes/schemas.
  • Definition of Done / Standards: include `@file:DOD.md` or `@file:CONTRIBUTING.md` if your repo has them.
  • Design System Source of Truth: include `@file:ui/index.ts` (replace with your DS entrypoint path).
  • Feature Flags: include the flag key/name and `@file:flags.ts` / `@file:config.json` (and optionally the PostHog flag name).
  • Edge/CDN Rules: link the Cloudflare rule/zone or describe the intended redirect/header behavior.
  • Attach an MCP tool output: use `@mcp<provider|tool>` (replace with an installed MCP provider + tool, e.g., `@mcp<sentry|events.search>`).
Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

-start_at_zero subtracts the input's start time, which is the earliest
stream's start, not the first keyframe's. When audio starts before the
video, the assembler measured groups from the wrong zero: it placed the
first group on a later keyframe and stopped assembling.

The plan now records the start time from ffprobe, which opens the file
with the same demuxer as FFmpeg. Without it, the session uses FFmpeg's
playlist. The time is also kept in the session's plan record. The
end-to-end test adds a source whose audio starts 2s before its video.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2d0ab3a5df

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Quick104 added a commit to Silo-Server/silo-translations that referenced this pull request Nov 13, 2026
#19)

* fix(catalog): say a far seek restarts the copied-video playlist's copy

Silo-Server/silo-server#1770 restarts the copy at a seek well past what has
been copied, instead of waiting for it to get there.

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

* chore(translations): copied-video playlist far-seek description in seven languages

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
rangoDJ and others added 3 commits November 12, 2026 21:33
With segment retention on, a restart keeps the assembled segments after
its start. The player can download them, and the pruner remove them,
before the new run reaches them. The run then rebuilt them behind the
pruner's cursor, which never visits those numbers again in the
generation, so they stayed on disk. A run now drops the groups of a
segment the pruner removed during it; a run restarted at that segment
still rebuilds it.

The pruner also left the removed file's DV8.1 conversion entry, keyed
by name and generation, so a planned segment written again under that
name in the same generation was served without conversion. Removing a
segment now drops its entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Main's Silo-Server#2515 plans copy playlists from the file's Cues without the full
check, and checks the plan against the segments FFmpeg writes to its own
playlist. Take its planning: the rebuild path loads the index with
keyframes.Load, and the plan carries the file version to reject.

Planned runs here write keyframe groups, not FFmpeg's segment playlist, so
the check moves to the group assembler. A group that starts where the plan
has no keyframe, or a planned keyframe FFmpeg skips, stops the run and
rejects the file version (keyframes.Reject), so later playbacks keep
FFmpeg's playlist. checkCopyPlan, checkCopyPlanOutput and the
never-written rule, which read FFmpeg's playlist, are dropped with their
tests.

Reconstructed stays: a rebuild whose probe of the source's start fails
still returns the error rather than serve FFmpeg's playlist to a player
holding the plan. A first start with a failed probe now records nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…places it

A session rebuilt without its plan record starts from the beginning, and a
request far ahead restarts it before that run has placed a group. The seek
run then set the session's timeline, a B-frame delay short of the original
from-start run's, so the rebuilt segments sat that far off the ones the
player had (80 ms on a -bf 2 source). The record kept the timeline only
while the output directory survived.

A planned restart now waits, up to 3 seconds, for the run it replaces to set
the timeline, or for its FFmpeg to exit. A copy from the start places its
first two groups within moments.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 94f212d141

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/playback/segment_pruner.go Resolved
The pruner removes a segment under s.mu and tells the assembler after
releasing it. A restart in between replaced the run, so the late notice
marked the new run's segment pruned, and that run dropped the groups of
the segment it was restarted for. Each run now records the generation it
was started for, and a prune notice marks only the run of the generation
its pass checked. The segment's assembled flag is cleared either way.

Calling forget under s.mu instead would make the session lock wait for
an assembler scan, which reads and writes segment files under its own
lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Quick104 and others added 2 commits November 14, 2026 18:34
…meline wait

main's restart now keeps the stopped throttler's threshold for a restart
hook that times out (Silo-Server#4127). The planned restart still lets the run it
replaces set the session's timeline before stopping it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… rebuilt segment counted

Two gaps on the keyframe-planned path:

- A native segment or playlist request for a planned session the server
  lost (no session, no runtime) rebuilt the session first and the runtime
  separately. When the plan record could no longer be served
  (ErrKeyframePlanChanged), the player got a 404 and the rebuilt session
  stayed registered, holding a stream slot. Planned cards now take the
  atomic rebuild tone-mapped cards already use: the session is removed
  again and the player gets 410 playback_session_ended.
- A prune notice that reports after a restart rebuilt the segment cleared
  its assembled flag, so the new run's head stopped short of it. forget now
  unmarks a segment only when its file is gone.

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

@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 fc62fd380, which is this branch with current main merged in. Two findings, both on the planned path. I'm fixing both in a commit on this branch, so there's no need to change anything yourself.

🤖 Claude Code (claude-opus-5-5), with a cross-provider review by gpt-6.1-sol

…d restart

On fast storage FFmpeg copies keyframe groups faster than the assembler
joins them. On the sandbox it had written groups through segment 640 while
segments were assembled through 335. A seek restart stops the run and
waits for its monitor, which first joined that whole backlog: the
restart's new FFmpeg started 10 s late and the segment took 22.7 s.

A run whose FFmpeg was cancelled (a restart or close) now stops assembling
between segments. It still reads groups until it is anchored, since its
first groups can set the session's timeline. A run that ends on its own
still finishes its last segments.

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

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

One more finding from the live check on a sandbox at 7a7654722, fixed in c428fd3d2.

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

Comment thread internal/playback/transcode.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c428fd3d22

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/playback/copy_keyframe_plan.go Resolved
…or a passed segment

- Two groups 40 ms apart fit keyframes 0 and 1 alike when keyframes are
  evenly spaced near a restart's seek. The run took the later one, so its
  third group matched no keyframe: the run stopped, the session failed, and
  a valid file was rejected. A run now holds its first groups while more
  than one keyframe within a B-frame-sized shift fits them, up to eight,
  and anchors once the groups tell them apart.
- A queued restart treated a missing segment at or behind the new run's
  head as about to be written. The pruner had removed it after the run
  passed it, so nothing wrote it and the request ended in a 404. It now
  restarts, as plannedSegmentRecoveryDecision already decides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Quick104
Quick104 merged commit 186c24a into Silo-Server:main Nov 14, 2026
27 checks passed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e3f7b26699

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/playback/transcode.go Resolved
@rangoDJ
rangoDJ deleted the fix/copy-remux-vod-playlist-1466-part3 branch November 15, 2026 00:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants