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
Direct play, remux, and transcode playback startup paid avoidable serial latency across the server, distributed nodes, and web player:
Tone-map probe and SDR transcode startup: When a cluster-wide hw_device list named a render node absent on the local host (for example renderD128,renderD129 on a host exposing only renderD128), tonemap.Probe failed every smoke test on the missing node, discarded the working node's capabilities, cached a negative result, and re-ran ~6 s of FFmpeg probes on every playback start, even for SDR sources that never tone-map.
Intel QSV first-segment latency: QSV H.264/HEVC transcodes buffered multiple lookahead/B-frames before emitting the first HLS segment.
Direct-play Dolby Vision RPU probe: /api/v2/playback/start ran a synchronous ffprobe bitstream check for Dolby Vision Profile 8 RPU stripping (~1.4 s over network storage) even when the client already supported direct play without stripping.
Serial auth, DB, and distributed node hops: Viewer access resolution ran independent user/policy/store/profile queries sequentially and loaded browsing-only preferences on media delivery routes; /stream ran live session deny check and media file lookup serially; transcode/proxy nodes re-probed hardware capabilities on refreshes, sent uncompressed multi-thousand-segment HLS manifests, and waited with coarse polling intervals for initial segments and completion signals.
Web player startup contention: Watch page navigation waited on redundant codec probes, uncached bandwidth/watch-detail fetches, redundant initial WebSocket marker reconciles, and immediate trickplay fetches alongside initial media bytes.
Approach
Server and distributed nodes
Tone-map probing and SDR skip (internal/tonemap/, internal/api/handlers/playback_v3.go, internal/playback/transformations_v3.go): Filter cluster-wide QSV/VAAPI DRM device lists to nodes openable by the local process (probeDevicesForHost), skip tonemap.Probe on SDR sources when tone-mapping cannot be needed, and add unit coverage in internal/tonemap/probe_test.go.
Encoder, remux, and seek-anchor startup (internal/playback/transcode.go, remux.go, copy_seek_anchor.go, candidate_video_v3.go): Add Intel QSV low-latency flags (-async_depth 1 -bf 0, plus -look_ahead 0 for H.264) and NVENC -preset p2 for live encodes, give fresh software H.264 starts x264's latency settings only (sync-lookahead=0:rc-lookahead=0:sliced-threads=1), use a 500 KB / 0.5 s input probe for Matroska and MP4 while MPEG-TS/PS files and node relay inputs keep 3 s / 5 MB, flush progressive fMP4 every 500 ms (2 s for audio-only), start every fresh generation after one segment, defer Dolby Vision RPU strip probing until a route actually needs stripping, and trim copy-seek anchor overhead.
Access resolution, stream fast path, and plan store (internal/access/, internal/policy/, internal/api/middleware/viewer_access.go, internal/api/router.go, internal/apiv2/gates.go, internal/api/handlers/stream*.go, internal/playback/planstore/postgres.go): Overlap independent account/policy and user-store reads, reuse the resolved account policy in session admission limits, skip browsing-only viewer preferences on media delivery routes, and overlap Redis deny checks with media file lookups on live in-memory sessions.
Distributed nodes and manifests (internal/playback/manifest_http.go, internal/transcodenode/, internal/proxy/, internal/transcodeproxy/, internal/nodeauth/, internal/nodecontrol/, internal/nodepool/): Cache transcode-node and proxy capability snapshots keyed by the configuration and identity read before the build (a snapshot whose configured hardware or tone-map probe didn't settle is served for 15 s and rebuilt within a minute), gzip HLS playlists of 1 KiB or more in memory with an exact Content-Length when Accept-Encoding admits it by the API compressor's rules (WriteHLSManifest, httpstream.AcceptsGzip), tighten liveness polling, and speed up proxy media-grant/reprobe handoffs.
Web player
Defer trickplay manifest fetches until playback starts or a 1.5 s fallback timer fires (useDeferredWatchTrickplay).
Prefetch watch detail when the viewer points at, presses, or focuses Play (ActionBar), warm the watch route chunks after sign-in, probe the browser decoder after sign-in when idle (App), avoid chapter refetches when chapters is explicitly [], parallelize codec capability checks (useCodecDetection, engine/capabilities.ts), and seed the playback capability cache from the bandwidth probe (start-v2.ts, bandwidth-probe.ts).
Validation
Go race unit tests across all 18 modified packages (umask 0022 && go test -race -count=1 ./internal/access/... ./internal/api/handlers/... ./internal/api/middleware/... ./internal/apiv2/... ./internal/nodeauth/... ./internal/nodecontrol/... ./internal/nodepool/... ./internal/playback/... ./internal/policy/... ./internal/proxy/... ./internal/tonemap/... ./internal/transcodenode/... ./internal/transcodeproxy/...): all passed.
Go linters and repository contracts (make lint-changed, make lint-router-recovery, make verify-size-ratchet verify-route-inventory verify-fork-pins verify-settings-bindings-all verify-playback-fixtures verify-local-paths verify-case-collisions verify-bidi, go test -count=1 -run '^TestCommittedArtifactMatchesRouter$' ./internal/apiv2/): all passed (0 issues).
Web checks (pnpm run lint, pnpm run format:check, pnpm run build, pnpm run budget:check, pnpm exec vitest run src/player/ src/pages/audiobooks/player/useAudiobookPlayback.test.ts): all passed (45/45 player test files, 849/849 tests; 23/23 audiobook tests).
Review fixes (head e96c17c3ad): make lint-changed and make lint-router-recovery 0 issues; size ratchet, route inventory, local paths, bidi, and TestCommittedArtifactMatchesRouter passed; go test -race on httpstream, tonemap, transcodenode, proxy, transcodeproxy and go test on playback and api/handlers passed; web tsc -b, ESLint, Prettier, and the player, playback, item-detail, audiobook-player, and boot tests passed.
Round-3 and round-4 fixes (head 1a48766e17): make lint-changed 0 issues; size ratchet passed; go test -race on transcodenode, tonemap, proxy, and the handler capability, start, replay and direct-state tests passed; focused playback tests passed.
On sandboxes with software encoding, median POST /api/v2/playback/start over 8 warm runs went from 2,698 to 1,420 ms for an HDR10 software tone-map transcode, and from 472 to 350 ms for a forced 1080p→480p transcode, with fresh CPU encodes starting on two segments. On an Intel Arc GPU with QSV and OpenCL tone mapping, HDR10 and Dolby Vision tone-map starts went from about 2.0–2.1 s to 1.4–1.6 s. A 1080p SDR QSV transcode showed no measurable change: about 0.8 s on main and 1.0 s here, both varying between 0.4 and 2.2 s. Gzipped playlists match the identity body byte for byte. The page also has the x264 quality comparison, the Apple HLS check against gzipped playlists, and the input-probe sweep over the release fixtures.
The author's measurements, on commit 90e782e2ee via automated test/contract gates and live server playback measurements:
1080p SDR H.264 QSV transcode startup (/api/v2/playback/start): dropped from 6,581 ms to 774 ms (all 6 hardware HDR tone-map kinds probed and cached on the accessible DRM render node; SDR playback no longer triggers tone-map probing).
4K Dolby Vision Profile 8.1 MKV direct-play startup (/api/v2/playback/start): dropped from 1,462 ms to 23 ms after deferring the synchronous RPU strip probe when direct play is already selected.
Distributed transcode/proxy startup and manifests: gzipped HLS playlists preserve exact Content-Length and shrink multi-thousand-segment VOD playlists by ~20x on the wire (TestWriteHLSManifestGzipAndIdentity).
The QSV figure didn't reproduce in review: on the Arc host, main already starts that case in about 0.8 s.
Risks
Disabling B-frames (-bf 0) and lookahead (-look_ahead 0) on Intel QSV trades a small amount of compression efficiency for lower initial-segment latency during live/VOD transcoding.
RequireMediaViewerAccess omits browsing-only preferences (Next Up, card overlays, metadata language, disabled library browse filters) on stream-reference media delivery routes; authorization, profile verification, and session ownership checks remain identical.
Fresh hardware encodes start after one segment (two on main), fresh CPU encodes after two (three on main), and codec copies after one (two on main). Reconstructed generations keep three.
NVENC live encodes use -preset p2, faster and slightly lower quality than the default p4.
Hardware tone-map and distributed node paths touch validated cases #1172 C1, C2, C3 and #1177 C1, C3; re-checking hardware HDR tone-mapping and multi-node failover after merge is recommended. Review ran QSV on an Intel Arc GPU; VAAPI and NVENC were not exercised.
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.
Council review
Rounds: 3, last reviewed 8675e3fc23 (round-3 fixes in cb3496fc92 through 1a48766e17)
Member
Round 1
Round 2
Round 3
Sol (gpt-6.2-sol, medium)
5/10
7/10
7.5/10
Opus (claude-opus-5-5, medium)
5/10
8/10
8/10
Gemini (gemini-4-neon, medium)
6.5/10
8.5/10
8.5/10
Visual review: not run; nothing changes on screen.
Fixed in rounds 1 and 2:
Server: shared capability fetch tied to one caller, replay and lifecycle ordering, subtitle error caching, capability snapshot keying and recovery, fast-start x264 quality, input probe on relay and MPEG-PS inputs, segment poll interval, audio-only fragments, and playlist gzip negotiation.
Cut stream startup latency across direct-play, remux, and transcode paths
Parallelizes playback start: PlaybackHandler.startPlaybackApplicationV3 overlaps attempt lookup, state resolution, file loading, and settings reads; replayed attempts return without waiting for other reads (playback_v3.go)
Speeds up FFmpeg startup: path-dependent input probe budgets, tighter startup segment thresholds (1 segment for copy and fresh hardware, 2 for fresh software), fast AAC coder, thread limits, and low-latency QSV/NVENC settings for live encodes (transcode.go)
Caches probes and lookups: node capabilities (TTL 10 minutes, shared via singleflight), primary-video probes, copy seek anchors, downloaded-subtitle inventories per request, and derived MAC keys
Adds HLS manifest gzip compression with exact Content-Length via playback.WriteHLSManifest, used by handlers and relays (manifest_http.go)
Defers Dolby Vision strip capability probes until a remux route is actually taken, and skips tone-map probing for SDR sources; remux candidates are skipped when remux is inactive
Speeds up client start: cached codec/engine probe answers, watch-detail prefetch on play-control hover, WatchPage chunk preloading, and 0.08s worker audio buffering threshold
Risk: new defaults change encoder flags, fragment durations (fixed 500ms/2s), and startup thresholds — verify buildFFmpegArgs, buildRemuxArgsWithLeadingPictureDropV3, and startupSegmentRequirement against existing players; capability snapshot expiry (15s unsettled TTL) and identity-keyed reports may change /hwcapabilities responses after re-probe
This PR updates HTTP manifest compression, access and stream-session resolution, playback planning and transcoding, node capability handling, and web playback startup. It also changes node communication, probe caching, and playback-related data fetching.
Manifest responses negotiate gzip, set the selected payload length, and use shared response-writing helpers. API and node relays negotiate upstream encoding and rewrite manifests when required.
Segment relay completion and liveness internal/api/handlers/playback.go, internal/proxy/server.go, internal/proxy/segment_completion_test.go, internal/transcodeproxy/completion.go, internal/transcodeproxy/liveness.go
Completed segment responses are flushed before asynchronous acknowledgement. Streamed node bodies use a reusable timer to detect unresponsive nodes.
Access and Playback Sessions
Layer / File(s)
Summary
Viewer policy resolution and gates internal/access/*, internal/policy/viewer_resolver.go, internal/api/middleware/viewer_access.go, internal/apiv2/gates.go, internal/api/router.go
Access resolution can skip viewer preferences and return resolved user policy through request context. Media-delivery gates use this path, and session limits reuse the resolved policy when available.
Live and reconstructed stream sessions internal/api/handlers/stream.go, internal/api/handlers/stream_session_resolve.go
Stream handling delegates live and reconstructed session checks to dedicated resolvers. The resolvers check denial, ownership, egress, session status, and media-file resolution.
Media grant authorization internal/proxy/mediagrant.go
Grant authorization runs login, grant, and applicable denial lookups concurrently, then checks the requested session and associated session identifiers.
Playback start reads and replay internal/api/handlers/playback_v3.go, internal/api/handlers/playback_connection.go, internal/api/handlers/playback_desired_tracks_v3.go, internal/api/handlers/playback_direct.go, internal/api/handlers/playback_session_recipe.go
Playback start overlaps lookup and preflight work, extracts replay and resume handling, and reuses downloaded-subtitle and connection data. Planner settings use a batch read when supported.
Canceled Redis denial lookups return without caching a negative result. The test checks that a later active lookup still sees the marker.
Playback Planning and Transcoding
Layer / File(s)
Summary
Playback route and probe selection internal/api/handlers/playback_v3.go, internal/playback/candidate_routes_v3.go, internal/playback/candidate_video_v3.go, internal/api/handlers/playback_v3_union_test.go, internal/playback/plan_v3_dv_strip_fallback_test.go
Planning skips tone-map inventory for applicable SDR sources and defers Dolby Vision strip checks until remux is active. Tests cover both planning paths.
Probe results are cached in selected paths. Transcode and remux arguments update probe budgets, thread and encoder settings, fragment durations, and startup segment requirements. Transformation probes run in concurrent phases.
Tone-map devices and filters internal/tonemap/dri_access.go, internal/tonemap/probe.go, internal/tonemap/tonemap.go, internal/tonemap/vaapi_vendor.go, internal/tonemap/probe_test.go
Hardware probes filter inaccessible devices and select filters from the resulting device list. Software conversion filters add optional scaling for non-Dolby Vision sources.
Node Capabilities and Communication
Layer / File(s)
Summary
Remote capability lookup and warmup internal/api/handlers/playback.go, internal/api/handlers/playback_v3.go, internal/api/handlers/playback_v3_capability_retry_test.go
Capability lookups coalesce concurrent requests and warm both proxy and transcode nodes. Tests cover shared fetches and caller cancellation.
Proxy and transcode nodes cache capability reports against configuration and identity keys. Reprobes and refreshes publish successful snapshots; transcode snapshots use expiry based on verification and retry state.
Node authentication and HTTP transports internal/nodeauth/nodeauth.go, internal/nodecontrol/client.go, internal/nodepool/health.go, internal/playback/transcode_manager.go
Node request MAC keys are cached. Control, health-check, and remote transcode clients use transports with node dialing and per-host idle-connection limits.
Web Playback Startup
Layer / File(s)
Summary
Watch route and detail prefetch web/src/App.tsx, web/src/playback/WatchPlaybackChrome.tsx, web/src/hooks/useViewTransition.ts, web/src/hooks/queries/items.ts, web/src/pages/ItemDetail/components/ActionBar.tsx
Watch route chunks are included in hot-route loading. Playback navigation preloads the watch page, disables view transitions, and Play controls prefetch watch-detail data.
Playback capabilities can be seeded and remain cached longer. Engine and codec probes expose settled results, which the browser engine hook and authenticated idle prewarmer can reuse.
Several playback startup paths still have open correctness issues. A stopped session can still receive media, and hardware tone-mapping can pick a device the probe never validated. Resolve these before merging.
Security architecture risk: Moderate · up to 1a487
Playback startup does less serial work, but a stop or policy change can miss a request already underway. A completed HLS response can also be counted too late to prevent the API from saving an incorrect bandwidth limit. Upgrade the API and Proxy relays before enabling manifest compression on Transcode nodes.
Minor · security · inferred: The Proxy can begin serving an already-in-flight header-authenticated direct request after its playback session is stopped. The merge base checked the deny marker after login and grant validation; the PR starts that lookup alongside them and reuses its result. A stop that becomes visible during those checks could have been caught by the base on a cache miss. The later check runs only for a distinct grant session or transport ID. The request still needs a valid login, an owned grant, and the correct route. Check the requested session's revocation state at the final authorization decision.
Minor · security · inferred: The API direct-stream fast path treats a copied session as authority to start serving even if the live session is gone. If a stop removes the session after the copy and a negative deny result but before the base's later session read would have run, the base can refuse. The PR receives a not-found result from BeginTransport but still calls ServeDirectPlay. This affects an already-in-flight request from the session owner. Require the live session and its route to match at transport admission before serving bytes.
Minor · security · inferred: SessionManager can admit work under a policy the administrator has already tightened. The merge base reread user and group policy at admission; the PR reuses the matching account's ViewerAccess snapshot. A lower stream or transcode limit, or a ban on video or audio transcoding, can therefore miss requests already carrying the old policy. Live counts are still checked, and the policy engine receives those counts but uses the supplied limits. Requests without a matching snapshot still reread policy. Revalidate policy at the point that admits or reserves playback work.
Trivial · security · observed: The worker MAC cache keeps the raw secret as a process-wide map key and the derived key as its value. The merge base derived the key per call; now rotation or expiry does not remove previously used material. A quiet process can retain it until restart. This requires access to the process's memory and is limited to credentials it has used; the cache does not make a retired credential acceptable on the wire. Tie cached material to the active credential lifecycle.
Minor · reliability · inferred: The Proxy can finish a segment response with acknowledgment still pending, whereas the merge base waited for the attempt before returning. If a replan checks Transcode node progress before the acknowledgment arrives, stale completion progress can look like encoder lead. For an eligible automatic-quality rebuffer report, the API can then persist a device and connection bandwidth cap for a stall caused by the encoder. The later acknowledgment advances the counter but does not undo the cap. Treat progress with an outstanding receipt as inconclusive before storing a limit.
Trivial · reliability · inferred: The documented relay-first upgrade order is required to preserve manifest framing. The base origin sent an identity response with a known length. With a new Transcode node behind an old pass-through relay, Go can add gzip upstream, transparently decode the reply, and drop its length. A length-sensitive player can then reject or misread the playlist. Updated relays explicitly set the upstream encoding before fetching a playlist, but the new writer does not require that the request came from an updated relay. Operators must avoid that version pairing on upgrade and rollback, or keep the origin on identity until relay support is verified.
inferred — The evidenced stop regressions affect authorized, already-in-flight requests for the affected playback session, not account isolation. The admission regression affects the account whose request carries an old policy and can consume shared stream or transcode capacity. The credential-retention issue is scoped to secrets used by a process whose memory is accessible.
Trust Boundaries and Controls
observed — The Proxy verifies the viewer's access JWT and login, matches the grant to the account and, for remote-playback handoff, the bound profile, then checks route and endpoint binding. The deny marker is a separate playback-stop control. Its short negative cache and fail-open Redis behavior predate the PR; the changed ordering can miss a stop even when Redis is healthy.
Public contracts
observed — The HLS writer reports exact wire length and varies by Accept-Encoding. It uses gzip only for eligible manifests at least 1 KiB in size when compression reduces the payload, otherwise keeping identity. The API relay requests identity when it needs to rewrite playlist URLs.
Dependencies
observed — The API asks the remote Transcode node whether the encoder paced playback before saving an eligible learned limit. An unreachable node or failed read suppresses learning, but a successful read does not distinguish a genuinely undelivered segment from one whose acknowledgment is still pending at the relay.
Data and control flow
observed — Fresh starts skip reading a prior Proxy grant because the grant is keyed by the server-generated session ID, not by the caller's attempt ID. If the attempt insert loses a race or fails, the handler rolls back and aborts its own session. The inspected rollback paths stop newly prepared remote work, release reservations where applicable, and delete a newly written grant or restore the previous grant on replacement. Store and node failures can still prevent best-effort cleanup.
Resilience and Maintainability Implications
observed — After a complete segment GET, the Proxy attempts to flush and dispatches a signed acknowledgment with its own timeout. It falls back to synchronous acknowledgment when background slots are full. The worker ignores receipts from prior session incarnations or generations and advances completion monotonically, so delayed or repeated receipts cannot credit replacement work. Neither the response nor the fallback guarantees a recorded receipt; failures are logged, and a late receipt cannot reverse a bandwidth cap the API has already saved.
Rollout and rollback
inferred — Before upgrading Transcode nodes, the operator must verify that every API and Proxy relay on their HLS paths explicitly sets the upstream encoding. The origin checks encoding negotiation at request time, not the relay's version. For rollback, return the origin to identity behavior before reverting a relay that would implicitly request gzip. The documented order is an operator prerequisite, not a transition the protocol prevents.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title "perf(playback): cut direct-play, remux, and transcode stream startup latency" matches the main change. The changeset targets playback startup latency across direct-play, remux, and transcod…
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 PR description is detailed and directly relevant to the changeset. It covers playback startup latency across tone-map probing, FFmpeg encoder and remux settings, access resolution, HLS manifest gz…
Full details: Title check
Explanation
The title "perf(playback): cut direct-play, remux, and transcode stream startup latency" matches the main change. The changeset targets playback startup latency across direct-play, remux, and transcode paths, including tone-map probing, Dolby Vision RPU probe deferral, FFmpeg encoder/probe settings, access resolution, node capability caching, and web player prefetching. The title is specific and concise, though it is broad because the PR spans server, distributed nodes, and web player.
Full details: Description check
Explanation
The PR description is detailed and directly relevant to the changeset. It covers playback startup latency across tone-map probing, FFmpeg encoder and remux settings, access resolution, HLS manifest gzip, node capability caching, and web player prefetching. It also lists validation, risks, and evidence, which match the files in the raw summary.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
The reason will be displayed to describe this comment to others. Learn more.
Limit the reconciliation bypass to the initial file
When playback switches to another version within the same session without disconnecting the control socket, this condition skips reconciliation again because the session/file key changed and the version already exists in versions. That version's markers can be stale: WatchPagePlayer ignores markers_updated events for files other than session.mediaFileId, so updates received while the version was inactive were discarded. Previously the active-file change fetched its current markers; now incorrect intro/credits ranges can persist until a socket reconnect. Restrict the bypass to the first connection rather than every previously unseen session/file key.
The reason will be displayed to describe this comment to others. Learn more.
Confirmed and fixed in 4273991, which restores main's reconcile on every connect. The first-connect skip had a second gap: it trusted a watch detail that can now be up to 15 seconds old or prefetched from the item page, and the server drops markers_updated for a session without a realtime connection, so a marker saved before the socket connected stayed stale. The reconcile runs after playback starts, so it costs no startup time.
The reason will be displayed to describe this comment to others. Learn more.
One request deadline fails other shared capability lookups
A deadline expiration can propagate context.DeadlineExceeded to healthy concurrent playback requests because the shared fetch uses the first request's context. Retry the shared fetch on deadline expiration as well as context.Canceled, or use an independent bounded context.
Prompt for LLM
File internal/api/handlers/playback_v3.go, lines 719-728:
One request deadline fails other shared capability lookups
A shared capability fetch uses the first request's context, but waiters retry only `context.Canceled`, so that request's deadline expiration propagates `context.DeadlineExceeded` to otherwise healthy concurrent playback starts. Retry a shared fetch when the initiating context expires as well as when it is canceled, or run the shared fetch under an independent bounded context.
The reason will be displayed to describe this comment to others. Learn more.
Confirmed and fixed in 9a81ee1. The shared fetch now runs on a context detached from any one caller, bounded by the node's probe budget, and each waiter still stops at its own deadline. TestSharedCapabilityFetchOutlivesTheLeadersDeadline fails on the previous head (the joiner re-fetched on its own) and passes now, 3 of 3 under -race. A panic inside the shared fetch becomes its error.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for addressing this. Based on your description, the detached, bounded fetch resolves the shared-deadline issue while preserving each caller’s ability to stop waiting. The regression test also covers the leader-deadline scenario.
I haven’t independently verified the commit or test results.
The reason will be displayed to describe this comment to others. Learn more.
Playback attempt replays wait for unrelated startup reads
Idempotent retries incur extra database load and wait for unrelated reads even when a replayable decision is available. Complete the attempt lookup first or let h.replayExistingStartAttemptV3 return without waiting for the speculative reads.
Prompt for LLM
File internal/api/handlers/playback_v3.go, lines 2301-2305:
Playback attempt replays wait for unrelated startup reads
Idempotent retries now wait for the direct-state, authorized-file, and planner-settings reads even when the attempt lookup already found a replayable decision, adding database load and the slowest unrelated read to every retry. Complete the attempt lookup first for replayed requests, or allow it to return without waiting for the speculative reads.
The reason will be displayed to describe this comment to others. Learn more.
Confirmed and fixed in 9a81ee1: the attempt lookup runs alone first in the wait order, so a replay answers as soon as it returns. The other three reads are still started in parallel for a fresh start.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update. The described change addresses the replay latency concern by returning as soon as the attempt lookup completes. The three speculative reads may still add database load on replay requests.
The reason will be displayed to describe this comment to others. Learn more.
A configuration change during probing can poison the capability cache
A configuration or node identity change during probing can cause stale capabilities to be cached under the new key. Capture the build's key and call s.storeCapabilitySnapshot only if it still matches s.currentCapabilityKey().
Prompt for LLM
File internal/transcodenode/server.go, line 1672:
A configuration change during probing can poison the capability cache
If configuration or node identity changes during the probe, the result built from the old values is stored under the new key and subsequent capability requests serve it as current. Capture the key associated with the build and publish only if it still matches the current configuration.
The reason will be displayed to describe this comment to others. Learn more.
Confirmed and fixed in 472b697, on the transcode node and the proxy. The key is read before the build and the snapshot is cached only while that key is still current, inside the build lock, so a scheduled refresh also can't overwrite a newer re-probe. TestProxyCapabilitiesNotCachedUnderIdentityLearnedMidBuild reproduces the identity-registered-mid-build case: it fails on the previous head and passes now.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for addressing this on both the transcode node and the proxy. The key check inside the build lock addresses the reported cache-poisoning race, including the scheduled-refresh case. The regression test provides useful coverage for an identity change during a build.
I haven’t independently verified the commit or test results.
The reason will be displayed to describe this comment to others. Learn more.
Closing a response body during a read can cause a nil dereference
A concurrent Close can set b.watch to nil while Read is blocked, causing a nil dereference when the read resumes. Synchronize access to b.watch and retain a local reference for each read.
Prompt for LLM
File internal/transcodeproxy/liveness.go, lines 200-203:
Closing a response body during a read can cause a nil dereference
A concurrent `Close` sets `b.watch` to nil while `Read` is blocked, so when closing the underlying response body releases the read, `b.watch.timer.Stop()` can dereference nil and crash the process. Synchronize access to the watch and retain a local reference for the duration of each read.
The reason will be displayed to describe this comment to others. Learn more.
No change. Every DoNode caller reads the body and closes it on the same goroutine (playback.go, playback_transport.go, the audiobook HLS nodes, jellycompat streams, and the proxy relay all use defer Body.Close() after reading), and none closes it from a watcher or context.AfterFunc. A scratch test that does close it from another goroutine during a blocked read does hit the nil pointer, so it's a constraint on future callers rather than a reachable crash today. The existing hung-read tests pass under -race.
The reason will be displayed to describe this comment to others. Learn more.
That assessment makes sense: the scratch test confirms the nil dereference is possible with concurrent Read and Close, but the described callers do not currently use the body that way. Given that constraint, I agree the finding should not be classified as a reachable critical bug today.
The passing race tests don’t establish that concurrent close is safe; they only cover the exercised paths. It may be worth documenting the same-goroutine usage constraint near watchedBody or adding a concurrency test if future callers need to close a blocked read.
The reason will be displayed to describe this comment to others. Learn more.
Capability prewarm uses a cache key the web player never reads
The prewarmed capabilities are missed because playerV2Origin normalizes the web player's /api/v2 base URL to an empty string. Seed seedPlaybackCapabilitiesV2 using the same normalized origin as playbackCapabilitiesV2.
Prompt for LLM
File web/src/player/bandwidth-probe.ts, line 79:
Capability prewarm uses a cache key the web player never reads
The web player's `apiBaseUrl` is `/api/v2`, which `playerV2Origin` normalizes to an empty string, so seeding under `/api/v2` never satisfies its subsequent capabilities lookup. Seed under the same normalized origin used by `playbackCapabilitiesV2`.
Suggested code:
seedPlaybackCapabilitiesV2("", cap);
The reason will be displayed to describe this comment to others. Learn more.
Confirmed and fixed in 954bbb1: seedPlaybackCapabilitiesV2 now takes the player config and keys the entry with playerV2Origin, the same function the lookup uses.
The reason will be displayed to describe this comment to others. Learn more.
Probe completion between render and effect can leave playback unsettled
If both probes finish between initialization and the effect, capabilities.settled can remain false indefinitely and block playback startup. Call refresh when the initial state is unsettled rather than rereading the module-level answers.
File web/src/player/hooks/useCodecDetection.ts, line 530:
Probe completion between render and effect can leave playback unsettled
Check whether this hook's initial state is settled rather than rereading the module-level answers. Both probes can finish after the state initializer returns `settled: false` but before this effect runs; in that case, the current condition skips `refresh`, leaving the hook unsettled indefinitely and potentially blocking playback startup. Calling `refresh` when the initial state is unsettled also reuses the completed probe results immediately.
Kody rule violation: [Make browser decoder probes independent, calibrated and time\-bounded](https://kodus.siloserver.org/settings/code-review/1247142351/kody-rules/18adc10a-3371-4616-b14f-c1005e124d5d?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)
The reason will be displayed to describe this comment to others. Learn more.
Confirmed (reproduced with a real root where the probes resolve between the initializer and the effect: still unsettled after 6 s) and fixed in 954bbb1: when the answers are already in, the effect applies them to an unsettled state.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for confirming and reproducing the race. Applying the completed probe answers to an unsettled state in the effect addresses the reported startup hang.
The reason will be displayed to describe this comment to others. Learn more.
Playback can remain unsettled when probes finish before the effect
If both probes finish between initialization and the effect, settled stays false and usePlaybackSession can wait indefinitely. Call refresh whenever the initialized state was unsettled.
Prompt for LLM
File web/src/player/hooks/useCodecDetection.ts, lines 530-532:
Playback can remain unsettled when probes finish before the effect
If both prewarm probes resolve after the state initializer but before this effect runs, the initializer leaves `settled` false and the effect skips `refresh`, so `usePlaybackSession` waits indefinitely to start playback. Track whether the initialized state is settled or always attach the refresh when the initial state was unsettled.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update. This is the same defect as in the earlier thread, and you’ve noted that it was fixed in commit 954bbb1bc1. I haven’t independently verified the fix.
A connected file switch can leave missed marker changes stale until another reconnect. Restrict the initialConnectedKeyRef.current skip to the first connection.
Prompt for LLM
File web/src/player/hooks/useMarkerChangeGuard.ts, lines 76-82:
File switches incorrectly skip marker reconciliation
When the active file changes while connected, the new session-file key differs and an existing version causes this branch to skip reconciliation again, despite the file-switch contract. Marker changes missed before the switch remain stale until another reconnect; restrict the skip to the first connection only.
The reason will be displayed to describe this comment to others. Learn more.
Independently tested 90e782e2ee against a55887d319 in isolated sandboxes.
Software HDR admission fell from 2,378 to 740 ms warm on a single node and from 2,456 to 760 ms through the worker and proxy (12 trials per revision). The distributed HDR playlist shrank from 148,391 to 9,886 bytes with exact Content-Length and matching identity fallback. Median transfer on the local link did not improve. The owning profile got HTTP 206 and a second valid profile on the same account got 403 on both revisions.
Chromium Play to first rendered frame fell from 455 to 366 ms with a fresh document (6 trials each) and from 232 to 95 ms warm (12 each).
I reproduced the marker issue in the existing inline thread. Switch between two known files while the socket stays connected. The base reads watch detail for the new file once. The PR makes zero reads, leaving markers stale until another event or reconnect.
The playback timing covers software encoding. QSV, VAAPI, and migration of an active stream between workers remain unverified.
AI-assisted validation · Codex (gpt-6.2-sol, xhigh) in T3 Code.
The reason will be displayed to describe this comment to others. Learn more.
Seed capabilities under the player's normalized origin
In the web app, PlayerConfig.apiBaseUrl is /api/v2, but playerV2Origin() strips that suffix, so playbackCapabilitiesV2() reads the cache under "". This call instead seeds /api/v2, and the seeding helper only removes trailing slashes. Consequently, playback never uses the prewarmed entry and still waits for another capabilities request, including its five-second timeout if the server is slow. Pass the normalized origin or normalize the seed key identically to the reader.
The shared node capability fetch ran on the first caller's context, so a planning lookup's short deadline or a disconnect failed the transport-time lookups that joined it. It now runs detached, bounded by the node's own probe budget, and a panic inside it becomes an error.
A replayed start answers from its stored attempt as soon as that lookup returns instead of waiting on the file, settings, and device reads. The lifecycle row is written before the 201 again, so a pause confirmed right after the response finds it. A failed downloaded-subtitle read is no longer cached for the rest of the start.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-described inputs wide
A fresh generation encodes the whole title, so the fast-start x264 settings now keep only the lookahead and threading changes. Turning off B-frames, adaptive quantization, and partition analysis, and scaling with fast_bilinear, cost quality for the whole session with no startup gain on a 1080p source.
MPEG transport and program streams, and inputs a node reads through its relay URL, keep the 3 s / 5 MB input probe. Segment waits poll every 10 ms again, since the interval applies for the whole session, and audio-only remuxes keep 2-second fragments.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… describes
A snapshot was stored under the configuration and node identity read after the build, so a change during a build cached the old report as current until the next 15-minute refresh. It is now stored under the key read before the build, only while that key is still current, and inside the build lock so a scheduled refresh cannot overwrite a newer re-probe. A transcode node whose configured hardware did not verify serves that snapshot for 15 seconds, so a transient GPU failure clears.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
WriteHLSManifest used its own Accept-Encoding parser, which disagreed with the API's response compressor on x-gzip, identity weights, malformed weights, and repeated field lines. It now uses the compressor's rules through httpstream.AcceptsGzip. The worker protocol notes describe gzip playlists and the relay upgrade order.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…er's key
When the prewarmed probes finished between the hook's first render and its effect, codec detection stayed unsettled and playback never started. The effect now applies answers that are already in. The bandwidth probe seeded playback capabilities under /api/v2 while the player reads them under the bare origin, so the seed never hit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
Unsettled snapshots do not shorten an already scheduled refresh
Recovered hardware can remain absent from the advertised hash for nearly 15 minutes after an endpoint request or manual re-probe. Wake and reset the scheduler when a newly stored snapshot becomes unsettled.
Prompt for LLM
File internal/transcodenode/server.go, line 1770:
Unsettled snapshots do not shorten an already scheduled refresh
An unsettled snapshot created by an endpoint request or manual re-probe does not reschedule an already armed 15-minute timer, so recovered hardware can remain absent from the advertised hash for nearly 15 minutes instead of one minute. Wake and reset the scheduler when a newly stored snapshot becomes unsettled.
The decoder prewarm now waits on scheduleWhenIdle, which the test's routeChunkPrefetch mock lacked, so the app fell into its error screen at boot. The mock never runs the task, keeping the probe out of the requests the test counts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On sandboxes (no GPU), the startup gains held after the fixes: an HDR10 software tone-map transcode starts in 871 ms against 2,611 ms on main, and a forced 480p transcode in 287 ms against 477 ms. Evidence: https://evidence.siloserver.org/r/silo-server/pr-5849/
The gzip playlists don't affect the Apple app. It plays server HLS through AVPlayer, and the pinned engine reached first frame the same way against main and this branch.
Left for the maintainers
Startup cushion for CPU encodes. Every fresh generation now waits for one segment, which is where most of the software-transcode gain comes from. On an encode near real time, such as a 4K Dolby Vision tone-map with burned-in subtitles, segments 1 and 2 then arrived 1.1–1.8 s after the start, against a few milliseconds on main. Options: keep one segment, use two for CPU encodes, or restore the old values. I'd use two for CPU encodes.
Scope. The branch spans five independent areas: tone-map and Dolby Vision probing; access and /stream; encoder and probe settings; node and proxy transport; and the web player. CONTRIBUTING asks for one concern per pull request. Splitting it would make each part reviewable and revertable on its own.
NVENC -preset p2 now applies to every live encode, a small quality cost the PR doesn't measure.
Not checked here: CPU decode is capped at four threads for the whole session (a possible throughput cost for 4K software decodes on slow many-core hosts); the 0.08 s audio pre-buffer in the browser engine; and QSV, VAAPI, and NVENC on real hardware.
Validated features
Validation tasks: changes #1172 C1, C2, C3; #1177 C1, C3; #1156 C1. No passed case regressed in the trace.
Hardware transcoding — NVENC #1172 (hardware tone mapping) changes through the encoder flags, the render-device filter, and the one-segment start.
The first-connect marker change that touched #1149 C1 was reverted. Re-checking hardware HDR tone mapping and multi-node failover after merge is worthwhile, since this review had no GPU.
Other checks
User manual: unaffected. No setting, label, or default changes, and the playback pages already allow a device list and say previews show once they've loaded.
Fit is 7 because the work serves a core goal (faster playback start) but stretches the one-concern rule and trades some encode quality for startup time. Readiness is 7 because the defects found are fixed and the gains were shown live. The cushion decision and the hardware paths are still open.
The direct-stream fast path treats a copied session as sufficient to serve after an earlier negative deny result. If a concurrent stop removes the live session before the base implementation would have re-read it, the base can refuse the request, but the new path can still serve the copied route. BeginTransport returns not found in that state, yet the caller proceeds to serve bytes. The exposure is a request from an authenticated session owner that was already underway, not a demonstrated cross-account bypass. Preserve the parallel lookup, but make transport admission verify that the live session and its route still match before serving.
1
The new process-wide worker MAC cache retains the raw worker secret as a map key and the derived MAC key as its value. It clears on cache pressure, not on credential rotation or expiry, so a quiet process can retain retired credentials until it exits. The added exposure requires access to that process's memory and is limited to credentials it has used. Signing and verification still select the current secret; the cache does not itself keep retired credentials valid on the wire. Bind cached key material to the active credential lifecycle.
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: 1597a779-9c91-4219-8552-8468a406892b
Commits
Reviewing files that changed from the base of the PR and between 4ad553a and e96c17c.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Stability & Availability · Quick win
A capability report overtaken by an invalidation can be cached for ten minutes.
fetchRemoteCapabilitiesOnceV3 checks the invalidation counter at line 784, then stores the result at line 829. An invalidation that runs between those points bumps the counter, but it finds no cached entry to delete and starts no refresh. The stale report is then stored with the 10-minute TTL. Lookups return it until it expires, so a node whose hardware changed can keep receiving transcode plans for that period. The window is narrow. It needs an invalidation during the probe's completion and lock acquisition.
Recheck the counter under the lock before storing the entry:
Suggested fix
var (
info playback.HWAccelInfo
err error
completedAt time.Time
overtaken bool
+ snapshot uint64
)
for attempt := range v3CapabilityFetchAttempts {
// Snapshot the invalidation count before probing: anything this fetch
// learns describes the node as it was when the request left.
- invalidations := h.nodeCapabilityInvalidationsV3(nodeURL)+ snapshot = h.nodeCapabilityInvalidationsV3(nodeURL)
requestCtx, cancel := context.WithTimeout(ctx, h.remoteToneMapProbeTimeoutV3(nodeURL))
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Quick win
Cache collisions can return another seek's stream origin.
seekMillis rounds the requested seek to whole milliseconds. FFmpeg receives the seek formatted with a different rule. 1000.5625 and 1000.563 both produce seekMillis=1000563, but FFmpeg receives -ss 1000.562 and -ss 1000.563. When a keyframe lies between those two positions, the probes return different anchors. The second request then receives the first request's cached origin, while its transport seeks to its own position. Before this change, the six-decimal singleflight key kept these probes separate.
Key the cache on the same formatted seek string passed to -ss. Each cache entry then matches the seek that FFmpeg performs. Replace the seekMillis field in cacheKey with that string. Do not add a second rounding rule.
Re-check the requested session's denial after the concurrent reads.
denied := sessionIDDenied reuses a Denied(sessionID) result that ran before the login-session and grant lookups finished. If those lookups take longer than the deny-cache freshness window, a stop recorded during the wait is missed. The later checks skip the requested ID, so the request reaches direct-play delivery, which performs no further deny check. A stopped session can then receive media.
Re-check the requested session after the waits. A stop during the wait then returns 410. Requests without a stop are unchanged. A negative cache entry written during the request still answers within its TTL, as it does today.
Proposed fix
--- "a/internal/proxy/mediagrant.go"+++ "b/internal/proxy/mediagrant.go"@@ -155,7 +155,7 @@
// The grant outlives the session it describes, so the deny marker is what
// stops a stopped, expired, or terminated session from serving here. Keep
// the JSON error shape the rest of this route family answers with.
- denied := sessionIDDenied+ denied := sessionIDDenied || (s.streamDeny != nil && s.streamDeny.Denied(r.Context(), sessionID))
if !denied && s.streamDeny != nil {
grantClaims := card.ToClaims()
if grantClaims.SessionID != "" && grantClaims.SessionID != sessionID && s.streamDeny.Denied(r.Context(), grantClaims.SessionID) {
Committable suggestion
IMPORTANT
Review the replacement and indentation, then test before committing.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Data Integrity & Integration · Quick win
Do not return success when snapshot publication is refused.
If node registration completes during the rebuild, storeCapabilitySnapshotLocked rejects the captured key and preserves the previous health hash. The handler still returns HTTP 200 with the rebuilt hash, although CapabilityHash promises the published snapshot.
Make the helper report whether it published the snapshot. If publication fails, return a retryable error instead of an unpublished hash. Keep the current success response when the key remains unchanged.
The reason will be displayed to describe this comment to others. Learn more.
Major · Stability & Availability · Quick win
Align tone-map device allocation with the probe.
With explicit QSV and an empty VerifiedHWDevices cache, local planning can advertise tone mapping from an openable device while allocation selects a different, inaccessible device. If the configured order is renderD129, renderD130, renderD128 and only renderD128 is openable, startup can fail on the first two devices without reaching the working device when software tone mapping is disabled.
Restrict hardware tone-map allocation to the accessible devices used by the probe, while retaining the existing verified-device filtering.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Quick win
Clear playback when Back interrupts the first watch route.
If the viewer presses Back while WatchRoute is still loading, its exit effect has not been installed. The early foreground request can remain active, so the preparing screen or player covers the previous page.
Clear the abandoned request when navigation leaves before the route mounts. Preserve successful starts and detached playback.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Quick win
Startup can play into an audible gap when the next audio chunk is late.
With the threshold at 0.08 s, the page treats audio as ready after four 20 ms chunks. Playback then starts from that queue. If the next chunk arrives after the queued audio ends, the worklet outputs silence and posts underrun. Playback resumes as soon as the next chunk arrives. The earlier 0.25 s threshold provided a larger startup cushion. Choose the startup cushion, or require the page to buffer again after an underrun, before merging.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Quick win
Stale HDR10 answers can outlive a superseded output-change probe.
refresh discards superseded results for the mounted hook. probeHDR10PlaybackSupport writes initialHDR10Answer before that check runs. If two output-change probes overlap and the older one resolves last, its answer becomes the cached answer. The mounted hook stays correct. A later mount reads the cache as settled and does not reprobe, so it can advertise the stale hdr10_max_frame_rate until the next output change. This applies only when the browser returns different answers for the overlapping probes.
Publish the cached HDR10 answer under the same generation check that guards the hook state. Remove the unconditional cache writes from probeHDR10PlaybackSupport. Keep the prewarm path writing the cache, and write from a refresh only while that refresh is current.
A heavy CPU encode (4K tone mapping, bitmap burn-in) runs close to real time. With a one-segment lead, playback started sooner but then stalled on the next segments. Fresh hardware encodes keep the one-segment lead. The check reads the actual video encoder, so a GPU tone map feeding a CPU encoder counts as CPU.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A lookup that ends because its caller went away says nothing about the marker, so it is no longer cached. Real Redis errors and timeouts still fail open and are cached as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…red fetch
A caller that missed the cache while another caller's fetch was finishing would start a second node probe. The shared fetch now checks the cache before probing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…early
A replayed start, or a failed attempt lookup, left the file and planner-settings reads running and holding database connections. Both now run on a context that those early returns cancel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments
1
Playback admission now uses policy captured by ViewerAccess for the same account, rather than rereading account and group policy at admission. If an administrator lowers a limit or disables transcoding after ViewerAccess has resolved the request but before the SessionManager admits it, the request can still acquire a slot under the old policy. Live counts are still checked, but against the old limits; requests without a matching snapshot still take the fresh-read path. Revalidate the policy at the state-changing admission check if tightening must take effect before the next session is admitted.
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: 1debc2e2-7860-44b1-bf74-c4d50a24ade0
Commits
Reviewing files that changed from the base of the PR and between e96c17c and 8675e3f.
Files selected for processing: 5
internal/api/handlers/playback_v3.go
internal/playback/streamdeny.go
internal/playback/streamdeny_test.go
internal/playback/transcode.go
internal/playback/transcode_manifest_test.go
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.
…n the probe will
- A build that a configuration or identity change superseded is no longer returned by /hw-capabilities. The endpoint builds once more for the new configuration, and answers 503 if that one is superseded too. A re-probe answers 503.
- The scheduled refresh looks every minute. It rebuilds a missing or unsettled snapshot whichever path stored it, and a settled one every 15 minutes, so an unsettled report published between ticks is not left standing.
- A snapshot expires when the tone-map probe will retry part of its inventory, such as a Dolby Vision smoke that failed for a passing reason.
- An explicit backend the host has no device for counts as settled, since nothing there can recover, so that node no longer re-probes every minute.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
Unsettled snapshots repeatedly launch FFmpeg before their retry deadline
A transient Dolby Vision failure causes repeated FFmpeg transformation probes while the tone-map result remains cached. Rebuild an unsettled snapshot only when now reaches expiresAt.
Prompt for LLM
File internal/transcodenode/server.go, lines 1832-1834:
Unsettled snapshots repeatedly launch FFmpeg before their retry deadline
A transient Dolby Vision failure sets `expiresAt` five minutes ahead, but this condition rebuilds the snapshot every minute before that deadline, and each rebuild launches multiple FFmpeg transformation probes while the tone-map result is still cached. Check whether `now` has reached `expiresAt` before rebuilding an unsettled snapshot.
Suggested code:
if snap == nil {
return true
}
if !snap.expiresAt.IsZero() {
return !now.Before(snap.expiresAt)
}
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments
1
The proxy's header-authenticated direct route can start serving an already-in-flight request after a playback stop that the old ordering could have seen. The head starts the playback-session deny lookup alongside the login and grant checks, then consumes that earlier result. If the marker becomes visible during those checks, the base's later lookup can refuse on a cache miss, but the head does not recheck the same session ID. A later lookup runs only for a distinct session or transport ID on the grant. Login validity, ownership, and route checks still apply; the regression is in playback-stop timing, not account isolation.
1
The proxy can finish a segment response while the transcode node still has not recorded delivery. The protocol already allowed acknowledgment failure, but the base waited for the attempt before the proxy handler returned. Now even a normally delivered acknowledgment can arrive after the next output-bound check. That check can mistake stale progress for encoder lead, allowing the API to persist a learned bandwidth limit for a stall actually caused by the encoder. A later acknowledgment advances progress but does not undo a limit already recorded.
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: 622b5d11-223b-43a8-8bbe-a639fec17a7c
Commits
Reviewing files that changed from the base of the PR and between 8675e3f and cb3496f.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.
…d listed backend as unsettled
- An unsettled build that repeats the same answer now waits 1, 2, 4, 8, then 15 minutes for its scheduled rebuild. A backend this FFmpeg cannot tone map on no longer re-probes every minute for as long as the node runs.
- A missing snapshot, or one built for another configuration, is due at once.
- Detection lists only backends whose hardware is present, so a listed backend that did not verify counts as unsettled even with no device list. That covers NVENC and VideoToolbox.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rt return
The direct-state read now runs on the context a replay or failed attempt lookup cancels, and its result is recorded on the request, and kept for a key retry, only on the path that uses it. A read cancelled this way no longer logs a warning, and neither does the viewer-limits read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fit: 7/10 · Readiness: 8/10 — conditional (assuming CI is green)
What changed since the last summary
Startup cushion. Fresh CPU encodes now start on two segments, and hardware encodes on one. On the sandboxes, an HDR10 software tone-map start takes 1,420 ms against 2,698 ms on main (it was 871 ms on one segment). The stall right after the first frame is gone: segments 2 and 3 arrive while the player is still on segment 0.
QSV, on an Intel Arc GPU with OpenCL tone mapping.
HDR10 tone-map starts go from 2,100 to 1,634 ms, and Dolby Vision from 2,002 to 1,363 ms.
A 1080p SDR QSV start showed no measurable change: about 0.8 s on main and 1.0 s here, with both varying between 0.4 and 2.2 s. So the 6.6 s → 0.77 s figure in the description didn't reproduce, since main already starts that case in about 0.8 s.
Timing FFmpeg alone, the low-latency QSV flags cost nothing measurable.
Council round 3 found capability-snapshot and start-path edge cases. All are fixed in cb3496fc92 through 1a48766e17:
A build superseded by a configuration change is no longer served.
A node rebuilds an unsettled or missing snapshot within a minute, and backs off one that keeps repeating.
A snapshot follows the tone-map probe's own retry.
The speculative start reads stop when a start returns early.
A replay seen before transport commit is left as is, since main has the same order.
Scope. The branch still spans five areas (tone-map and Dolby Vision probing, access and /stream, encoder and probe settings, node transport, and the web player), against CONTRIBUTING's one concern per pull request.
Not checked here: VAAPI and NVENC, and NVENC's -preset p2 quality cost.
Council
Member
Round 1
Round 2
Round 3
Sol (gpt-6.2-sol, medium)
5/10
7/10
7.5/10
Opus (claude-opus-5-5, medium)
5/10
8/10
8/10
Gemini (gemini-4-neon, medium)
6.5/10
8.5/10
8.5/10
Readiness is 8: every finding is fixed and the gains held on CPU and on QSV. The round-3 fixes haven't had a council round of their own. Fit stays 7 because of the scope.
The documented relay-first upgrade order is required to preserve manifest framing. The base origin sent an identity response with a known length. With a new Transcode node behind an old pass-through relay, Go can add gzip upstream, transparently decode the reply, and drop its length. A length-sensitive player can then reject or misread the playlist. Updated relays explicitly set the upstream encoding before fetching a playlist, but the new writer does not require that the request came from an updated relay. Operators must avoid that version pairing on upgrade and rollback, or keep the origin on identity until relay support is verified.
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: d4eb21e7-8d59-426b-bc7a-55507e7957cc
Commits
Reviewing files that changed from the base of the PR and between cb3496f and 1a48766.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Major · Stability & Availability · Quick win
Hardware playback can select an inaccessible first device.
The probe tests only accessible devices (internal/tonemap/probe.go:483, internal/tonemap/dri_access.go:27-38), then advertises the hardware backend. Playback does not use that accessible subset. It sends the raw configured value to the source preflight (internal/playback/transcode.go:1171). The preflight takes the first comma-separated entry with firstDevice (internal/tonemap/preflight.go:684, internal/tonemap/probe.go:988-992).
With hw_device set to /dev/dri/renderD128,/dev/dri/renderD129 and only renderD129 openable, the advertised capability is valid for renderD129. Playback can still select renderD128. The preflight then fails for that session. If the failure does not fall back to software, playback fails.
The device used for playback must be an accessible device that the probe validated. Apply the same access filter when playback chooses its device, so it does not use the first raw entry. Choose the mechanism that keeps the probe and playback on the same device list.
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
enhancementNew feature or requestimpact: perfUnusable slowness on normal hardwareneeds-reviewNeeds maintainer review to resolve uncertain classification, scope, or changed evidence.priority: P2Limited scope, workaround exists, or polishsize/XXXL3000+ added + deleted lines (all files); change volume, not priority.
1 participant
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: changes #1172 C1, C2, C3; #1177 C1, C3; #1156 C1
Other clients: Apple Silo-Server/silo-apple#1360 (engine: Silo-Server/AetherEngine#31); Android Silo-Server/silo-android#1135; Roku Silo-Server/silo-roku#129; Web (this PR)
Direct play, remux, and transcode playback startup paid avoidable serial latency across the server, distributed nodes, and web player:
hw_devicelist named a render node absent on the local host (for examplerenderD128,renderD129on a host exposing onlyrenderD128),tonemap.Probefailed every smoke test on the missing node, discarded the working node's capabilities, cached a negative result, and re-ran ~6 s of FFmpeg probes on every playback start, even for SDR sources that never tone-map./api/v2/playback/startran a synchronousffprobebitstream check for Dolby Vision Profile 8 RPU stripping (~1.4 s over network storage) even when the client already supported direct play without stripping./streamran live session deny check and media file lookup serially; transcode/proxy nodes re-probed hardware capabilities on refreshes, sent uncompressed multi-thousand-segment HLS manifests, and waited with coarse polling intervals for initial segments and completion signals.Approach
Server and distributed nodes
internal/tonemap/,internal/api/handlers/playback_v3.go,internal/playback/transformations_v3.go): Filter cluster-wide QSV/VAAPI DRM device lists to nodes openable by the local process (probeDevicesForHost), skiptonemap.Probeon SDR sources when tone-mapping cannot be needed, and add unit coverage ininternal/tonemap/probe_test.go.internal/playback/transcode.go,remux.go,copy_seek_anchor.go,candidate_video_v3.go): Add Intel QSV low-latency flags (-async_depth 1 -bf 0, plus-look_ahead 0for H.264) and NVENC-preset p2for live encodes, give fresh software H.264 starts x264's latency settings only (sync-lookahead=0:rc-lookahead=0:sliced-threads=1), use a 500 KB / 0.5 s input probe for Matroska and MP4 while MPEG-TS/PS files and node relay inputs keep 3 s / 5 MB, flush progressive fMP4 every 500 ms (2 s for audio-only), start every fresh generation after one segment, defer Dolby Vision RPU strip probing until a route actually needs stripping, and trim copy-seek anchor overhead.internal/access/,internal/policy/,internal/api/middleware/viewer_access.go,internal/api/router.go,internal/apiv2/gates.go,internal/api/handlers/stream*.go,internal/playback/planstore/postgres.go): Overlap independent account/policy and user-store reads, reuse the resolved account policy in session admission limits, skip browsing-only viewer preferences on media delivery routes, and overlap Redis deny checks with media file lookups on live in-memory sessions.internal/playback/manifest_http.go,internal/transcodenode/,internal/proxy/,internal/transcodeproxy/,internal/nodeauth/,internal/nodecontrol/,internal/nodepool/): Cache transcode-node and proxy capability snapshots keyed by the configuration and identity read before the build (a snapshot whose configured hardware or tone-map probe didn't settle is served for 15 s and rebuilt within a minute), gzip HLS playlists of 1 KiB or more in memory with an exactContent-LengthwhenAccept-Encodingadmits it by the API compressor's rules (WriteHLSManifest,httpstream.AcceptsGzip), tighten liveness polling, and speed up proxy media-grant/reprobe handoffs.Web player
useDeferredWatchTrickplay).ActionBar), warm the watch route chunks after sign-in, probe the browser decoder after sign-in when idle (App), avoid chapter refetches whenchaptersis explicitly[], parallelize codec capability checks (useCodecDetection,engine/capabilities.ts), and seed the playback capability cache from the bandwidth probe (start-v2.ts,bandwidth-probe.ts).Validation
Go race unit tests across all 18 modified packages (
umask 0022 && go test -race -count=1 ./internal/access/... ./internal/api/handlers/... ./internal/api/middleware/... ./internal/apiv2/... ./internal/nodeauth/... ./internal/nodecontrol/... ./internal/nodepool/... ./internal/playback/... ./internal/policy/... ./internal/proxy/... ./internal/tonemap/... ./internal/transcodenode/... ./internal/transcodeproxy/...): all passed.Go linters and repository contracts (
make lint-changed,make lint-router-recovery,make verify-size-ratchet verify-route-inventory verify-fork-pins verify-settings-bindings-all verify-playback-fixtures verify-local-paths verify-case-collisions verify-bidi,go test -count=1 -run '^TestCommittedArtifactMatchesRouter$' ./internal/apiv2/): all passed (0 issues).Web checks (
pnpm run lint,pnpm run format:check,pnpm run build,pnpm run budget:check,pnpm exec vitest run src/player/ src/pages/audiobooks/player/useAudiobookPlayback.test.ts): all passed (45/45 player test files, 849/849 tests; 23/23 audiobook tests).Review fixes (head
e96c17c3ad):make lint-changedandmake lint-router-recovery0 issues; size ratchet, route inventory, local paths, bidi, andTestCommittedArtifactMatchesRouterpassed;go test -raceonhttpstream,tonemap,transcodenode,proxy,transcodeproxyandgo testonplaybackandapi/handlerspassed; webtsc -b, ESLint, Prettier, and the player, playback, item-detail, audiobook-player, and boot tests passed.Round-3 and round-4 fixes (head
1a48766e17):make lint-changed0 issues; size ratchet passed;go test -raceontranscodenode,tonemap,proxy, and the handler capability, start, replay and direct-state tests passed; focusedplaybacktests passed.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-5849/
On sandboxes with software encoding, median
POST /api/v2/playback/startover 8 warm runs went from 2,698 to 1,420 ms for an HDR10 software tone-map transcode, and from 472 to 350 ms for a forced 1080p→480p transcode, with fresh CPU encodes starting on two segments. On an Intel Arc GPU with QSV and OpenCL tone mapping, HDR10 and Dolby Vision tone-map starts went from about 2.0–2.1 s to 1.4–1.6 s. A 1080p SDR QSV transcode showed no measurable change: about 0.8 s on main and 1.0 s here, both varying between 0.4 and 2.2 s. Gzipped playlists match the identity body byte for byte. The page also has the x264 quality comparison, the Apple HLS check against gzipped playlists, and the input-probe sweep over the release fixtures.The author's measurements, on commit
90e782e2eevia automated test/contract gates and live server playback measurements:/api/v2/playback/start): dropped from 6,581 ms to 774 ms (all 6 hardware HDR tone-map kinds probed and cached on the accessible DRM render node; SDR playback no longer triggers tone-map probing)./api/v2/playback/start): dropped from 1,462 ms to 23 ms after deferring the synchronous RPU strip probe when direct play is already selected.Content-Lengthand shrink multi-thousand-segment VOD playlists by ~20x on the wire (TestWriteHLSManifestGzipAndIdentity).The QSV figure didn't reproduce in review: on the Arc host, main already starts that case in about 0.8 s.
Risks
-bf 0) and lookahead (-look_ahead 0) on Intel QSV trades a small amount of compression efficiency for lower initial-segment latency during live/VOD transcoding.RequireMediaViewerAccessomits browsing-only preferences (Next Up, card overlays, metadata language, disabled library browse filters) on stream-reference media delivery routes; authorization, profile verification, and session ownership checks remain identical.-preset p2, faster and slightly lower quality than the defaultp4.#1172 C1, C2, C3and#1177 C1, C3; re-checking hardware HDR tone-mapping and multi-node failover after merge is recommended. Review ran QSV on an Intel Arc GPU; VAAPI and NVENC were not exercised.Checklist
Council review
Rounds: 3, last reviewed
8675e3fc23(round-3 fixes incb3496fc92through1a48766e17)Visual review: not run; nothing changes on screen.
Fixed in rounds 1 and 2:
Fixed in round 3:
Answered:
Closerace: no caller closes concurrently.AI Disclosure
Note
Cut stream startup latency across direct-play, remux, and transcode paths
PlaybackHandler.startPlaybackApplicationV3overlaps attempt lookup, state resolution, file loading, and settings reads; replayed attempts return without waiting for other reads (playback_v3.go)playback.WriteHLSManifest, used by handlers and relays (manifest_http.go)buildFFmpegArgs,buildRemuxArgsWithLeadingPictureDropV3, andstartupSegmentRequirementagainst existing players; capability snapshot expiry (15s unsettled TTL) and identity-keyed reports may change/hwcapabilitiesresponses after re-probeMacroscope summarized cb3496f.