You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(playback): end the stream past a finished transcode's last segment - #4639
Related issue: N/A
Validation tasks: none (#1177 C3 runs through the transcode node's segment handler, but only a request past a finished transcode's last segment behaves differently)
Other clients: Apple N/A (server-only fix, checked on iOS and tvOS); Android N/A (server-only fix, checked on Android TV); Roku N/A (server-only fix, Roku plays the same HLS playlists)
Some MKV files have a container duration longer than their video: an ASS subtitle track that ends a few seconds after the film is enough. When such a file plays as an encoded transcode, the player reaches the end and freezes on the last frame. A few seconds later it fails with "All compatible playback recipes have already failed for this output route." This affects every client that plays the transcode: Android TV, iOS and tvOS all showed it. This change makes the stream end cleanly at the real end of the video, and the scanner now stores the video's length for files like this.
The synthetic VOD playlist of a transcode lists two-second segments up to media_files.duration. For the test file "H264 MoreFonts (2018)" that is 154 s, while the video ends at 150 s. FFmpeg finishes at 150 s and never writes the last two segments. A request for one of them found FFmpeg "not running", treated that like a crash, and seek-restarted FFmpeg at the end of the file. That FFmpeg wrote nothing, the request failed, and the player asked for the same segment again until it gave up.
Approach
Transcode end of stream. An encoded transcode learns where its media ends from FFmpeg runs that read their input to the end: a run that exits 0, was not stopped or replaced, and logged no Error during demuxing. A run whose own playlist lists segments with media sets the end to the last of them; a run that wrote no media (it started past the end) only bounds it. A video segment request past the learned end answers 200 with a segment that holds no media (recovery reason past_end_of_stream): the PAT and PMT of one of the session's MPEG-TS segments, or an fMP4 moof and empty mdat built from the init segment. It does not wait and does not restart FFmpeg; players treat such a segment as a gap and end at the video's end. A crash, a kill, a non-zero exit, or an exit 0 after a logged demux read error still restarts as before. Copy-video and keyframe-planned copies keep their own rules, and a learned end holds only for the audio track it was learned with. The check sits in the segment recovery core the native API, jellycompat and transcode nodes share (OpenSegmentWithRecovery), before a restart, again under the restart lock, and after one.
Stored duration correction. When a transcode answers past its learned end, the stored media_files.duration is lowered to where the run found the media ends (playback.StreamEndRecorder, FileRepository.ShortenDuration), so the next play's playlist ends with the video. The API server does this for its own transcodes; a transcode node reports the end in its session report (stream_end_seconds), and the core accepts it only for a transcode a playback session it holds runs on that node for that file. It never lengthens a duration, applies only while the stored duration is still the one the transcode was planned with and the file was last probed before the measuring run started reading it, and skips files with more than one audio track.
Scanner duration.audioVideoSpan already replaced the container duration with the video and audio span when a subtitle track stretched it, but only past a 5 s tolerance, so a 4 s stretch was kept. It now applies past 1 s, and only when another track that ends after the video and audio accounts for the container duration. Files whose longer container nothing explains keep their duration.
Existing rows keep their stored duration until a transcode of the file reaches the end or the file is probed again; there is no backfill.
Other fixes from the same report (an MKV with many large embedded fonts, with ASS subtitles, on Android TV): #4640, #4641, #4642 and Silo-Server/silo-android#1010. #4642 also edits internal/scanner/probe.go, in different functions.
Validation
go build ./..., go vet on the touched packages, gofmt, go mod tidy -diff: clean.
make lint-changed, make lint-router-recovery: 0 issues.
go test for internal/playback/..., internal/scanner/..., internal/transcodenode/..., internal/jellycompat/..., internal/api/handlers: pass. The handlers package needs umask 022 locally; its upload tests fail under umask 002 on main too.
make verify-local-paths, verify-size-ratchet, verify-bidi, verify-case-collisions: pass.
New tests: a fake FFmpeg that exits cleanly, exits 1, or exits 0 after a demux error, checked for the recovery decision and the empty 200, including a request that arrives while another request's restart is in flight. A duration table covers a 4 s subtitle stretch, a stretch nothing explains, and a subtitle that ends before the video.
Not run: the full make test-go and the web gate (no web change).
Review fix (0b1b5d2, d82f571): when video and audio fall short of the container by less than the old tolerance, the track that accounts for the container must end within 5 s of it, before or after, so understated video and audio tags on a long file can't shorten it. Two rows in the duration table fail without it.
Main merged (4234b69): main's refactor(playback): share HLS segment wait and recovery core across surfaces #4890 moved the three handlers' wait and restart into OpenSegmentWithRecovery, so the end-of-stream check moved there. Review fix c8f3a01 adds the check after the post-restart wait; TestSegmentRestartPastEndOfStreamEndsTheStream fails without it. go build ./..., make lint-changed and make lint-router-recovery are clean, and the playback, scanner, transcode node, jellycompat and handlers tests pass on c8f3a01.
Second review (675c925, merged with main at 8c40826): the zero-byte answer froze hls.js, so the answer became a segment with no media, plus the stored-duration correction. Live on a sandbox with a transcode node, a file whose video ends at 20 s with its stored duration set to 24 s or 30 s ended cleanly on the web app (hls.js 1.6.15), Android TV and an iPhone simulator. The stored duration then read 20 s, and the next play requested nothing past the video. New tests, each failing without its rule: copy-video learns no end, an end holds per audio track, empty runs (including FFmpeg's EXTINF:0 playlist) never raise or fabricate an end, the restart-lock re-check, a node's reported end needs a matching session, the past-end TS bytes, the recorder, and a two-subtitle scanner row. The touched packages pass, and make lint-changed and make lint-router-recovery report 0 issues.
Bot review follow-ups (fda1530): the end is the run's seek plus what it wrote (an audio switch restarts inside a segment); a run's options are captured when it starts; the duration is lowered only while it is still the one the transcode was planned with (stream_planned_seconds in a node's report); a written end is remembered for ten minutes; node reports reuse the resolved node identity. New subtest for an unaligned restart fails on the old arithmetic.
Replacement fix (4c3c12f, main merged at 399fd2e): a file replaced at the same path with the same stored duration could still take an end measured on the old file. A learned end now carries when its run started (for a node's transcode, when the core's playback session started), and ShortenDuration requires probe_updated_at before it. TestShortenDurationOnlyForTheFileTheRunReadDB, added to scripts/ci/db-contracts.txt, fails without the check. The touched packages pass on d424365 against a freshly migrated Postgres, and make lint-changed reports 0 issues.
Main merged (ce35ed2): main's AV1 hardware-decode stop (fix(playback): decode on the CPU when VA-API or QSV can't decode the source #4478) and this branch both changed ffmpegStderrWriter; the merge keeps the stop and the demux-error flag. On the merged head the playback, scanner, node control, node sessions, transcode node and jellycompat tests pass against a freshly migrated Postgres (TestShortenDurationOnlyForTheFileTheRunReadDB ran, not skipped), and make lint-changed and make lint-router-recovery report 0 issues.
Third review (e0c4904): an end that rounds up to the planned duration no longer runs a no-op UPDATE for every finished node transcode, and a PAT packet whose lengths overrun it no longer panics the past-end TS answer. The new rows in TestStreamEndRecorder and TestPastEndTSProgramTables fail without the fixes. The protocol doc now says a node reports the end once it learns it, and that only the API server holding the playback session stores it.
Played "H264 MoreFonts (2018)" (transcode with ASS burn-in) to the end, and again from 2:28, on Android TV, iOS and tvOS against a local server built from this branch and from main.
Surface and build: the web app (headless Chromium), an Android TV emulator and an iPhone simulator with the current Silo clients, against a sandbox built from this branch (tree of 675c925) with a transcode node. The author's earlier captures (Android TV, iOS and tvOS against main and the first version of this branch) and the review captures of the zero-byte answer on the web are on earlier pages of the same evidence site.
Risks
If FFmpeg ever exits 0 early without logging a demux error, the session would end the stream at the last segment it wrote instead of restarting, and the stored duration would be lowered to that point until the file is probed again. The test suite pins the one early-exit case known to exit 0 (a failed read) to the restart path. No migration and no client API shape change: the segment endpoint answers 200 with a segment that holds no media where it used to fail. The node-to-core session report gains one optional field (stream_end_seconds), which an older core ignores.
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
Tool(s): Claude Code, Codex CLI, GitHub CLI
Council: Sol, Opus, Gemini, 3 rounds, last reviewed ce35ed2
Model(s): claude-opus-5-5 (implementation and review), gpt-6.2-sol and gpt-6.2-astra via Codex CLI (review), gemini-4-neon (review), Claude Fable 5.2 (review)
Involvement: Fully AI-generated, human verified
Adversarial review: four independent reviews of the full branch diff (correctness, standards, spec), reconciled, then a focused review of the fixes. Fixed: the scanner accepted a track that ends before the video as the explanation for the longer container; a past-end request waited out another request's restart; the three handler copies of the end-of-stream check became one helper; a redundant test row went. Dismissed: a narrow race where FFmpeg finishes between the end-of-stream check and a restart (the restarted FFmpeg has nothing to read, exits at once, and the next request should then end the stream).
Note
Serve empty segments past a finished transcode's learned stream end
Encoded transcodes can produce synthetic playlists that extend past the actual media duration, so segment requests near the end previously triggered restarts and errors. This PR has the FFmpeg monitor learn the media's real end from a cleanly finished run and serve valid empty MPEG-TS or fMP4 segments for requests beyond it.
monitorFFmpeg learns the last nonempty segment and end time from a run's manifest; failed, demux-error, cancelled, copy-plan, and multi-audio runs are excluded. Empty runs starting after segment 0 set a bound just before their start (transcode.go)
OpenSegmentWithRecovery and RestartSegmentSince return a new ErrPastEndOfStream (wrapping ErrSegmentNotFound) instead of restarting when the segment is past the learned end (segment_recovery.go)
ServePastEndOfStream serves HTTP 200 with an empty segment: TS reuses PAT/PMT packets from a nearby segment (or generic tables), fMP4 builds a moof with zero-sample truns per track plus an empty mdat (past_end_segment.go)
A new StreamEndRecorder shortens the stored file duration asynchronously via FileRepository.ShortenDuration, which only lowers duration when the row still matches the planned duration and probe revision and has at most one audio track; transcode nodes report ends and the API server validates them against the session and reporting node (stream_end_recorder.go, file_repo.go, server.go)
Duration probing fixes: audio/video spans round up to whole seconds and require a 1-second shortfall with an accounting non-A/V track before replacing the container duration (probe.go)
Behavioral Change: segment requests past the learned end now return HTTP 200 with an empty segment instead of an error/restart; stored file durations can be lowered by the recorder; SessionInfo reports gain stream_end_seconds and stream_planned_seconds fields
A transcode's synthetic VOD playlist lists two-second segments up to the
file's stored duration. When the container outlasts its audio and video
(an ASS track that ends after the film, trailing attachments, a bad
duration tag), the last segments are never written. A request for one
after FFmpeg finished found it "not running" and seek-restarted FFmpeg
past the end; that run wrote nothing, the request failed with 404 or
500, and the player asked again until it gave up buffering.
When FFmpeg exits 0 without logging a demux error, it read its input to
the end, so the session records its last segment as the media's last.
Video segment requests past it now answer 200 with an empty body,
without waiting or restarting, and the player steps to the end of the
playlist. FFmpeg also exits 0 after a read fails mid-file, but it logs
"Error during demuxing" first, so a cut-off source, a crash, or a kill
still restarts as before. Keyframe-planned copies keep their own rules.
The native API, transcode nodes and jellycompat share the change.
… stretches it by seconds
A container whose duration a subtitle track stretched kept that
duration whenever video and audio fell short of it by 5 seconds or
less, the tolerance meant for matching a subtitle's length to the
container. A 150-second film with a 154.39-second ASS track was stored
as 154 seconds, so transcode playlists listed segments past the end of
the video and seek previews and runtimes ran long.
Video and audio now replace the container duration once they fall more
than a second short, when a track that ends after them accounts for
it. Files whose container nothing else explains keep it.
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.
The change adds clean end detection for encoded transcodes, empty-segment responses for requests past a learned end, and reporting that can lower eligible stored media durations. It also changes scanner duration selection when non-audio/video tracks account for a container duration beyond the audio/video span.
Changes: Transcode end-of-stream and duration reporting
A qualifying FFmpeg exit records the last nonempty segment for eligible encoded sessions. Requests beyond a learned end do not restart FFmpeg and can receive an empty TS or fMP4 segment with HTTP 200. Tests cover clean and unsuccessful exits, empty runs, and response contents.
Playback paths pass past-end errors to the segment responder. Transcode nodes report learned ends. Node control validates the reporting session, file, transport, and node before recording an end. The recorder rounds the end up to seconds, and the repository lowers stored duration only when its conditions are met.
Playback handling and protocol documentation docs/architecture/playback-protocol-v3.md, docs/playback-api.md, docs/architecture/transcode-nodes.md
The documentation describes when a transcode end is learned, how requests past the end are answered, and how eligible session reports can lower stored duration.
Scanner duration selection
Layer / File(s)
Summary
Account for non-A/V track ends internal/scanner/probe.go, internal/scanner/probe_duration_test.go
The duration calculation applies a one-second shortfall threshold, checks qualifying non-A/V track ends near the container duration, and rounds selected audio/video spans up. Tests cover subtitle and partial-second cases.
sequenceDiagram
participant TranscodeSession
participant TranscodeNode
participant NodeControl
participant StreamEndRecorder
participant FileRepository
TranscodeSession->>TranscodeNode: Provide learned stream end
TranscodeNode->>NodeControl: Report session and stream_end_seconds
NodeControl->>NodeControl: Validate transport, file, and node ownership
NodeControl->>StreamEndRecorder: Note media file end
StreamEndRecorder->>FileRepository: Shorten stored duration
Loading
Possibly related issues
Silo-Server/silo-server#3597 — The issue describes FFmpeg exiting without output when a replan starts at the file end. This change handles past-end segment requests after qualifying FFmpeg exits, but does not change route-failure accounting.
Silo-Server/silo-server#5127 — The issue concerns a start inside the file tail that fails after learned-end handling. It involves the same learned-end and empty-segment behavior, while describing remaining behavior.
Possibly related PRs
Silo-Server/silo-server#1770 — This PR introduces keyframe-planned copy sessions, whose playlist rules are explicitly distinguished from the encoded-transcode end handling here.
Playback past the end of a transcoded stream now returns valid empty segments instead of freezing the player. Two edge cases should be fixed before merge. After an audio-track switch, a stream end learned by the old run could be applied to the new track. A late stream-end report for a replaced file could shorten the replacement's stored duration.
Security architecture risk: Moderate · up to 8c408
Access checks constrain the new duration updates, but corrections are not tied to the file version that produced them. A delayed correction from older playback can shorten a replacement file’s shared duration, affecting later viewers and surviving a code rollback.
Retained concerns
Medium · reliability · inferred: Duration corrections are authorized by file identity but not fenced to the source revision that produced them. Note launches a detached database update, and ShortenDuration checks only the row ID, existing duration, and audio-track count. Meanwhile, a same-path scanner upsert preserves the row identity while replacing its source metadata and duration. If that refresh occurs before an older correction executes, the correction can shorten the replacement file’s duration for subsequent viewers. The atomic shorten-only predicate and transport ownership checks do not prevent this cross-revision write. Re-probing can restore the value, but reverting the code does not reverse an already persisted correction.
Security review details
Security Blast Radius
inferred — A transcode node’s new durable-write authority is constrained to eligible media files named by matching core-held transports on that node. The effect is file-global rather than viewer-local: lowering the shared duration changes the duration used by later transcodes. The inspected authorization path does not allow a node to redirect a matching transport’s correction to an unrelated file.
Trust Boundaries and Controls
observed — The report route requires node-key authentication and per-node rate limiting. Node identity comes from authenticated request context, not report fields. Before a duration correction, runsFile checks the reported file against the core-held transport and compares its assigned node URL with the authenticated node’s registered URL. Report boot/sequence fencing rejects older accepted reports.
Resilience and Maintainability Implications
observed — Corrections use a ten-second detached write context and per-process deduplication; write errors clear the deduplication entry. Remote reports repeat learned ends with increasing sequence numbers, allowing a later accepted report to retry. Atomic shorten-only SQL makes duplicate or reordered corrections safe for a single unchanged source, but does not establish cross-revision safety.
Hardening Proposals
proposed — Carry the observed source revision through local and remote correction paths and compare it atomically in the duration UPDATE. This would prevent a queued correction from applying after a same-row file replacement. Retaining correction provenance would also make restoration distinguishable from fresh probe metadata.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: when a finished encoded transcode has no FFmpeg output past its last segment, the stream now ends there instead of failing or restarting FFmpeg. The changeset matches …
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
The description states the problem (MKV container duration longer than video causes playback freeze at end of encoded transcodes), the approach (learning stream end from FFmpeg runs, serving past-end …
Full details: Title check
Explanation
The title names the main change: when a finished encoded transcode has no FFmpeg output past its last segment, the stream now ends there instead of failing or restarting FFmpeg. The changeset matches this: stream-end recording in transcode.go, ErrPastEndOfStream and ServePastEndOfStream, and the segment recovery changes. The scanner duration tightening is a secondary change that the title does not mention, which is acceptable.
Full details: Description check
Explanation
The description states the problem (MKV container duration longer than video causes playback freeze at end of encoded transcodes), the approach (learning stream end from FFmpeg runs, serving past-end empty segments, scanner duration selection changes), and validation steps. It is closely related to the changeset and is detailed, so it is not vague or off-topic.
Finishing Touches
Generate unit tests (beta)
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
… duration
When the video and audio span replaces a longer container duration, it was
truncated to whole seconds like every other duration. The container used to
cover that partial last second; the span does not, so a file whose video ends
at 150.9 s was stored as 150 and the transcode playlist left out the segment
holding its last 0.9 s. The span is now rounded up.
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 settingsReview 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
The span of video and audio now replaces the container duration once it
falls more than a second short, but the track that accounts for the
container could still end anywhere within the old tolerance, which is
72 seconds on a two-hour file. Video and audio tags that understate a
long file by seconds would then shorten it whenever a subtitle ended a
little after them, dropping the real end from runtime, progress and the
transcode playlist.
A shortfall inside that tolerance now needs a track that ends within 5
seconds of the container. Longer stretches keep the earlier rule.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
Review of bdd3c7f. The diagnosis holds and both halves aim at the right problem: on the base, a request past a cleanly finished transcode decides transcode_not_running and restarts FFmpeg, and the new decision stops that. The scanner test fails on the base for the reported reason.
The main open point is the web app. I played a synthetic file with a stretched container through the web player (hls.js 1.6.15) on a sandbox built from the base and from this head. The empty 200 doesn't end playback there; details are on the ServeIfPastEndOfStream line. That one needs a maintainer decision, so I haven't changed it. I'm fixing the scanner tolerance finding in a commit on this branch, so there's no need to change it yourself. The other notes are low severity.
The reason will be displayed to describe this comment to others. Learn more.
Low: rounding the span up can list one segment FFmpeg never writes.
Trigger: audio ends a few milliseconds after the video and crosses a segment boundary. On the sandbox, a file with video ending at 20.000 s and audio at 20.023 s, freshly scanned, stored 21 s. The playlist lists segment 10 (20 to 21 s), FFmpeg starts segments on video keyframes, so segment 10 is never written and is answered empty.
Impact: newly scanned rows can still reach the empty-segment path, which on the web means the request burst described on ServeIfPastEndOfStream. Rounding the video track's own end up (rather than the joint span) would keep the 150.9 s case from the earlier thread without listing an audio-only tail. This depends on how the first finding is settled, so I'm not changing it.
The reason will be displayed to describe this comment to others. Learn more.
Leaving the rounding as is. The one extra segment it can list is now answered with a segment that holds no media, which hls.js, ExoPlayer and AVPlayer all step over at the end (checked live), and a transcode that reaches the end lowers the stored duration to what it found.
Reviewed bdd3c7f, then pushed fixes over six passes. The branch is now at e0c4904. The last pass merged current main, which moved under this branch, and fixed three low-severity items from a third three-model review.
Fit: 8/10 · Readiness: 8/10 — conditional (assuming CI is green)
Fit. A server-side fix for a playback failure every client hit, with no new setting. The scanner change stores the film's real length instead of one a subtitle track stretched. Playback can also correct a stored duration: when a transcode reads a file to its real end and the stored duration runs longer, the server lowers it, so the next play's playlist ends with the video. That crosses from playback into catalog data, so the write is narrow. It only ever shortens a duration, skips files with more than one audio track, and applies only while the row still holds the duration the transcode was planned with and was probed before the run started. It accepts a transcode node's report only for a transcode the receiving server runs on that node for that file. The node report gains two optional fields in the v2 contract (stream_end_seconds, stream_planned_seconds). An older core ignores them, and no client reads them.
Readiness. A request past the end now gets a segment that holds no media, where it used to restart FFmpeg in a loop. On a sandbox with a transcode node, with a file whose video ends at 20 s and a stored duration of 24 s or 30 s:
Web app (hls.js 1.6.15): ended at 20.05 s with two segments past the video, and at 20.07 s with four. With four, hls.js raised one fatal fragParsingError, and the player's media recovery handled it.
Android TV (ExoPlayer): "End of playback" with two and with five such segments.
iPhone (AVPlayer, simulator): "End of playback" with two, from a seek and from the start.
After each play the stored duration was 20 s, and the next play requested nothing past the video.
Before, the same web play froze on the last frame and sent about 60 requests a second until 429. Those captures are from the tree of 675c925. Later commits change when the stored duration is corrected and how two edge cases behave, and tests cover those changes. Every new rule has a test that fails without it. Three things hold the score at 8. fMP4 wasn't exercised live. A long phantom tail on the web is untested (below). A play that starts inside the tail still fails (#5127).
Evidence: https://evidence.siloserver.org/r/silo-server/pr-4639-r3/
Addressed
The answer past the end is a segment that holds no media, not zero bytes.
The stored duration is lowered to where a transcode found the media ends: by the API server for its own transcodes, and by the core from a transcode node's session report.
Only encoded transcodes with a synthetic playlist learn an end, and an end holds only for the audio track it was learned with.
The end is read from the run's own playlist. It is the run's seek plus what it wrote, and the run's options are captured when it starts. A run that wrote no media only lowers a known end.
A request that waited on the restart lock checks the end again before restarting, and again after the post-restart wait.
The duration write is bound to the file the run read: the planned duration must still be stored, and the row must have been probed before the run started.
The scanner check needs a track that ends with the container, and compares the absolute distance.
An end that rounds up to the planned duration no longer runs an UPDATE that matches nothing. Before, that happened for nearly every node transcode that finished.
A PAT packet whose lengths overrun it no longer panics the past-end TS answer.
The protocol doc says a node reports the end once it learns it, and that only the API server holding the playback session stores it.
A long phantom tail on the first web play. hls.js steps over two segments with no media and then raises a parsing error. The web player recovers from two media errors per load and gives up on the third. Four segments past the video cost one recovery live. A longer overrun is untested and could use up the recoveries, ending the first web play with an error at the very end. Later plays are fixed by the duration correction. Subtitle-stretched files rarely get there: the old scanner already corrected stretches over 5 s. It takes a container duration that nothing explains. Android TV and the iPhone aren't affected this way. Accepting that is the call to make; the alternative is a web-side follow-up that stops at the learned end.
The scanner's 1 s threshold has a trade-off. If a file's video and audio tags understate its real length by up to 5 s, and a subtitle ends between them and the container, the scanner now stores the shorter tag length. The end of the film then plays up to 5 s short. That pattern is the same one this PR fixes, and probe metadata alone can't tell the two apart. I recommend accepting it.
Duration correction or a re-probe. One reviewer suggested asking the scanner to re-probe the file on a past-end answer instead of writing the measured end. That would drop the node-report fields and the binding checks. A re-probe can't fix a container whose tags nothing explains, though, which is the case the long-tail item above needs. I recommend keeping the correction.
Checked against the v1.0 validation board. The only passed cases this code reaches are #1177 C1–C3 (transcode nodes: zero-config, caps, and removing a node during playback). C3's failover rebuilds the session on another node, where the end starts unknown and a request past the produced output restarts as before. The report gains two optional fields. No passed case changes. The other tasks the code touches (#197 Movies, #1250 Series, #1246 Jellyfin compatibility, hardware transcoding) haven't been run yet.
Other checks
User manual: unaffected. No siloserver.org page describes stored durations or segment handling.
Apple, Android, Roku: no client change. Roku and fMP4 on AVPlayer weren't checked.
Declined from the third review, with reasons:
A partial read that FFmpeg takes for the end of the file. The node's source relay aborts a body it can't finish, so FFmpeg logs the demux error this branch checks for. A local read error logs it too.
A seek that lands after its target. Encoded transcodes keep accurate_seek, and FFmpeg seeks no later than the target.
A subtitle whose length tag includes its start offset. This only keeps the longer duration, as main does.
A ten-minute delay in repeating a write that matched no row. Only a background correction waits.
Several API servers: a node report that reaches a server that doesn't hold the playback session corrects nothing. The doc now says so. The session still ends its stream cleanly, and a later report or transcode corrects the duration.
Tests on e0c4904: internal/playback/..., scanner, nodecontrol, nodesessions, transcodenode and jellycompat pass against a freshly migrated Postgres, with the database test run rather than skipped. make lint-changed and make lint-router-recovery report 0 issues.
Round 3 reviewed the merged head. Opus and Gemini found no correctness problem in the end-of-stream path and confirmed the merge resolution. Gemini found the no-op write and the PAT panic, both fixed. Sol raised the long web tail and the scanner trade-off, which are left for the maintainers above, plus the partial read, which doesn't hold. All three noted the several-API-servers case, which is documented now.
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: 5f4922b3-23f7-4cbc-9fa8-69128e572a5b
Commits
Reviewing files that changed from the base of the PR and between bdd3c7f and 0b1b5d2.
Files selected for processing: 2
internal/scanner/probe.go
internal/scanner/probe_duration_test.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.
Main's Silo-Server#4890 moved the three segment handlers' wait and restart logic into
playback.OpenSegmentWithRecovery. The end-of-stream check now sits in that
core, after the wait and before any restart: it returns ErrPastEndOfStream
(which wraps ErrSegmentNotFound), and the API, jellycompat and transcode
node handlers answer it with ServePastEndOfStream's empty 200.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…from either side
0b1b5d2 required the track that accounts for a short stretch to end
within 5 s of the container, but only checked the early side. A subtitle
ending 40 s after a 7200 s container still passed, and the scanner stored
the 7160 s video and audio span. Compare the absolute distance instead.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A seek into the playlist's phantom tail before any FFmpeg of the session
had reached the end restarted FFmpeg there. It exited 0 at once and the
session learned the end, but the request still answered not found, which
the player retries. After the post-restart wait, a segment past the learned
end now answers ErrPastEndOfStream like the check before the restart.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 6
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: bd97f3c5-cc02-4de4-b7dd-01600a44cdd3
Commits
Reviewing files that changed from the base of the PR and between 0b1b5d2 and c8f3a01.
Files selected for processing: 11
docs/architecture/playback-protocol-v3.md
docs/playback-api.md
internal/api/handlers/playback.go
internal/jellycompat/streams.go
internal/playback/errors.go
internal/playback/segment_recovery.go
internal/playback/transcode.go
internal/playback/transcode_manifest_test.go
internal/scanner/probe.go
internal/scanner/probe_duration_test.go
internal/transcodenode/server.go
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Data Integrity & Integration · Quick win
Document the clean-exit condition.
Reading the source to its end is not sufficient. For example, FFmpeg can exit nonzero after reading the source, and the stated contract retains restart behavior in that case. Document the successful exit and other conditions for the past-end response.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 675c925. Both docs now state when a request past the end gets this answer: an FFmpeg run of the session exited 0, was not stopped or replaced, and logged no demux error, or a run started past the end and wrote no media. The protocol doc also lists what doesn't count (a crash, a kill, a non-zero exit, an exit after a demux error) and that only encoded transcodes with a synthetic playlist learn the end.
@Quick104 Thanks. The protocol document states the clean-exit condition, but docs/playback-api.md Line 376 presents an empty run as an alternative to it.
In internal/playback/transcode.go Line 731, the clean-exit check also applies to empty runs. Please make that condition apply to both cases in the API document. I’m not marking the finding as addressed yet.
If you found this review helpful, would you consider giving us a shout-out on X?
The reason will be displayed to describe this comment to others. Learn more.
Major · Functional Correctness · Heavy lift
The learned end of stream is not reset when the audio track changes.
SetAudioTrackIndex changes the mapped audio track on the existing session, and the restart reuses that session. streamEnded and streamEndSegment are never cleared, so the end learned from the previous track still applies. If the new track runs longer, requests past the old endpoint can receive the empty past-end response, and the new track's final segments are not served.
When the audio track changes, the learned end must be discarded before the new generation can answer segment requests. The discard must also stop a generation for the previous track from setting the end after the change.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 675c925, without a reset. The learned end records the audio track it was learned with, and pastEndOfStream applies it only while that track is selected. A run for the previous track that finishes after the switch records an end for its own track, which doesn't apply to the new one. A new row in TestSegmentRecoveryAfterFFmpegExits switches the track after the end is learned and expects a restart; it fails without the check.
#!/bin/bashset -u
echo'=== repository instructions ==='
cat AGENTS.md
echo'=== audio-switch caller outline ==='
ast-grep outline internal/jellycompat/streams.go --items all --match 'audio|Audio'echo'=== audio-switch caller ==='
cat -n internal/jellycompat/streams.go | sed -n '3830,3920p'echo'=== monitor ==='
cat -n internal/playback/transcode.go | sed -n '684,742p'echo'=== end learning ==='
cat -n internal/playback/transcode.go | sed -n '3450,3535p'echo'=== restart cancellation ==='
cat -n internal/playback/transcode.go | sed -n '4186,4255p'echo'=== regression test synchronization ==='
ast-grep outline internal/playback/transcode_manifest_test.go --items all --match 'runFakeFFmpeg|fakeFFmpegSession|TestSegmentRecoveryAfterFFmpegExits'
cat -n internal/playback/transcode_manifest_test.go | sed -n '900,1005p'
Length of output: 47209
@Quick104 The track check handles a switch after the end is learned, but a race remains.
SetAudioTrackIndex changes s.opts before the old FFmpeg process is stopped (internal/jellycompat/streams.go, Line 3880). If that process exits cleanly before cancellation, learnStreamEndLocked reads the new track index from s.opts (internal/playback/transcode.go, Lines 3463 and 3500). It can therefore record the old track’s end as the new track’s end.
Please capture the track used by each FFmpeg generation and use it when learning the end. A synchronized test should switch tracks before the old generation exits. The current test waits for exit before switching.
I did not run the tests. I am not marking this finding as addressed.
Learnings added
Learnt from: Quick104
Repo: Silo-Server/silo-server PR: 4639
File: internal/playback/transcode.go:0-0
Timestamp: 2026-11-22T18:41:24.994Z
Learning: Within repository "Silo-Server/silo-server", only for files matching one of ["internal/playback/transcode.go"]: In internal/playback/transcode.go, SetAudioTrackIndex changes the session's s.opts.AudioTrackIndex before Restart starts the replacement FFmpeg process; it does not change the track used by the running process. Code attributing output to an FFmpeg generation must use that generation's actual audio track rather than assuming the current session option identifies it.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
…ding later
When video and audio fell short of the container by less than the tolerance,
the scanner took the latest end among the tracks that account for the
container and required it within 5 s of the container. A subtitle ending
with a 3600 s container beside another ending at 3620 s then failed the check
and the stretched container duration stood. The check now uses the latest end
among the tracks within 5 s of the container.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The past-end answer was a zero-byte 200. hls.js fails its format probe on
that and requests the segment again without end, so the web app froze on
the last frame. The answer is now a segment that holds no media: the PAT and
PMT of one of the session's MPEG-TS segments (a generic H.264 pair when none
can be read), or an fMP4 moof and empty mdat built from the init segment's
tracks. hls.js skips such segments as gaps.
The session learns the end more carefully:
- only an encoded transcode with a synthetic playlist learns it; copy-video
serves FFmpeg's playlist, which a seek re-cuts at other keyframes;
- the end is read from the run's own playlist; a run that wrote no media
(no playlist, or one listing a single empty EXTINF:0 segment, which is
what FFmpeg writes when it starts past the end) only lowers a known end,
one from segment 0 shows nothing, and output the session cannot read
teaches nothing;
- it holds for the audio track it was learned with;
- a request that waited on the restart lock checks it again.
So that later plays list the right segments, the stored media_files.duration
is lowered to where a run found the media ends (StreamEndRecorder,
FileRepository.ShortenDuration): by the API server that answers past the end
of a local transcode, and by the core from a transcode node's session report
(stream_end_seconds) when a playback session it holds runs that transport on
that node for that file. It never lengthens a duration and skips files with
more than one audio track.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
Stream-end checks repeat node identity reads for every reported session
An in-memory identity miss makes s.identity read the database for every session, even though all sessions share the same authenticated node. Pass the identity or canonical node URL already resolved by HandleReport to runsFile.
File internal/nodecontrol/server.go, line 61:
Stream-end checks repeat node identity reads for every reported session
Reuse the node identity already resolved by `HandleReport` instead of looking it up for every reported session. When the in-memory identity source misses, this performs a database read per session, even though every session in the report has the same authenticated node. Pass the already resolved identity or canonical node URL into `runsFile`.
Kody rule violation: [Batch scoped Go lookups and bound dependency fan\-out](https://kodus.siloserver.org/settings/code-review/1247142351/kody-rules/d2a64d9a-568c-46c2-9fa4-ad93c54ef90e?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)
The reason will be displayed to describe this comment to others. Learn more.
Fixed in fda1530. HandleReport already resolves the reporting node's identity once, so runsFile now takes that node URL instead of looking the identity up per session.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update. Passing the URL already resolved by HandleReport to runsFile addresses the repeated identity lookups described in the suggestion. I haven’t independently verified the commit.
The reason will be displayed to describe this comment to others. Learn more.
A missing fMP4 init segment restores the infinite retry loop
A seek past the end can leave hlsInitSegmentName missing, causing a zero-byte 200 response that hls.js retries indefinitely. Return a valid init-based empty fragment or a response that does not masquerade as a valid fragment.
Prompt for LLM
File internal/playback/past_end_segment.go, lines 193-195:
A missing fMP4 init segment restores the infinite retry loop
A seek directly past the end can finish without writing an init segment, so this returns a zero-byte 200 response and hls.js retries the segment indefinitely instead of advancing. Preserve or generate a valid init-based empty fragment before returning success, or use a response that does not masquerade as a valid fragment.
The reason will be displayed to describe this comment to others. Learn more.
Not changing this here. For fMP4 the init segment is written by the session's first run and kept across restarts (cleanStaleSegments preserves it), so it is missing only when the session's very first run starts past the end. That is the case tracked in #5127: a play that starts inside the tail has no earlier media, and players fail it either way (ExoPlayer can't prepare from a first segment with no samples). The fix for that start belongs there, not in a different empty answer.
The reason will be displayed to describe this comment to others. Learn more.
Agreed. If the init segment is preserved across restarts, the missing-init case described in the suggestion is limited to playback starting in the tail, which is already tracked in #5127. A different empty response would not resolve the underlying first-segment playback failure.
The reason will be displayed to describe this comment to others. Learn more.
A file-wide duration conflates different selected output timelines
Selected output tracks can end at different times, so r.store.ShortenDuration can truncate a later output or leave an unsupported tail. Derive each playlist endpoint from its selected tracks, falling back to FFmpeg's playlist when the endpoint is unknown.
File internal/playback/stream_end_recorder.go, line 67:
A file-wide duration conflates different selected output timelines
Do not use one transcode's observed endpoint to shorten a file-wide duration that later playlists use for every track selection. Different selected output tracks can end at different times, so this can truncate a later output or leave an unsupported tail. Derive each playlist endpoint from its selected tracks, and fall back to FFmpeg's playlist when that endpoint is unknown.
**Also found in:**
- `internal/playback/stream_end_recorder.go:52-52`
- `internal/playback/transcode.go:3535-3535`
Kody rule violation: [Build VOD durations from the selected output timeline](https://kodus.siloserver.org/settings/code-review/1247142351/kody-rules/2151b8a9-a358-4f5a-9e18-fcad07b2c489?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)
The reason will be displayed to describe this comment to others. Learn more.
Covered by the existing guard: ShortenDuration changes only files with at most one audio track, so every transcode of such a file maps the same video and audio, and their outputs end at the same time. Burned-in subtitles don't change the length. A file with several audio tracks keeps its stored duration and gets only the per-session end answer.
The reason will be displayed to describe this comment to others. Learn more.
The single-audio-track guard addresses the specific risk of shortening the file based on one audio selection when another audio track ends later. For files with multiple audio tracks, the described behavior leaves the stored duration unchanged and uses the learned end only within the session.
I would qualify the broader claim, though: having at most one audio track alone does not prove every output timeline ends at the same point. That also depends on video-track selection, whether audio can be omitted, and whether different output modes produce equivalent endpoints.
The PR file lookup did not return stream_end_recorder.go, so I can’t independently verify those assumptions from the retrieved code. If they hold for the supported playback paths, the original suggestion’s multi-audio example is covered; otherwise, the file-wide duration concern may still apply.
The reason will be displayed to describe this comment to others. Learn more.
Cached stream ends suppress corrections after a file is re-probed
Re-probing can restore a longer duration while r.noted retains the old end, preventing subsequent transcodes from correcting the phantom playlist tail. Invalidate the entry on re-probe or include the probe revision in deduplication.
Prompt for LLM
File internal/playback/stream_end_recorder.go, lines 53-57:
Cached stream ends suppress corrections after a file is re-probed
After a file is re-probed, the scanner can restore a longer stored duration while this process still remembers the old end, so subsequent transcodes reporting the same end never correct the phantom playlist tail again. Invalidate the deduplication entry when the file is re-probed, or make deduplication depend on the probe revision.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in fda1530. A written end is remembered for ten minutes instead of for the life of the process, so a duration that a later probe stores again can be corrected again. The write itself now also applies only while the stored duration is still the one the transcode was planned with.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update. The ten-minute expiration addresses the indefinite suppression described in the suggestion, although a re-probe can still leave corrections suppressed until the cached entry expires. The planned-duration check also helps prevent a stale transcode from overwriting a newer duration.
I haven’t independently verified commit fda1530fe.
The reason will be displayed to describe this comment to others. Learn more.
Unaligned seek restarts produce an incorrectly shortened media endpoint
Jellyfin audio-selection restarts can seek to an arbitrary positionSeconds, so using SegmentAt(positionSeconds) understates the endpoint by the offset within the segment. Convert playlist durations using the actual seek origin, or skip duration recording for unaligned runs.
Prompt for LLM
File internal/playback/transcode.go, line 3499:
Unaligned seek restarts produce an incorrectly shortened media endpoint
Jellyfin audio-selection restarts seek to an arbitrary `positionSeconds` while numbering output from `SegmentAt(positionSeconds)`, so this calculation understates the real endpoint by the offset within that segment. Use the run's actual seek origin when converting its playlist durations to source time, or avoid recording a duration for unaligned runs.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in fda1530. The end is now the run's seek position plus the length of the segments it wrote, instead of its last segment number times the segment length, so a restart at an unaligned position (the Jellyfin audio switch) measures the right end. A new subtest restarts at 145.3 s, writes 5.5 s, and expects 150.8 s; it fails on the old arithmetic.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update. Using the run’s actual seek position plus its segment durations addresses the reported unaligned-seek issue, and the new subtest covers the example. I haven’t independently verified the commit or test results.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
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: 7d4200d9-e252-494d-b3f6-47bcfbb812ae
Commits
Reviewing files that changed from the base of the PR and between c8f3a01 and 8c40826.
Files selected for processing: 27
cmd/silo/main.go
cmd/silo/transcode_node.go
contracts/api/v2/openapi.json
docs/architecture/playback-protocol-v3.md
docs/architecture/transcode-nodes.md
docs/playback-api.md
internal/api/handlers/playback.go
internal/api/router.go
internal/jellycompat/router.go
internal/jellycompat/server.go
internal/jellycompat/streams.go
internal/nodecontrol/server.go
internal/nodecontrol/server_test.go
internal/nodesessions/tracker.go
internal/playback/errors.go
internal/playback/past_end_segment.go
internal/playback/past_end_segment_test.go
internal/playback/segment_recovery.go
internal/playback/session.go
internal/playback/stream_end_recorder.go
internal/playback/transcode.go
internal/playback/transcode_manager.go
internal/playback/transcode_manifest_test.go
internal/scanner/file_repo.go
internal/scanner/probe.go
internal/scanner/probe_duration_test.go
internal/transcodenode/server.go
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.
…on it corrects
Review follow-ups on the stream-end correction:
- The end is where the run started (its seek) plus the length it wrote, not
its last segment number times the segment length: an audio-track switch
restarts at the player's position, inside a segment.
- The run's own options and inherited playlist are captured when it starts,
so an audio switch before a clean exit cannot tag the old run's end with
the new track.
- The stored duration is lowered only while it is still the one the
transcode was planned with (stream_planned_seconds in a node's report), so
an end measured on a file since replaced or probed again changes nothing.
- A written end is remembered for ten minutes instead of for the life of the
process, so a duration a later probe stores again can be corrected again.
- A node report's sessions reuse the node identity HandleReport resolved.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
Duration equality does not protect replacement files from stale stream ends
A replacement or re-probe can retain the same whole-second duration, allowing a stale transcode end to permanently truncate the replacement's playlists. Carry the planned file or probe revision with the learned end and require it to match during the update.
Prompt for LLM
File internal/scanner/file_repo.go, line 979:
Duration equality does not protect replacement files from stale stream ends
A replacement or re-probe can retain the same whole-second duration, so a stale transcode's end still passes this predicate and permanently truncates the replacement's playlists. Carry the planned file or probe revision with the learned end and require it to match in the update as well.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 4c3c12f. The planned-duration check alone let a same-path replacement with the same stored duration through, as you describe. A learned end now also carries when the run that measured it started reading the file. For a transcode node, that is when the core's playback session started, which no run of it precedes. ShortenDuration adds AND probe_updated_at < <that time>. A replacement is probed after the old run started, so its row no longer matches, and a row with no probe time is left alone. TestShortenDurationOnlyForTheFileTheRunReadDB covers the replacement case and fails without the new condition. It is listed in scripts/ci/db-contracts.txt.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the follow-up. The probe timestamp condition addresses the reported case where a replacement is re-probed after the old run started, even if its stored duration is unchanged. Leaving rows without a probe timestamp untouched is a conservative choice, and the regression test covers the scenario.
I haven’t independently verified commit 4c3c12fc2 or run the test.
A same-path replacement probed to the same whole-second duration still
matched ShortenDuration's planned-duration check, so a stale transcode's
end could shorten the new file. A learned end now carries when its run
started (for a node's transcode, when the core's playback session
started), and the duration is lowered only when the row was probed before
that. A row with no probe time keeps its duration.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Main's AV1 hardware-decode stop (Silo-Server#4478) added fields and a per-line hook to
ffmpegStderrWriter; keep both it and this branch's demux-error flag.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
An end that rounds up to the planned duration shortens nothing, yet every
node transcode that finished reported one and ran an UPDATE that matched no
row. Return before writing.
The past-end TS segment copies the PAT of a session segment; a packet whose
adaptation field, pointer field or section length overruns it sliced out of
range. Treat such a packet as naming no PMT, so the generic tables are used.
The protocol doc now says a node reports the end once it learns it, and that
only the API server holding the playback session stores it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
Review of ce35ed2, which is this branch with current main merged in. Main's AV1 hardware-decode stop touched ffmpegStderrWriter, so the merge keeps both that stop and this branch's demux-error flag. A three-model review of the merged head found no correctness problem in the end-of-stream path. It found the three low-severity items below. I'm fixing all three in a commit on this branch, so there's no need to change them yourself.
Code Review Completed, but its comments could not be posted ⚠️
The review produced 1 comment(s), but none could be posted to this pull request (for example, the platform rejected them with a rate limit). This is not a clean review: comment @kody review on this PR to run it again.
Kody Guide: Usage and ConfigurationInteracting 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.
Validate Business Logic: Ask Kody to validate your code against business rules by adding a comment with the @kody -v business-logic command.
Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.
Current Kody ConfigurationReview Options
The following review options are enabled or disabled:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bugSomething isn't workinggoPull requests that update go codeimpact: playbackCan't play, stalls, or wrong mediapriority: P1Core-path bug; painful workaround — next after P0size/XXL1000–2999 added + deleted lines (all files); change volume, not priority.
2 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Related issue: N/A
Validation tasks: none (#1177 C3 runs through the transcode node's segment handler, but only a request past a finished transcode's last segment behaves differently)
Other clients: Apple N/A (server-only fix, checked on iOS and tvOS); Android N/A (server-only fix, checked on Android TV); Roku N/A (server-only fix, Roku plays the same HLS playlists)
Some MKV files have a container duration longer than their video: an ASS subtitle track that ends a few seconds after the film is enough. When such a file plays as an encoded transcode, the player reaches the end and freezes on the last frame. A few seconds later it fails with "All compatible playback recipes have already failed for this output route." This affects every client that plays the transcode: Android TV, iOS and tvOS all showed it. This change makes the stream end cleanly at the real end of the video, and the scanner now stores the video's length for files like this.
The synthetic VOD playlist of a transcode lists two-second segments up to
media_files.duration. For the test file "H264 MoreFonts (2018)" that is 154 s, while the video ends at 150 s. FFmpeg finishes at 150 s and never writes the last two segments. A request for one of them found FFmpeg "not running", treated that like a crash, and seek-restarted FFmpeg at the end of the file. That FFmpeg wrote nothing, the request failed, and the player asked for the same segment again until it gave up.Approach
Error during demuxing. A run whose own playlist lists segments with media sets the end to the last of them; a run that wrote no media (it started past the end) only bounds it. A video segment request past the learned end answers200with a segment that holds no media (recovery reasonpast_end_of_stream): the PAT and PMT of one of the session's MPEG-TS segments, or an fMP4moofand emptymdatbuilt from the init segment. It does not wait and does not restart FFmpeg; players treat such a segment as a gap and end at the video's end. A crash, a kill, a non-zero exit, or an exit 0 after a logged demux read error still restarts as before. Copy-video and keyframe-planned copies keep their own rules, and a learned end holds only for the audio track it was learned with. The check sits in the segment recovery core the native API, jellycompat and transcode nodes share (OpenSegmentWithRecovery), before a restart, again under the restart lock, and after one.media_files.durationis lowered to where the run found the media ends (playback.StreamEndRecorder,FileRepository.ShortenDuration), so the next play's playlist ends with the video. The API server does this for its own transcodes; a transcode node reports the end in its session report (stream_end_seconds), and the core accepts it only for a transcode a playback session it holds runs on that node for that file. It never lengthens a duration, applies only while the stored duration is still the one the transcode was planned with and the file was last probed before the measuring run started reading it, and skips files with more than one audio track.audioVideoSpanalready replaced the container duration with the video and audio span when a subtitle track stretched it, but only past a 5 s tolerance, so a 4 s stretch was kept. It now applies past 1 s, and only when another track that ends after the video and audio accounts for the container duration. Files whose longer container nothing explains keep their duration.Existing rows keep their stored duration until a transcode of the file reaches the end or the file is probed again; there is no backfill.
Other fixes from the same report (an MKV with many large embedded fonts, with ASS subtitles, on Android TV): #4640, #4641, #4642 and Silo-Server/silo-android#1010. #4642 also edits
internal/scanner/probe.go, in different functions.Validation
go build ./...,go veton the touched packages,gofmt,go mod tidy -diff: clean.make lint-changed,make lint-router-recovery: 0 issues.go testforinternal/playback/...,internal/scanner/...,internal/transcodenode/...,internal/jellycompat/...,internal/api/handlers: pass. The handlers package needs umask 022 locally; its upload tests fail under umask 002 onmaintoo.make verify-local-paths,verify-size-ratchet,verify-bidi,verify-case-collisions: pass.200, including a request that arrives while another request's restart is in flight. A duration table covers a 4 s subtitle stretch, a stretch nothing explains, and a subtitle that ends before the video.make test-goand the web gate (no web change).OpenSegmentWithRecovery, so the end-of-stream check moved there. Review fix c8f3a01 adds the check after the post-restart wait;TestSegmentRestartPastEndOfStreamEndsTheStreamfails without it.go build ./...,make lint-changedandmake lint-router-recoveryare clean, and the playback, scanner, transcode node, jellycompat and handlers tests pass on c8f3a01.EXTINF:0playlist) never raise or fabricate an end, the restart-lock re-check, a node's reported end needs a matching session, the past-end TS bytes, the recorder, and a two-subtitle scanner row. The touched packages pass, andmake lint-changedandmake lint-router-recoveryreport 0 issues.stream_planned_secondsin a node's report); a written end is remembered for ten minutes; node reports reuse the resolved node identity. New subtest for an unaligned restart fails on the old arithmetic.ShortenDurationrequiresprobe_updated_atbefore it.TestShortenDurationOnlyForTheFileTheRunReadDB, added toscripts/ci/db-contracts.txt, fails without the check. The touched packages pass on d424365 against a freshly migrated Postgres, andmake lint-changedreports 0 issues.ffmpegStderrWriter; the merge keeps the stop and the demux-error flag. On the merged head the playback, scanner, node control, node sessions, transcode node and jellycompat tests pass against a freshly migrated Postgres (TestShortenDurationOnlyForTheFileTheRunReadDBran, not skipped), andmake lint-changedandmake lint-router-recoveryreport 0 issues.UPDATEfor every finished node transcode, and a PAT packet whose lengths overrun it no longer panics the past-end TS answer. The new rows inTestStreamEndRecorderandTestPastEndTSProgramTablesfail without the fixes. The protocol doc now says a node reports the end once it learns it, and that only the API server holding the playback session stores it.main.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-4639-r3/
Surface and build: the web app (headless Chromium), an Android TV emulator and an iPhone simulator with the current Silo clients, against a sandbox built from this branch (tree of 675c925) with a transcode node. The author's earlier captures (Android TV, iOS and tvOS against
mainand the first version of this branch) and the review captures of the zero-byte answer on the web are on earlier pages of the same evidence site.Risks
If FFmpeg ever exits 0 early without logging a demux error, the session would end the stream at the last segment it wrote instead of restarting, and the stored duration would be lowered to that point until the file is probed again. The test suite pins the one early-exit case known to exit 0 (a failed read) to the restart path. No migration and no client API shape change: the segment endpoint answers
200with a segment that holds no media where it used to fail. The node-to-core session report gains one optional field (stream_end_seconds), which an older core ignores.Checklist
AI Disclosure
Note
Serve empty segments past a finished transcode's learned stream end
Encoded transcodes can produce synthetic playlists that extend past the actual media duration, so segment requests near the end previously triggered restarts and errors. This PR has the FFmpeg monitor learn the media's real end from a cleanly finished run and serve valid empty MPEG-TS or fMP4 segments for requests beyond it.
monitorFFmpeglearns the last nonempty segment and end time from a run's manifest; failed, demux-error, cancelled, copy-plan, and multi-audio runs are excluded. Empty runs starting after segment 0 set a bound just before their start (transcode.go)OpenSegmentWithRecoveryandRestartSegmentSincereturn a newErrPastEndOfStream(wrappingErrSegmentNotFound) instead of restarting when the segment is past the learned end (segment_recovery.go)ServePastEndOfStreamserves HTTP 200 with an empty segment: TS reuses PAT/PMT packets from a nearby segment (or generic tables), fMP4 builds a moof with zero-sample truns per track plus an empty mdat (past_end_segment.go)StreamEndRecordershortens the stored file duration asynchronously viaFileRepository.ShortenDuration, which only lowers duration when the row still matches the planned duration and probe revision and has at most one audio track; transcode nodes report ends and the API server validates them against the session and reporting node (stream_end_recorder.go, file_repo.go, server.go)SessionInforeports gainstream_end_secondsandstream_planned_secondsfieldsMacroscope summarized e0c4904.