diff --git a/docs/architecture/worker-http-protocol.md b/docs/architecture/worker-http-protocol.md index d7a38d89870..c2eb007e44d 100644 --- a/docs/architecture/worker-http-protocol.md +++ b/docs/architecture/worker-http-protocol.md @@ -628,6 +628,18 @@ the node with GET; it rewrites a playlist it re-tokenizes and recomputes its `Content-Length`. Segment routes take GET only, and remux HEAD is still forwarded as HEAD. +Playlists of 1 KiB or more are gzipped when the request's `Accept-Encoding` +admits gzip (negotiated as the API's response compressor negotiates), with +`Content-Encoding: gzip`, `Vary: Accept-Encoding`, and a `Content-Length` that +counts the encoded bytes; otherwise they go out as identity with their exact +length. Every writer (the API manifest route, the API relay's rewrite, and the +node) holds the whole playlist, so a playlist never goes out chunked. Relays +pass the viewer's preference upstream (`gzip` or `identity`) instead of letting +Go's transport add its own, because a transport that adds `gzip` itself also +decodes the answer and drops its length. The rewrite asks the node for +identity, since it reads the body. A proxy or API relay older than its node +still lets Go's transport add `gzip`, so upgrade relays before nodes. + The proxy `/stream/v3` family remains a separate header-authenticated protocol. Each request requires an access JWT, a live login session and a stored grant owned by the same account, plus the committed egress and endpoint family. API keys, diff --git a/internal/access/context.go b/internal/access/context.go index a464b740904..a2387df8c15 100644 --- a/internal/access/context.go +++ b/internal/access/context.go @@ -4,7 +4,10 @@ import "context" type contextKey string -const scopeKey contextKey = "access_scope" +const ( + scopeKey contextKey = "access_scope" + resolvedPolicyKey contextKey = "access_resolved_user_policy" +) // SetScope stores a resolved access scope in context. func SetScope(ctx context.Context, scope Scope) context.Context { @@ -16,3 +19,18 @@ func GetScope(ctx context.Context) (Scope, bool) { scope, ok := ctx.Value(scopeKey).(Scope) return scope, ok } + +// SetResolvedUserPolicy stores the request's resolved account policy in context. +func SetResolvedUserPolicy(ctx context.Context, policy ResolvedUserPolicy) context.Context { + return context.WithValue(ctx, resolvedPolicyKey, policy) +} + +// GetResolvedUserPolicy retrieves the request's resolved account policy for +// userID if viewer access resolution already loaded it on this request. +func GetResolvedUserPolicy(ctx context.Context, userID int) (EffectiveUserPolicy, bool) { + resolved, ok := ctx.Value(resolvedPolicyKey).(ResolvedUserPolicy) + if !ok || !resolved.Resolved || resolved.UserID != userID { + return EffectiveUserPolicy{}, false + } + return resolved.Policy, true +} diff --git a/internal/access/resolver.go b/internal/access/resolver.go index 3345adee42f..8d67c209c9c 100644 --- a/internal/access/resolver.go +++ b/internal/access/resolver.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "sort" + "sync" "github.com/Silo-Server/silo-server/internal/models" "github.com/Silo-Server/silo-server/internal/settingsresolve" @@ -76,15 +77,79 @@ func NewResolver(users UserRepository, storeFactory userstore.UserStoreProvider, // Resolve computes the effective viewer scope for the request. func (r *Resolver) Resolve(ctx context.Context, input ResolveInput) (Scope, error) { - user, err := r.users.GetByID(ctx, input.UserID) - if err != nil { - return Scope{}, fmt.Errorf("loading user %d: %w", input.UserID, err) + // Overlap independent account/policy reads with user-store/profile/preference + // reads while preserving exact error precedence. + var ( + user *models.User + userErr error + effective EffectiveUserPolicy + effectiveErr error + allowUnrated bool + store userstore.UserStore + storeErr error + preferences ViewerPreferences + profile *userstore.Profile + profileErr error + outer sync.WaitGroup + ) + outer.Add(1) + go func() { + defer outer.Done() + user, userErr = r.users.GetByID(ctx, input.UserID) + if userErr != nil { + return + } + effective, effectiveErr = EffectivePolicyForUser(ctx, user, r.groups) + }() + if r.unrated != nil { + outer.Add(1) + go func() { + defer outer.Done() + allowUnrated = r.unrated.AllowUnratedContent(ctx) + }() + } + if r.storeFactory != nil { + outer.Add(1) + go func() { + defer outer.Done() + store, storeErr = r.storeFactory.ForUser(ctx, input.UserID) + if storeErr != nil || store == nil { + return + } + var inner sync.WaitGroup + if !input.SkipViewerPreferences { + inner.Add(1) + go func() { + defer inner.Done() + preferences = ResolveViewerPreferences(ctx, store, r.defaults, input.ProfileID) + }() + } + if input.ProfileID != "" { + inner.Add(1) + go func() { + defer inner.Done() + profile, profileErr = store.GetProfile(ctx, input.ProfileID) + }() + } + inner.Wait() + }() } - effective, err := EffectivePolicyForUser(ctx, user, r.groups) - if err != nil { - return Scope{}, fmt.Errorf("loading access group policy for user %d: %w", input.UserID, err) + outer.Wait() + + if userErr != nil { + return Scope{}, fmt.Errorf("loading user %d: %w", input.UserID, userErr) + } + if effectiveErr != nil { + return Scope{}, fmt.Errorf("loading access group policy for user %d: %w", input.UserID, effectiveErr) } + if input.EffectivePolicyOut != nil { + *input.EffectivePolicyOut = ResolvedUserPolicy{ + UserID: user.ID, + Policy: effective, + Resolved: true, + } + } scope := Scope{ UserID: user.ID, ProfileID: input.ProfileID, @@ -95,22 +160,16 @@ func (r *Resolver) Resolve(ctx context.Context, input ResolveInput) (Scope, erro MaxLocalStreamBitrateKbps: effective.MaxLocalStreamBitrateKbps, PolicyRevision: user.AccessPolicyRevision, ProfileVerified: input.ProfileID == "", - } - if r.unrated != nil { - scope.AllowUnratedContent = r.unrated.AllowUnratedContent(ctx) + AllowUnratedContent: allowUnrated, } - store, err := r.storeFactory.ForUser(ctx, input.UserID) - if err != nil { - return Scope{}, fmt.Errorf("opening user store for %d: %w", input.UserID, err) + if storeErr != nil { + return Scope{}, fmt.Errorf("opening user store for %d: %w", input.UserID, storeErr) } - preferences := ResolveViewerPreferences(ctx, store, r.defaults, input.ProfileID) - var profile *userstore.Profile if input.ProfileID != "" { - profile, err = store.GetProfile(ctx, input.ProfileID) - if err != nil { - return Scope{}, fmt.Errorf("loading profile %s: %w", input.ProfileID, err) + if profileErr != nil { + return Scope{}, fmt.Errorf("loading profile %s: %w", input.ProfileID, profileErr) } if profile == nil { return Scope{}, ErrProfileNotFound diff --git a/internal/access/types.go b/internal/access/types.go index 05377ce9aaf..53ed057e60b 100644 --- a/internal/access/types.go +++ b/internal/access/types.go @@ -164,6 +164,22 @@ type ResolveInput struct { // Reading another profile's shared personal collection uses it: the // owner's browsing preference does not limit what the collection shows. ContentAccessOnly bool + // SkipViewerPreferences omits browsing-only viewer preferences (Next Up, + // card availability, metadata language, disabled library filters) on + // routes that only serve bytes for an already-authorized playback session. + SkipViewerPreferences bool + // EffectivePolicyOut, when non-nil, receives the resolved EffectiveUserPolicy + // so downstream request handlers (e.g. playback admission limits) can reuse + // it without repeating the user and access-group DB queries. + EffectivePolicyOut *ResolvedUserPolicy +} + +// ResolvedUserPolicy carries the account-level EffectiveUserPolicy computed +// during viewer access resolution for reuse within the same request. +type ResolvedUserPolicy struct { + UserID int + Policy EffectiveUserPolicy + Resolved bool } // ProfileTokenClaims are the claims embedded in a verified profile token. diff --git a/internal/api/handlers/playback.go b/internal/api/handlers/playback.go index ee29c8ad6ad..7bccb66a0d5 100644 --- a/internal/api/handlers/playback.go +++ b/internal/api/handlers/playback.go @@ -19,6 +19,7 @@ import ( "github.com/go-chi/chi/v5" "github.com/google/uuid" + "golang.org/x/sync/singleflight" apimw "github.com/Silo-Server/silo-server/internal/api/middleware" "github.com/Silo-Server/silo-server/internal/catalog" @@ -325,6 +326,7 @@ type PlaybackHandler struct { v3RouteNodeProbe func(context.Context, string) bool // nil: probeRouteNodeV3 v3NodeCapabilitiesMu sync.Mutex v3NodeCapabilities map[v3NodeCapabilityKey]v3NodeCapabilityCache + v3NodeCapFlight singleflight.Group // v3NodeProbeBudgets holds what each node last said a capability read of it // costs, guarded by v3NodeCapabilitiesMu. It is kept apart from the // inventory above because the two are invalidated for different reasons: an @@ -2441,20 +2443,7 @@ func (h *PlaybackHandler) HandleGetTranscodeManifest(w http.ResponseWriter, r *h return } playback.WarnIfPlaylistOversized(r.Context(), "api", sessionID, manifest) - - w.Header().Set("Content-Type", "application/vnd.apple.mpegurl") - // no-transform keeps proxies and CDNs from re-encoding the playlist, - // which drops the Content-Length below (Cloudflare does). - w.Header().Set("Cache-Control", "no-store, no-transform, max-age=0") - w.Header().Set("Pragma", "no-cache") - // The playlist is complete in memory, so state its length. Without it a - // playlist past net/http's small write buffer goes out chunked, and a - // player that opens HLS sources with a ranged byte reader (AetherEngine - // on Apple platforms) takes the length-less 200 for a non-seekable stream - // and misreads the playlist as media. - w.Header().Set("Content-Length", strconv.Itoa(len(manifest))) - w.WriteHeader(http.StatusOK) - _, _ = w.Write(manifest) + playback.WriteHLSManifest(w, r, manifest) } func writePlaybackToneMapExecutionError(w http.ResponseWriter, err error) bool { @@ -2720,6 +2709,15 @@ func (h *PlaybackHandler) relayToTranscodeNode(w http.ResponseWriter, r *http.Re slog.WarnContext(r.Context(), "stream token not forwarded to transcode node", "component", "api", "error", verifyErr, "playback_session_id", sessionID) } } + if strings.HasSuffix(path, ".m3u8") { + if validToken != "" { + // Need plain text here so token re-injection can rewrite segment URIs + // before WriteHLSManifest compresses the client-facing response. + req.Header.Set("Accept-Encoding", "identity") + } else { + req.Header.Set("Accept-Encoding", playback.ManifestRelayAcceptEncoding(r)) + } + } resp, err := transcodeproxy.DoNode(transcodeproxy.NodeClient(), req, transcodeNodeURL, "stream") if err != nil { @@ -2772,16 +2770,16 @@ func (h *PlaybackHandler) relayToTranscodeNode(w http.ResponseWriter, r *http.Re } playback.WarnIfPlaylistOversized(r.Context(), "api", sessionID, rewritten) for k, vv := range resp.Header { - if http.CanonicalHeaderKey(k) == "Content-Length" { + canonical := http.CanonicalHeaderKey(k) + if canonical == "Content-Length" || canonical == "Content-Encoding" || canonical == "Content-Type" || + canonical == "Cache-Control" || canonical == "Pragma" || canonical == "Vary" { continue } for _, v := range vv { w.Header().Add(k, v) } } - w.Header().Set("Content-Length", strconv.Itoa(len(rewritten))) - w.WriteHeader(resp.StatusCode) - _, _ = w.Write(rewritten) + playback.WriteHLSManifest(w, r, rewritten) return nil } @@ -2804,6 +2802,7 @@ func (h *PlaybackHandler) relayToTranscodeNode(w http.ResponseWriter, r *http.Re fullSize := transcodeproxy.FullRepresentationSize(resp) if isMediaSegment && generation != "" && r.Method == http.MethodGet && sw.CompletedFullResponse(fullSize) { + _ = http.NewResponseController(w).Flush() if ackErr := transcodeproxy.Acknowledge(r.Context(), transcodeproxy.NodeClient(), transcodeNodeURL, path, h.NodeKeys, generation); ackErr != nil { slog.WarnContext(r.Context(), "acknowledge transcode segment completion", "component", "api", "error", ackErr, "playback_session_id", sessionID) } diff --git a/internal/api/handlers/playback_connection.go b/internal/api/handlers/playback_connection.go index 5fc108b3102..9e061121e75 100644 --- a/internal/api/handlers/playback_connection.go +++ b/internal/api/handlers/playback_connection.go @@ -68,19 +68,30 @@ func (h *PlaybackHandler) currentReadings(probe *connectionstore.Probe, sample * // purpose: the sender's reading is not the receiver's link. Nothing is // recorded. key is the connection the reading is read under; empty applies none. func (h *PlaybackHandler) applyConnectionReading(r *http.Request, req *playback.StartRequestV3, key string) error { + _, _, err := h.applyConnectionReadingRow(r, req, key) + return err +} + +// applyConnectionReadingRow is applyConnectionReading returning the fetched +// connection row (and whether a lookup ran) so applyLearnedLimitWithRow can +// reuse its learned limit without a second playback_connections query. +func (h *PlaybackHandler) applyConnectionReadingRow(r *http.Request, req *playback.StartRequestV3, key string) (*connectionstore.AdminConnection, bool, error) { if !playback.HasFeatureV3(req.ClientFeatures, playback.FeatureBufferingQualityV1) || req.QualityPreference != playback.QualityAutoV3 || req.BandwidthEstimateKbps != nil || req.LearnedLimit == playback.LearnedLimitIgnoreV3 { - return nil + return nil, false, nil } device, _ := r.Context().Value(playbackConnectionDeviceContextKey{}).(string) c, err := h.Connections.Connection(r.Context(), apimw.GetUserID(r.Context()), connectionDeviceV3(device), key) - if err != nil || c == nil { - return err + if err != nil { + return nil, false, err + } + if c == nil { + return nil, true, nil } if kbps := connectionstore.Reading(h.currentReadings(c.Probe, c.PlaybackSample)); kbps > 0 { req.BandwidthEstimateKbps, req.BandwidthEstimateSource = &kbps, playback.BandwidthEstimateProbeV3 } - return nil + return c, true, nil } // clearKeysV3 is the connections a clear removes the limit of: record first, @@ -114,6 +125,10 @@ func clearKeysV3(record string, clearAlso ...string) []string { // removes the limit of clearAlso, the connection the plan may be served over // instead. An empty key or record applies or writes nothing. func (h *PlaybackHandler) applyLearnedLimit(r *http.Request, req *playback.StartRequestV3, clientSent bool, key, record string, outputBound func() bool, clearAlso ...string) (*playback.BandwidthLimitV3, error) { + return h.applyLearnedLimitWithRow(r, req, clientSent, key, record, outputBound, nil, false, clearAlso...) +} + +func (h *PlaybackHandler) applyLearnedLimitWithRow(r *http.Request, req *playback.StartRequestV3, clientSent bool, key, record string, outputBound func() bool, prefetched *connectionstore.AdminConnection, hasPrefetched bool, clearAlso ...string) (*playback.BandwidthLimitV3, error) { if !playback.HasFeatureV3(req.ClientFeatures, playback.FeatureBufferingQualityV1) { return nil, nil } @@ -139,6 +154,7 @@ func (h *PlaybackHandler) applyLearnedLimit(r *http.Request, req *playback.Start if req.LearnedLimit == playback.LearnedLimitIgnoreV3 { return nil, nil } + wrote := false if clientSent && req.BandwidthEstimateSource == playback.BandwidthEstimateObservedRebufferV3 && req.BandwidthEstimateKbps != nil && req.QualityPreference == playback.QualityAutoV3 { switch { case device == "" || record == "": @@ -151,12 +167,23 @@ func (h *PlaybackHandler) applyLearnedLimit(r *http.Request, req *playback.Start if err := h.Connections.Observe(r.Context(), user, device, record, *req.BandwidthEstimateKbps); err != nil { return nil, err } + wrote = true } } if req.QualityPreference != playback.QualityAutoV3 { return nil, nil } - limit, err := h.Connections.Get(r.Context(), user, device, key) + var ( + limit *connectionstore.Limit + err error + ) + if hasPrefetched && !wrote { + if prefetched != nil { + limit = prefetched.LearnedLimit + } + } else { + limit, err = h.Connections.Get(r.Context(), user, device, key) + } if err != nil || limit == nil { return nil, err } diff --git a/internal/api/handlers/playback_desired_tracks_v3.go b/internal/api/handlers/playback_desired_tracks_v3.go index addd7225990..9b8bbb46d3d 100644 --- a/internal/api/handlers/playback_desired_tracks_v3.go +++ b/internal/api/handlers/playback_desired_tracks_v3.go @@ -39,7 +39,7 @@ func (h *PlaybackHandler) desiredSubtitleFromFileV3(ctx context.Context, file *m if h.SubtitleRepo == nil { return nil, nil } - downloaded, err := h.SubtitleRepo.ListDownloadedSubtitles(ctx, file.ID) + downloaded, err := h.listDownloadedSubtitlesRawV3(ctx, file.ID) if err != nil { return nil, fmt.Errorf("load downloaded subtitles: %w", wrapSubtitleStoreErrorV3(err)) } @@ -70,7 +70,7 @@ func (h *PlaybackHandler) resolveDesiredSubtitleV3(ctx context.Context, want pla var downloaded []subtitles.DownloadedSubtitle if want.Source == playback.SubtitleSourceDownloadedV3 && h.SubtitleRepo != nil { var err error - downloaded, err = h.SubtitleRepo.ListDownloadedSubtitles(ctx, target.ID) + downloaded, err = h.listDownloadedSubtitlesRawV3(ctx, target.ID) if err != nil { // A failed lookup says nothing about whether the track exists; // dropping the selection over it would turn subtitles off. diff --git a/internal/api/handlers/playback_direct.go b/internal/api/handlers/playback_direct.go index fb0eb016c50..192e3237a61 100644 --- a/internal/api/handlers/playback_direct.go +++ b/internal/api/handlers/playback_direct.go @@ -104,7 +104,9 @@ func (h *PlaybackHandler) loadDirectDeviceV3(ctx context.Context, userID int, de } state, ok, err := h.DirectState.Device(ctx, userID, device) if err != nil { - slog.WarnContext(ctx, "direct connection state unavailable; the API host serves the media", logComponentKey, playbackLogValueV3, "error", err) + if ctx.Err() == nil { + slog.WarnContext(ctx, "direct connection state unavailable; the API host serves the media", logComponentKey, playbackLogValueV3, "error", err) + } return directconn.DeviceDirect{}, false, err //nolint:wrapcheck // Callers only test it. } return state, ok, nil @@ -128,14 +130,24 @@ func (h *PlaybackHandler) newDirectRequestV3(ctx context.Context, userID int, de // withDirectRequestV3 records the request's direct state on ctx. The device is // the one the caller named in X-Silo-Device-Id. func (h *PlaybackHandler) withDirectRequestV3(ctx context.Context, userID int, requested string) context.Context { - retry := keyRetryFromContext(ctx) - if retry != nil && retry.direct != nil { + return attachDirectRequestV3(ctx, h.readDirectRequestV3(ctx, userID, requested)) +} + +// readDirectRequestV3 reads the direct state withDirectRequestV3 records, +// without recording it. +func (h *PlaybackHandler) readDirectRequestV3(ctx context.Context, userID int, requested string) *directRequestV3 { + if retry := keyRetryFromContext(ctx); retry != nil && retry.direct != nil { // The request runs again (see keyRetryV3) on the state its first run read. - return context.WithValue(ctx, directRequestKeyV3{}, retry.direct) + return retry.direct } device, _ := ctx.Value(playbackConnectionDeviceContextKey{}).(string) - d := h.newDirectRequestV3(ctx, userID, device, requested) - if retry != nil { + return h.newDirectRequestV3(ctx, userID, device, requested) +} + +// attachDirectRequestV3 records d on ctx, and on a key retry's first run keeps +// it for the rerun. +func attachDirectRequestV3(ctx context.Context, d *directRequestV3) context.Context { + if retry := keyRetryFromContext(ctx); retry != nil && retry.direct == nil { retry.direct = d } return context.WithValue(ctx, directRequestKeyV3{}, d) diff --git a/internal/api/handlers/playback_session_recipe.go b/internal/api/handlers/playback_session_recipe.go index 0a8ee5677ed..1098d6ea655 100644 --- a/internal/api/handlers/playback_session_recipe.go +++ b/internal/api/handlers/playback_session_recipe.go @@ -41,7 +41,7 @@ type sessionRecipeStoreV3 interface { // Best effort, like the node recipe: a failed write only costs this session its // restart recovery, and the plan binding keeps the card it failed to replace // from rebuilding the superseded transport. -func (h *PlaybackHandler) recordSessionRecipeV3(ctx context.Context, planID string, transport *preparedTransportV3) { +func (h *PlaybackHandler) recordSessionRecipeV3(ctx context.Context, planID string, transport *preparedTransportV3, isReplan bool) { if h == nil || transport == nil || transport.sessionRecipe == nil || planID == "" || h.SessionRecipeStore == nil || !h.SessionRecipeStore.Enabled() { return @@ -54,7 +54,9 @@ func (h *PlaybackHandler) recordSessionRecipeV3(ctx context.Context, planID stri return } if current.RoutingEgress == string(noderouting.EgressProxy) { - h.deleteSessionRecipeV3(ctx, card.SessionID) + if isReplan { + h.deleteSessionRecipeV3(ctx, card.SessionID) + } return } card.PlanID = planID diff --git a/internal/api/handlers/playback_v3.go b/internal/api/handlers/playback_v3.go index b0515a9900e..15b40a7bf8c 100644 --- a/internal/api/handlers/playback_v3.go +++ b/internal/api/handlers/playback_v3.go @@ -53,7 +53,7 @@ const ( maxPlaybackV3EventBodyBytes = 32 << 10 replanLeaseDurationV3 = 15 * time.Second replanReleaseTimeoutV3 = 3 * time.Second - v3NodeCapabilityTTL = time.Minute + v3NodeCapabilityTTL = 10 * time.Minute playbackNodeIntegratedV3 = "integrated" subtitleFormatVTTV3 = "vtt" subtitleCodecPGSFFmpegV3 = "hdmv_pgs_subtitle" @@ -273,6 +273,10 @@ type mediaAuthModeV3 struct { // the new transport. It changes the stream URL only, so it is not part of // plan identity. hlsTransportMarker bool + // freshStart is true only when preparing transport for a brand-new session + // created during startPlannedPlaybackV3, where no prior proxy grant can + // exist in ProxyGrantStore. + freshStart bool } // withNativeDeliveryFeaturesV3 adds the request's delivery opt-ins to mode: @@ -705,6 +709,57 @@ func (h *PlaybackHandler) lookupRemoteCapabilitiesV3(ctx context.Context, target h.refreshRemoteCapabilitiesV3(key) return entry, nil } + if err := ctx.Err(); err != nil { + return v3NodeCapabilityCache{}, err + } + + // Coalesce concurrent capability fetches for the same node and invalidation + // generation so bursts of starts never stampede /hw-capabilities. + // + // The shared fetch belongs to no single caller. Each waiter still stops at + // its own deadline below, but a planning caller's short deadline or a + // disconnected client must not fail the transport-time callers that joined + // it, nor land in the failure cache as the node's answer. + // fetchRemoteCapabilitiesOnceV3 bounds each attempt with the node's own + // probe budget. + fetchCtx := context.WithoutCancel(ctx) + flightKey := fmt.Sprintf("%d|%s|%d", target, nodeURL, h.nodeCapabilityInvalidationsV3(nodeURL)) + ch := h.v3NodeCapFlight.DoChan(flightKey, func() (result any, err error) { + // DoChan re-panics on a goroutine of its own, where no recoverer + // runs; turn a panic into this fetch's error instead. + defer func() { + if recovered := recover(); recovered != nil { + err = fmt.Errorf("node capability fetch panicked: %v", recovered) + } + }() + // A flight that finished between this caller's cache read and DoChan + // has already stored a fresh answer; use it instead of probing again. + h.v3NodeCapabilitiesMu.Lock() + current, currentOK := h.v3NodeCapabilities[key] + h.v3NodeCapabilitiesMu.Unlock() + if currentOK && current.err == nil && time.Now().Before(current.expiresAt) { + return current, nil + } + return h.fetchRemoteCapabilitiesOnceV3(fetchCtx, key) + }) + select { + case <-ctx.Done(): + return v3NodeCapabilityCache{}, ctx.Err() + case res := <-ch: + if res.Err != nil { + return v3NodeCapabilityCache{}, res.Err + } + val, ok := res.Val.(v3NodeCapabilityCache) + if !ok { + return v3NodeCapabilityCache{}, errors.New("unexpected capability cache result type") + } + return val, nil + } +} + +func (h *PlaybackHandler) fetchRemoteCapabilitiesOnceV3(ctx context.Context, key v3NodeCapabilityKey) (v3NodeCapabilityCache, error) { + target := key.target + nodeURL := key.url // An invalidation landing mid-fetch means the report this probe is about to // return describes the node as it was, not as it is — and this caller is @@ -757,7 +812,7 @@ func (h *PlaybackHandler) lookupRemoteCapabilitiesV3(ctx context.Context, target h.v3NodeCapabilitiesMu.Unlock() return v3NodeCapabilityCache{}, err } - entry = v3NodeCapabilityCache{ + entry := v3NodeCapabilityCache{ transformations: append([]playback.TransformationV3(nil), info.Transformations...), transportFeatures: append([]string(nil), info.TransportFeatures...), toneMapCapabilities: append(tonemap.Capabilities(nil), info.ToneMapCapabilities...), @@ -923,31 +978,37 @@ func (h *PlaybackHandler) warmPlaybackCapabilitiesV3(ctx context.Context) { if err := playback.WarmHardwareEncoder(ctx, cfg.FFmpegPath, cfg.HWAccel, cfg.HWDevice); err != nil { slog.DebugContext(ctx, "protocol v3 hardware encoder warmup failed", "component", "api", "error", err) } - enumerator, ok := h.NodePlanner.(transcodeNodeEnumeratorV3) - if !ok { - return + var targets []v3NodeCapabilityKey + if enumerator, ok := h.NodePlanner.(transcodeNodeEnumeratorV3); ok { + for _, nodeURL := range enumerator.TranscodeNodeURLs() { + targets = append(targets, v3NodeCapabilityKey{target: nodeauth.TargetTranscode, url: nodeURL}) + } } - nodeURLs := enumerator.TranscodeNodeURLs() - workerCount := min(playbackCapabilityWarmupWorkersV3, len(nodeURLs)) + if proxyEnumerator, ok := h.NodePlanner.(proxyNodeEnumeratorV3); ok { + for _, nodeURL := range proxyEnumerator.ProxyNodeURLs() { + targets = append(targets, v3NodeCapabilityKey{target: nodeauth.TargetProxy, url: nodeURL}) + } + } + workerCount := min(playbackCapabilityWarmupWorkersV3, len(targets)) if workerCount == 0 { return } - jobs := make(chan string) + jobs := make(chan v3NodeCapabilityKey) var group sync.WaitGroup group.Add(workerCount) for range workerCount { go func() { defer group.Done() - for nodeURL := range jobs { - if _, err := h.lookupRemoteCapabilitiesV3(ctx, nodeauth.TargetTranscode, nodeURL, false); err != nil { - slog.DebugContext(ctx, "protocol v3 node capability warmup failed", logComponentKey, "api", "node", logredact.SanitizeURL(nodeURL), "error", err) + for job := range jobs { + if _, err := h.lookupRemoteCapabilitiesV3(ctx, job.target, job.url, false); err != nil { + slog.DebugContext(ctx, "protocol v3 node capability warmup failed", logComponentKey, "api", "target", job.target, "node", logredact.SanitizeURL(job.url), "error", err) } } }() } - for _, nodeURL := range nodeURLs { + for _, job := range targets { select { - case jobs <- nodeURL: + case jobs <- job: case <-ctx.Done(): close(jobs) group.Wait() @@ -1322,6 +1383,7 @@ type hlsPlanningSnapshotV3 struct { settings playback.PlannerSettingsV3 localRegistry *playback.TransformationRegistryV3 proxyAllowed bool + needsToneMap bool progressiveOnce sync.Once progressiveRegistry *playback.TransformationRegistryV3 remuxOnce sync.Once @@ -1568,7 +1630,9 @@ func (snapshot *hlsPlanningSnapshotV3) hlsRemuxRegistry() *playback.Transformati func (snapshot *hlsPlanningSnapshotV3) hlsVideoRegistry() *playback.TransformationRegistryV3 { snapshot.videoOnce.Do(func() { - snapshot.resolveInventory() + if snapshot.needsToneMap { + snapshot.resolveInventory() + } snapshot.videoRegistry = snapshot.handler.hlsPlanningRegistryWithInputsForClientV3( snapshot.ctx, snapshot.settings, snapshot.inventory, noderouting.WorkloadVideoTranscode, snapshot.proxyAllowed, @@ -1615,8 +1679,13 @@ func retryablePlanningFailureV3(result playback.PlannerResultV3, message string) func (h *PlaybackHandler) planPlaybackWithCapabilitiesV3(ctx context.Context, input playback.PlannerInputV3) (playback.PlannerResultV3, error) { mode := headerAuthenticatedMediaV3(input.Request.ClientFeatures) proxyAllowed := !mode.headerAuth && h.JWTSecret != "" || mode.proxyEgress && h.proxyEgressOriginsAvailableV3() + fileForToneMap := input.EffectiveFile + if fileForToneMap == nil { + fileForToneMap = input.RequestedFile + } + needsToneMap := fileForToneMap == nil || playback.SourceDescriptorFromFileV3(fileForToneMap, input.AudioTrackIndex).DynamicRange != playback.DynamicRangeSDRV3 snapshot := &hlsPlanningSnapshotV3{ - handler: h, ctx: ctx, settings: input.Settings, localRegistry: input.Registry, proxyAllowed: proxyAllowed, + handler: h, ctx: ctx, settings: input.Settings, localRegistry: input.Registry, proxyAllowed: proxyAllowed, needsToneMap: needsToneMap, } input.ProgressiveRemuxRegistry = snapshot.progressiveRemuxRegistry input.HLSRemuxRegistry = snapshot.hlsRemuxRegistry @@ -1971,7 +2040,8 @@ type startPassV3 struct { // can start from them again. func (h *PlaybackHandler) planStartPassV3(r *http.Request, keys keyPassV3, req playback.StartRequestV3, requestedFile, alternateBase, effectiveFile *models.MediaFile, audioIndex, preferredAudio int, serverAudio bool, settings playback.PlannerSettingsV3, settingsErr error) startPassV3 { pass := startPassV3{read: keys.read} - if err := h.applyConnectionReading(r, &req, keys.read); err != nil { + connRow, hasConnRow, err := h.applyConnectionReadingRow(r, &req, keys.read) + if err != nil { pass.storeErr = true return pass } @@ -1980,7 +2050,7 @@ func (h *PlaybackHandler) planStartPassV3(r *http.Request, keys keyPassV3, req p // goes with the limit; the connection's reading then stands in for it. pass.unlimitedReq, pass.unlimitedFile, pass.unlimitedAudioIndex = withoutObservedEstimateV3(req), effectiveFile, audioIndex record := keys.record - learnedLimit, limitErr := h.applyLearnedLimit(r, &req, keys.writes, keys.read, record, nil, keys.clearAlso) + learnedLimit, limitErr := h.applyLearnedLimitWithRow(r, &req, keys.writes, keys.read, record, nil, connRow, hasConnRow, keys.clearAlso) if limitErr != nil { pass.storeErr = true return pass @@ -2196,7 +2266,7 @@ func (h *PlaybackHandler) startPlaybackWithRetryV3(r *http.Request, body []byte) } func (h *PlaybackHandler) startPlaybackApplicationV3(r *http.Request, body []byte) (playback.DecisionResponseV3, error) { - r = r.WithContext(withPlaybackRoutingPolicySnapshotV3(r.Context(), h.playbackRoutingPolicyV3())) + r = r.WithContext(withDownloadedSubtitlesCacheV3(withPlaybackRoutingPolicySnapshotV3(r.Context(), h.playbackRoutingPolicyV3()))) timings := newPlaybackStartTimingsV3() var req playback.StartRequestV3 defer func() { timings.log(r.Context(), req.PlaybackAttemptID) }() @@ -2218,46 +2288,58 @@ func (h *PlaybackHandler) startPlaybackApplicationV3(r *http.Request, body []byt userID := apimw.GetUserID(r.Context()) deviceID := deviceMetadataFromRequest(r).DeviceID requestDigests := newPlaybackStartRequestDigestsV3(body, deviceID) - if existing, lookupErr := h.PlanStoreV3.GetAttemptByPlaybackAttemptID(r.Context(), req.PlaybackAttemptID); lookupErr == nil { - if existing.UserID != userID || existing.ProfileID != profileID || existing.RequestedMediaFileID != req.FileID || - !requestDigests.matches(existing.RequestDigest) { - return playback.DecisionResponseV3{}, playbackOperationError(http.StatusConflict, "playback_attempt_reused", "The playback attempt ID belongs to a different request") - } - response := decisionResponseFromAttemptV3(existing) - // A terminal publishes no subtitle URLs, so it replays on either - // surface; the surface check protects only a playable plan. - if response.Terminal != nil { - return response, nil - } - if err := requireAttemptAPISurfaceV3(existing, req.ClientFeatures); err != nil { - return playback.DecisionResponseV3{}, err - } - // The replayed plan is only usable while its session is alive; a dead - // session must surface as a retryable terminal so the client mints a - // fresh attempt instead of replaying a plan it can never stream. A - // stopped attempt is dead on every replica, whether or not this one - // still holds the session. - if existing.SessionID == "" { - return playback.DecisionResponseV3{}, playbackOperationError(http.StatusInternalServerError, "internal_error", "Stored playback attempt has no replayable decision") - } - if existing.StoppedAt != nil { - return playback.NewTerminalResponseV3(terminalSessionExpiredV3, "The playback session for this attempt has ended.", true), nil - } - if _, sessionErr := h.sessionMgr.GetSession(existing.SessionID); sessionErr != nil { - return playback.NewTerminalResponseV3(terminalSessionExpiredV3, "The playback session for this attempt has ended.", true), nil - } - return h.gateReplayV3(r.Context(), userID, response) - } else if !errors.Is(lookupErr, playback.ErrSessionNotFound) { + // Wave 1: overlap attempt idempotency lookup, direct-path state lookup, + // authorized file load, and planner settings reads instead of paying four + // serial Postgres RTTs. A replay answers from the stored attempt as soon as + // that lookup returns, without waiting on the other three. + var ( + existing *playback.AttemptRecordV3 + lookupErr error + requestedFile *models.MediaFile + fileErr error + settings playback.PlannerSettingsV3 + settingsErr error + direct *directRequestV3 + wave1 sync.WaitGroup + ) + attemptLooked := make(chan struct{}) + go func() { + defer close(attemptLooked) + existing, lookupErr = h.PlanStoreV3.GetAttemptByPlaybackAttemptID(r.Context(), req.PlaybackAttemptID) + }() + // An early return below cancels the other three reads so they stop holding + // database connections. Their results are recorded only on the path that + // uses them. + speculativeCtx, cancelSpeculative := context.WithCancel(r.Context()) + defer cancelSpeculative() + wave1.Add(3) + go func() { + defer wave1.Done() + direct = h.readDirectRequestV3(speculativeCtx, userID, req.MediaTransport) + }() + go func() { + defer wave1.Done() + requestedFile, fileErr = h.loadAuthorizedFile(r.WithContext(speculativeCtx), req.FileID) + }() + go func() { + defer wave1.Done() + settings, settingsErr = h.plannerSettingsV3Result(speculativeCtx) + }() + <-attemptLooked + if lookupErr == nil { + cancelSpeculative() + return h.replayExistingStartAttemptV3(r.Context(), userID, profileID, req, requestDigests, existing) + } + if !errors.Is(lookupErr, playback.ErrSessionNotFound) { + cancelSpeculative() return playback.DecisionResponseV3{}, playbackOperationError(http.StatusInternalServerError, "internal_error", "Failed to check playback attempt idempotency") } + wave1.Wait() + directCtx := attachDirectRequestV3(r.Context(), direct) timings.mark("idempotency") - r = r.WithContext(withServerBitrateCapV3(r.Context(), requestBitrateCapV3(r.Context()))) - // The device's direct state is read here, once, before any route is - // resolved: planning and route selection only read fields of it. - r = r.WithContext(h.withDirectRequestV3(r.Context(), userID, req.MediaTransport)) - requestedFile, err := h.loadAuthorizedFile(r, req.FileID) - if err != nil { - return playback.DecisionResponseV3{}, playbackFileOperationError(err) + r = r.WithContext(withServerBitrateCapV3(directCtx, requestBitrateCapV3(directCtx))) + if fileErr != nil { + return playback.DecisionResponseV3{}, playbackFileOperationError(fileErr) } requestedFile = h.ensurePlaybackProbe(r.Context(), requestedFile) timings.mark("file_load_probe") @@ -2271,23 +2353,55 @@ func (h *PlaybackHandler) startPlaybackApplicationV3(r *http.Request, body []byt if audioDegraded { warnings = append(warnings, playback.AudioTrackUnavailableWarningV3()) } + effectiveFile := requestedFile + // Wave 2: overlap saved audio preference, filesystem preflight, and saved + // resume position reads while preserving exact error precedence. + needAudioPref := req.AudioTrackID == "" && req.AudioTrackIndex == nil + needResume := req.StartPosition == nil + var ( + prefAudioIndex int + prefSaved bool + prefAudioErr error + preflightErr error + resumePos *float64 + resumeErr error + wave2 sync.WaitGroup + ) + wave2.Add(1) + go func() { + defer wave2.Done() + preflightErr = preflightPlaybackFile(r.Context(), effectiveFile, h.MissingMarker, h.EventsHub) + }() + if needAudioPref { + wave2.Add(1) + go func() { + defer wave2.Done() + prefAudioIndex, prefSaved, prefAudioErr = h.preferredAudioTrackIndexV3(r.Context(), userID, profileID, deviceID, requestedFile) + }() + } + if needResume { + wave2.Add(1) + go func() { + defer wave2.Done() + resumePos, resumeErr = h.resumePositionV3(r.Context(), userID, profileID, effectiveFile) + }() + } + wave2.Wait() + // serverAudio marks a track the server chose by preference alone, which // the request's capabilities may still refine below. serverAudio := false - if req.AudioTrackID == "" && req.AudioTrackIndex == nil { - var saved bool - audioIndex, saved, err = h.preferredAudioTrackIndexV3(r.Context(), userID, profileID, deviceID, requestedFile) - if err != nil { + if needAudioPref { + if prefAudioErr != nil { return playback.DecisionResponseV3{}, playbackOperationError(http.StatusInternalServerError, "internal_error", "Failed to load the saved audio preference") } - serverAudio = !saved + audioIndex = prefAudioIndex + serverAudio = !prefSaved } timings.mark("audio_preference") - effectiveFile := requestedFile - settings, settingsErr := h.plannerSettingsV3Result(r.Context()) timings.mark("planner_settings") - if err := preflightPlaybackFile(r.Context(), effectiveFile, h.MissingMarker, h.EventsHub); err != nil { - return playback.DecisionResponseV3{}, playbackPreflightOperationError(err) + if preflightErr != nil { + return playback.DecisionResponseV3{}, playbackPreflightOperationError(preflightErr) } timings.mark("file_preflight") // preferredAudio is that choice before the refinement, which a later @@ -2303,38 +2417,14 @@ func (h *PlaybackHandler) startPlaybackApplicationV3(r *http.Request, body []byt if req.SubtitleTrackID != "" || req.SubtitleTrackIndex != nil { intent.subtitle = &playback.TrackIdentityV3{ID: req.SubtitleTrackID, Index: copyOptionalIntV3(req.SubtitleTrackIndex)} } - if req.StartPosition == nil { - req.StartPosition, err = h.resumePositionV3(r.Context(), userID, profileID, effectiveFile) - if err != nil { + if needResume { + if resumeErr != nil { return playback.DecisionResponseV3{}, playbackOperationError(http.StatusInternalServerError, "internal_error", "Failed to load saved playback progress") } - // Multipart audiobook files share one item progress row, while the - // planner starts a single file-local timeline. When the stored resume - // point is item-absolute, select the corresponding part and translate - // it to that part's local clock. Explicit client positions remain - // unchanged. - if req.StartPosition != nil && effectiveFile.PresentationPartTotal > 1 { - target, local, resolveErr := h.multipartResumeFileV3(r.Context(), effectiveFile, *req.StartPosition, requestAccessFilter(r)) - if resolveErr != nil { - // An item-absolute position cannot be projected onto this - // file's part-local clock without the complete ordered part - // list. Applying it to the requested part would seek that part - // far past its end, so start from the beginning instead. - slog.DebugContext(r.Context(), "protocol v3 multipart resume mapping unavailable", "component", "api", "file_id", effectiveFile.ID, "error", resolveErr) - req.StartPosition = nil - } else if target != nil && target.ID != requestedFile.ID && !req.AllowsAlternateVersions() { - // A fixed-file attempt cannot resume into a different part. - req.StartPosition = new(float64(0)) - } else if target != nil { - effectiveFile = h.ensurePlaybackProbe(r.Context(), target) - audioIndex = remapAudioIndexV3(requestedFile, effectiveFile, audioIndex) - if err := preflightPlaybackFile(r.Context(), effectiveFile, h.MissingMarker, h.EventsHub); err != nil { - return playback.DecisionResponseV3{}, playbackPreflightOperationError(err) - } - req.StartPosition = &local - } else { - req.StartPosition = nil - } + var opErr error + effectiveFile, audioIndex, req.StartPosition, opErr = h.applyStartResumeV3(r, req, requestedFile, effectiveFile, audioIndex, resumePos) + if opErr != nil { + return playback.DecisionResponseV3{}, opErr } } timings.mark("resume") @@ -2528,12 +2618,82 @@ func appendStartWarningsV3(result *playback.PlannerResultV3, warnings []playback } } +func (h *PlaybackHandler) replayExistingStartAttemptV3(ctx context.Context, userID int, profileID string, req playback.StartRequestV3, requestDigests playbackStartRequestDigestsV3, existing *playback.AttemptRecordV3) (playback.DecisionResponseV3, error) { + if existing.UserID != userID || existing.ProfileID != profileID || existing.RequestedMediaFileID != req.FileID || + !requestDigests.matches(existing.RequestDigest) { + return playback.DecisionResponseV3{}, playbackOperationError(http.StatusConflict, "playback_attempt_reused", "The playback attempt ID belongs to a different request") + } + response := decisionResponseFromAttemptV3(existing) + // A terminal publishes no subtitle URLs, so it replays on either + // surface; the surface check protects only a playable plan. + if response.Terminal != nil { + return response, nil + } + if err := requireAttemptAPISurfaceV3(existing, req.ClientFeatures); err != nil { + return playback.DecisionResponseV3{}, err + } + // The replayed plan is only usable while its session is alive; a dead + // session must surface as a retryable terminal so the client mints a + // fresh attempt instead of replaying a plan it can never stream. A + // stopped attempt is dead on every replica, whether or not this one + // still holds the session. + if existing.SessionID == "" { + return playback.DecisionResponseV3{}, playbackOperationError(http.StatusInternalServerError, "internal_error", "Stored playback attempt has no replayable decision") + } + if existing.StoppedAt != nil { + return playback.NewTerminalResponseV3(terminalSessionExpiredV3, "The playback session for this attempt has ended.", true), nil + } + if !h.hasLiveSessionV3(existing.SessionID) { + return playback.NewTerminalResponseV3(terminalSessionExpiredV3, "The playback session for this attempt has ended.", true), nil + } + return h.gateReplayV3(ctx, userID, response) +} + +func (h *PlaybackHandler) hasLiveSessionV3(sessionID string) bool { + _, err := h.sessionMgr.GetSession(sessionID) + return err == nil +} + +func (h *PlaybackHandler) applyStartResumeV3(r *http.Request, req playback.StartRequestV3, requestedFile, effectiveFile *models.MediaFile, audioIndex int, resumePos *float64) (*models.MediaFile, int, *float64, error) { + // Multipart audiobook files share one item progress row, while the + // planner starts a single file-local timeline. When the stored resume + // point is item-absolute, select the corresponding part and translate + // it to that part's local clock. Explicit client positions remain + // unchanged. + if resumePos == nil || effectiveFile.PresentationPartTotal <= 1 { + return effectiveFile, audioIndex, resumePos, nil + } + target, local, resolveErr := h.multipartResumeFileV3(r.Context(), effectiveFile, *resumePos, requestAccessFilter(r)) + if resolveErr != nil { + // An item-absolute position cannot be projected onto this + // file's part-local clock without the complete ordered part + // list. Applying it to the requested part would seek that part + // far past its end, so start from the beginning instead. + slog.DebugContext(r.Context(), "protocol v3 multipart resume mapping unavailable", "component", "api", "file_id", effectiveFile.ID, "error", resolveErr) + return effectiveFile, audioIndex, nil, nil + } + if target == nil { + return effectiveFile, audioIndex, nil, nil + } + if target.ID != requestedFile.ID && !req.AllowsAlternateVersions() { + // A fixed-file attempt cannot resume into a different part. + return effectiveFile, audioIndex, new(float64(0)), nil + } + effectiveFile = h.ensurePlaybackProbe(r.Context(), target) + audioIndex = remapAudioIndexV3(requestedFile, effectiveFile, audioIndex) + if err := preflightPlaybackFile(r.Context(), effectiveFile, h.MissingMarker, h.EventsHub); err != nil { + return effectiveFile, audioIndex, nil, playbackPreflightOperationError(err) + } + return effectiveFile, audioIndex, &local, nil +} + // startPlannedPlaybackV3 creates a session and transport for an accepted plan. func (h *PlaybackHandler) startPlannedPlaybackV3(r *http.Request, userID int, profileID string, req playback.StartRequestV3, requestDigests playbackStartRequestDigestsV3, requestedFile, effectiveFile *models.MediaFile, audioIndex int, intent startIntentV3, result playback.PlannerResultV3, clientInfo playback.ClientInfo) (playback.DecisionResponseV3, *transportErrorV3) { if result.Plan == nil { return playback.DecisionResponseV3{}, &transportErrorV3{reason: "internal_error", message: "The server produced no playback plan."} } mode := withNativeDeliveryFeaturesV3(headerAuthenticatedMediaV3(req.ClientFeatures), req) + mode.freshStart = true ctx := playback.WithClientInfo(r.Context(), clientInfo) session, err := h.sessionMgr.StartSessionWithFilesContext(ctx, userID, profileID, effectiveFile.ID, requestedFile.ID, result.PlayMethod, result.TranscodeAudio) if err != nil { @@ -2641,8 +2801,11 @@ func (h *PlaybackHandler) startPlannedPlaybackV3(r *http.Request, userID int, pr persisted.attemptPersisted = true return playback.DecisionResponseV3{}, &persisted } - h.recordSessionRecipeV3(r.Context(), result.Plan.PlanID, &transport) + h.recordSessionRecipeV3(r.Context(), result.Plan.PlanID, &transport, false) if started, err := h.sessionMgr.GetSession(session.ID); err == nil { + // Before the 201: a pause or admin command the client confirms right + // after the response updates this row, and finds nothing if the row + // does not exist yet. h.SessionStarted(r.Context(), started, LifecycleFrontendNative) } // Start-side effects belong after both the attempt and transport commits: @@ -3424,7 +3587,7 @@ func (h *PlaybackHandler) prepareIdentityTransportV3(r *http.Request, session *p case !mode.headerAuth: streamURL, servedByProxy = h.identityStreamURLV3(&routeSession, file, proxyNode, accessPath, directMediaFromContext(r.Context())) case mode.proxyEgress: - streamURL, servedByProxy, priorGrant = h.identityGrantStreamURLV3(r.Context(), &routeSession, file, proxyNode, accessPath, directMediaFromContext(r.Context())) + streamURL, servedByProxy, priorGrant = h.identityGrantStreamURLWithPriorV3(r.Context(), &routeSession, file, proxyNode, accessPath, directMediaFromContext(r.Context()), !mode.freshStart) } reservationReleased := false if proxyNode != nil && !servedByProxy { @@ -3620,6 +3783,10 @@ func (h *PlaybackHandler) revokeStaleProxyGrantOnCommitV3(ctx context.Context, s // path is the client's access path: a proxy with no origin on it is treated // like no proxy at all, before any grant is written, so the API relays. func (h *PlaybackHandler) identityGrantStreamURLV3(ctx context.Context, s *playback.Session, file *models.MediaFile, proxyNode *nodepool.Node, path netaccess.Path, direct nodepool.DirectMedia) (string, bool, *playback.RecipeCard) { + return h.identityGrantStreamURLWithPriorV3(ctx, s, file, proxyNode, path, direct, true) +} + +func (h *PlaybackHandler) identityGrantStreamURLWithPriorV3(ctx context.Context, s *playback.Session, file *models.MediaFile, proxyNode *nodepool.Node, path netaccess.Path, direct nodepool.DirectMedia, fetchPrior bool) (string, bool, *playback.RecipeCard) { if proxyNode == nil || file == nil || s == nil { return h.playbackStreamURL(s), false, nil } @@ -3632,7 +3799,7 @@ func (h *PlaybackHandler) identityGrantStreamURLV3(ctx context.Context, s *playb card.DVProfile = file.PrimaryDVProfile() card.AudioOnly = file.IsAudioOnly() card.RoutingEgressNodeID = proxyNode.ID - prior, stored := h.putProxyGrantV3(ctx, s.ID, card) + prior, stored := h.putProxyGrantV3(ctx, s.ID, card, fetchPrior) if !stored { return h.playbackStreamURL(s), false, nil } @@ -3654,13 +3821,15 @@ func (h *PlaybackHandler) identityGrantStreamURLV3(ctx context.Context, s *playb // A disabled store is a negative answer rather than a silent success: it // accepts writes it cannot retrieve (the Redis-less integrated box), and // publishing a proxy URL against one would hand the client a route that 404s. -func (h *PlaybackHandler) putProxyGrantV3(ctx context.Context, sessionID string, card playback.RecipeCard) (*playback.RecipeCard, bool) { +func (h *PlaybackHandler) putProxyGrantV3(ctx context.Context, sessionID string, card playback.RecipeCard, fetchPrior bool) (*playback.RecipeCard, bool) { if h.ProxyGrantStore == nil || !h.ProxyGrantStore.Enabled() || sessionID == "" { return nil, false } - prior, hadPrior := h.ProxyGrantStore.Get(ctx, sessionID) - if !hadPrior { - prior = nil + var prior *playback.RecipeCard + if fetchPrior { + if existing, hadPrior := h.ProxyGrantStore.Get(ctx, sessionID); hadPrior { + prior = existing + } } if err := h.ProxyGrantStore.Put(ctx, sessionID, card); err != nil { slog.WarnContext(ctx, "protocol v3 proxy egress grant write failed; serving from the API origin", @@ -4907,7 +5076,7 @@ func (h *PlaybackHandler) prepareRemoteTransportV3(r *http.Request, session *pla url = h.buildProxyManifestURL(card, nodePlan.ProxyNode, mode.headerAuth, accessPath, directMediaFromContext(r.Context())) servedByProxy = nodePlan.ProxyNode != nil && strings.HasPrefix(url, "http") case mode.proxyEgress: - url, servedByProxy, priorGrant = h.grantManifestURLV3(r.Context(), card, nodePlan.ProxyNode, accessPath, directMediaFromContext(r.Context())) + url, servedByProxy, priorGrant = h.grantManifestURLWithPriorV3(r.Context(), card, nodePlan.ProxyNode, accessPath, directMediaFromContext(r.Context()), !mode.freshStart) } if mode.headerAuth { // No client-visible URL carries a stream token in this mode, so neither the @@ -5055,6 +5224,10 @@ func remoteTranscodeRecipeCardV3(session *playback.Session, file *models.MediaFi // from this server, which relays the same node. The third value is the grant // this write displaced, for the caller's rollback. func (h *PlaybackHandler) grantManifestURLV3(ctx context.Context, card playback.RecipeCard, proxyNode *nodepool.Node, path netaccess.Path, direct nodepool.DirectMedia) (string, bool, *playback.RecipeCard) { + return h.grantManifestURLWithPriorV3(ctx, card, proxyNode, path, direct, true) +} + +func (h *PlaybackHandler) grantManifestURLWithPriorV3(ctx context.Context, card playback.RecipeCard, proxyNode *nodepool.Node, path netaccess.Path, direct nodepool.DirectMedia, fetchPrior bool) (string, bool, *playback.RecipeCard) { localURL := fmt.Sprintf("/playback/transcode/%s/master.m3u8", card.SessionID) if proxyNode == nil { return localURL, false, nil @@ -5064,7 +5237,7 @@ func (h *PlaybackHandler) grantManifestURLV3(ctx context.Context, card playback. return localURL, false, nil } card.RoutingEgressNodeID = proxyNode.ID - prior, stored := h.putProxyGrantV3(ctx, card.SessionID, card) + prior, stored := h.putProxyGrantV3(ctx, card.SessionID, card, fetchPrior) if !stored { return localURL, false, nil } @@ -5311,7 +5484,7 @@ func (h *PlaybackHandler) attachSubtitleArtifactV3(ctx context.Context, sessionI if h == nil || h.SubtitleRepo == nil { return errors.New("the downloaded subtitle inventory is unavailable") } - downloaded, err := h.SubtitleRepo.ListDownloadedSubtitles(ctx, file.ID) + downloaded, err := h.listDownloadedSubtitlesRawV3(ctx, file.ID) if err != nil { return wrapSubtitleStoreErrorV3(err) } @@ -5423,13 +5596,51 @@ func (h *PlaybackHandler) downloadedSubtitleInventoryV3(ctx context.Context, fil return entries } +type downloadedSubtitlesCacheKeyV3 struct{} + +type downloadedSubtitlesCacheV3 struct { + mu sync.Mutex + entries map[int][]subtitles.DownloadedSubtitle +} + +func withDownloadedSubtitlesCacheV3(ctx context.Context) context.Context { + return context.WithValue(ctx, downloadedSubtitlesCacheKeyV3{}, &downloadedSubtitlesCacheV3{ + entries: make(map[int][]subtitles.DownloadedSubtitle, 2), + }) +} + +func (h *PlaybackHandler) listDownloadedSubtitlesRawV3(ctx context.Context, fileID int) ([]subtitles.DownloadedSubtitle, error) { + if h == nil || h.SubtitleRepo == nil { + return nil, nil + } + if cache, ok := ctx.Value(downloadedSubtitlesCacheKeyV3{}).(*downloadedSubtitlesCacheV3); ok && cache != nil { + cache.mu.Lock() + rows, found := cache.entries[fileID] + cache.mu.Unlock() + if found { + return rows, nil + } + rows, err := h.SubtitleRepo.ListDownloadedSubtitles(ctx, fileID) + if err != nil { + // A failed read is not cached: a later lookup in the same start + // that needs the inventory retries, as it did before the cache. + return nil, err + } + cache.mu.Lock() + cache.entries[fileID] = rows + cache.mu.Unlock() + return rows, nil + } + return h.SubtitleRepo.ListDownloadedSubtitles(ctx, fileID) +} + // listDownloadedSubtitlesV3 is downloadedSubtitleInventoryV3 that reports a // failed lookup, wrapped as a subtitle-store outage. func (h *PlaybackHandler) listDownloadedSubtitlesV3(ctx context.Context, file *models.MediaFile) ([]playback.SubtitleInventoryEntryV3, error) { if h == nil || h.SubtitleRepo == nil || file == nil { return nil, nil } - downloaded, err := h.SubtitleRepo.ListDownloadedSubtitles(ctx, file.ID) + downloaded, err := h.listDownloadedSubtitlesRawV3(ctx, file.ID) if err != nil { return nil, wrapSubtitleStoreErrorV3(err) } @@ -5691,7 +5902,7 @@ func (h *PlaybackHandler) replanPlaybackApplicationV3(r *http.Request, sessionID _ = h.abortPlaybackSessionByID(context.WithoutCancel(r.Context()), sessionID) return playback.DecisionResponseV3{}, playbackOperationError(http.StatusServiceUnavailable, commitErr.reason, commitErr.message) } - h.recordSessionRecipeV3(r.Context(), updated.CurrentPlanID, transport) + h.recordSessionRecipeV3(r.Context(), updated.CurrentPlanID, transport, true) if transport.afterDurableCommit != nil { transport.afterDurableCommit() } @@ -7778,6 +7989,10 @@ func (h *PlaybackHandler) plannerSettingsV3(ctx context.Context) playback.Planne return settings } +type serverSettingsBatchGetter interface { + GetMany(ctx context.Context, keys ...string) (map[string]string, error) +} + // plannerSettingsV3Result reads the live settings used for an actual planning // decision. Callers must not persist a policy terminal when the store is down. func (h *PlaybackHandler) plannerSettingsV3Result(ctx context.Context) (settings playback.PlannerSettingsV3, err error) { @@ -7785,8 +8000,6 @@ func (h *PlaybackHandler) plannerSettingsV3Result(ctx context.Context) (settings viewerTranscodeDisabled := h.viewerTranscodeDisabledV3(ctx) defer func() { settings.ViewerTranscodeDisabled = <-viewerTranscodeDisabled }() if h.SettingsRepo != nil { - var values [5]string - var errs [5]error keys := [...]string{ config.Allow4KTranscodeSettingKey, config.PlaybackTranscodeHardwareToneMapSettingKey, @@ -7794,29 +8007,41 @@ func (h *PlaybackHandler) plannerSettingsV3Result(ctx context.Context) (settings config.PlaybackAllowHEVCEncodingSettingKey, config.PlaybackPreferLowerVersionTranscodeSettingKey, } - var group sync.WaitGroup - group.Add(len(keys)) - for index, key := range keys { - go func() { - defer group.Done() - values[index], errs[index] = h.SettingsRepo.Get(ctx, key) - }() - } - group.Wait() - if errs[0] != nil { - return settings, fmt.Errorf("load 4K transcode setting: %w", errs[0]) - } - if errs[1] != nil { - return settings, fmt.Errorf("load hardware tone-map setting: %w", errs[1]) - } - if errs[2] != nil { - return settings, fmt.Errorf("load software tone-map setting: %w", errs[2]) - } - if errs[3] != nil { - return settings, fmt.Errorf("load HEVC encoding setting: %w", errs[3]) - } - if errs[4] != nil { - return settings, fmt.Errorf("load lower-version transcode setting: %w", errs[4]) + var values [5]string + if batch, ok := h.SettingsRepo.(serverSettingsBatchGetter); ok { + loaded, batchErr := batch.GetMany(ctx, keys[:]...) + if batchErr != nil { + return settings, fmt.Errorf("load planner settings: %w", batchErr) + } + for index, key := range keys { + values[index] = loaded[key] + } + } else { + var errs [5]error + var group sync.WaitGroup + group.Add(len(keys)) + for index, key := range keys { + go func() { + defer group.Done() + values[index], errs[index] = h.SettingsRepo.Get(ctx, key) + }() + } + group.Wait() + if errs[0] != nil { + return settings, fmt.Errorf("load 4K transcode setting: %w", errs[0]) + } + if errs[1] != nil { + return settings, fmt.Errorf("load hardware tone-map setting: %w", errs[1]) + } + if errs[2] != nil { + return settings, fmt.Errorf("load software tone-map setting: %w", errs[2]) + } + if errs[3] != nil { + return settings, fmt.Errorf("load HEVC encoding setting: %w", errs[3]) + } + if errs[4] != nil { + return settings, fmt.Errorf("load lower-version transcode setting: %w", errs[4]) + } } settings.Allow4KTranscode = config.AdminSettingEnabled(keys[0], values[0]) settings.HardwareToneMapEnabled = config.AdminSettingEnabled(keys[1], values[1]) @@ -7846,7 +8071,8 @@ func (h *PlaybackHandler) viewerTranscodeDisabledV3(ctx context.Context) <-chan } go func() { limits, err := reader.LimitsForUser(ctx, userID) - if err != nil { + // A start that returned early cancels this read; that is not a failure. + if err != nil && ctx.Err() == nil { slog.WarnContext(ctx, "load viewer playback limits for planning", "component", "playback", "user_id", userID, "error", err) } result <- err == nil && limits.TranscodingDisabled diff --git a/internal/api/handlers/playback_v3_capability_retry_test.go b/internal/api/handlers/playback_v3_capability_retry_test.go index 2bfb100e4a0..d5cb0d8d719 100644 --- a/internal/api/handlers/playback_v3_capability_retry_test.go +++ b/internal/api/handlers/playback_v3_capability_retry_test.go @@ -3,6 +3,7 @@ package handlers import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "sync" @@ -129,3 +130,62 @@ func TestRefreshNodeCapabilitiesKeepsTheLearnedProbeBudget(t *testing.T) { release() waitForCachedNodeCapabilitiesV3(t, handler, node.URL) } + +// Concurrent lookups for one node share a single fetch. A planning lookup with +// a short deadline can be the one that starts it; when its deadline passed, the +// transport-time lookup that joined failed with that deadline too, rejecting a +// node it had the budget to validate. +func TestSharedCapabilityFetchOutlivesTheLeadersDeadline(t *testing.T) { + handler := newKeyedPlaybackHandler(nil) + var fetches atomic.Int32 + started := make(chan struct{}) + release := make(chan struct{}) + node := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if fetches.Add(1) == 1 { + close(started) + } + select { + case <-release: + case <-r.Context().Done(): + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "resolved": "none", + "transformations": []map[string]any{ + {"name": "video_to_h264", "executor": "software", "recipe_version": "v3"}, + }, + }) + })) + t.Cleanup(node.Close) + + leaderCtx, cancelLeader := context.WithCancel(context.Background()) + leaderErr := make(chan error, 1) + go func() { + _, err := handler.lookupRemoteCapabilitiesV3(leaderCtx, nodeauth.TargetTranscode, node.URL, true) + leaderErr <- err + }() + <-started + + joined := make(chan error, 1) + go func() { + _, err := handler.lookupRemoteCapabilitiesV3(context.Background(), nodeauth.TargetTranscode, node.URL, false) + joined <- err + }() + // Whether the joiner reaches the shared fetch before or after the leader + // leaves, the fetch must outlive the leader and answer the joiner. + cancelLeader() + if err := <-leaderErr; !errors.Is(err, context.Canceled) { + t.Fatalf("leader error = %v, want its own cancellation", err) + } + close(release) + if err := <-joined; err != nil { + t.Fatalf("joined lookup failed with the leader's error: %v", err) + } + if got := fetches.Load(); got != 1 { + t.Fatalf("fetches = %d, want the joiner served by the one shared fetch", got) + } + if _, err := handler.lookupRemoteCapabilitiesV3(context.Background(), nodeauth.TargetTranscode, node.URL, true); err != nil { + t.Fatalf("planning lookup after the shared fetch = %v, want the cached report", err) + } +} diff --git a/internal/api/handlers/playback_v3_union_test.go b/internal/api/handlers/playback_v3_union_test.go index 840b268347d..3eda54a4f59 100644 --- a/internal/api/handlers/playback_v3_union_test.go +++ b/internal/api/handlers/playback_v3_union_test.go @@ -446,3 +446,80 @@ func TestProgressivePlanningCapabilitiesV3RequireRelayAndAuthorityForTranscodeEx t.Fatal("eligible transcode capability with relay and authority store was omitted") } } + +func TestPlanPlaybackWithCapabilitiesV3SkipsToneMapProbeForSDR(t *testing.T) { + manager := playback.NewSessionManager(0, 0) + handler := newKeyedPlaybackHandler(manager) + handler.SettingsRepo = &mutablePlaybackSettingsV3{values: map[string]string{ + config.PlaybackTranscodeHardwareToneMapSettingKey: "true", + config.PlaybackTranscodeSoftwareToneMapSettingKey: "true", + }} + toneMapProbeCalls := 0 + handler.v3ToneMapProbe = func(context.Context, string, string, string) (tonemap.Capabilities, error) { + toneMapProbeCalls++ + return nil, nil + } + localReg := playback.NewTransformationRegistryV3([]playback.TransformationSpecV3{ + {Name: playback.TransformationVideoToH264V3, RecipeVersion: playback.TransformationVideoToH264RecipeVersionV3, Available: true}, + {Name: playback.TransformationVideoToHEVCV3, RecipeVersion: playback.TransformationVideoToHEVCRecipeVersionV3, Available: true}, + {Name: playback.TransformationAudioToAACV3, RecipeVersion: playback.TransformationAudioToAACRecipeVersionV3, Available: true}, + }) + presetLocalRegistryV3(handler, localReg) + + multiplePPS := true + sdrFile := v3HandlerFixtureFile(t) + sdrFile.ID = 379784 + sdrFile.Container = "mkv" + sdrFile.CodecVideo = "h264" + sdrFile.CodecAudio = "dts" + sdrFile.Bitrate = 25_000 + sdrFile.VideoTracks = []models.VideoTrack{{ + Codec: "h264", Profile: "high", Level: 41, Width: 1920, Height: 1080, + FrameRate: "24000/1001", Bitrate: 25_000, BitDepth: 8, VideoRange: "SDR", VideoRangeType: "SDR", + ColorPrimaries: "bt709", ColorTransfer: "bt709", ColorSpace: "bt709", MultiplePPS: &multiplePPS, + }} + sdrFile.AudioTracks = []models.AudioTrack{{Codec: "dts", Channels: 6, Layout: "5.1", Default: true}} + + req := playback.StartRequestV3{ + ProtocolVersion: playback.ProtocolV3, + FileID: 379784, + Capabilities: playback.ClientCodecCapabilitiesV3{ + VideoEvidence: playback.EvidenceDeclaredV3, AudioEvidence: playback.EvidenceDeclaredV3, + CodecsVideo: []string{"h264", "hevc"}, CodecsAudio: []string{"aac"}, Containers: []string{"mp4", "mkv"}, + MaxResolution: "2160p", + }, + ClientPlaybackContext: playback.ClientPlaybackContextV3{ + ProtocolVersion: playback.ProtocolV3, + Device: playback.DeviceContextV3{ + Platform: "web", + PlatformDetails: map[string]string{ + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36", + }, + }, + Deliveries: map[string]playback.DeliveryCapabilityV3{ + playback.DeliveryClassHLSV3: { + Enabled: true, SupportedOnDevice: true, + VideoCodecs: []string{"h264", "hevc"}, AudioDecodeCodecs: []string{"aac"}, + }, + }, + }, + } + + result, err := handler.planPlaybackWithCapabilitiesV3(t.Context(), playback.PlannerInputV3{ + Request: req, RequestedFile: sdrFile, EffectiveFile: sdrFile, AudioTrackIndex: 0, + Settings: playback.PlannerSettingsV3{ + TranscodeEnabled: true, Allow4KTranscode: true, + HardwareToneMapEnabled: true, SoftwareToneMapEnabled: true, + }, + Registry: localReg, + }) + if err != nil { + t.Fatalf("plan SDR transcode error = %v", err) + } + if result.Plan == nil || result.PlayMethod != playback.PlayTranscode { + t.Fatalf("SDR plan = %#v, terminal = %#v; want PlayTranscode", result.Plan, result.Terminal) + } + if toneMapProbeCalls != 0 { + t.Fatalf("SDR transcode invoked v3ToneMapProbe %d times, want 0", toneMapProbeCalls) + } +} diff --git a/internal/api/handlers/stream.go b/internal/api/handlers/stream.go index 75d037db43e..23011b29b76 100644 --- a/internal/api/handlers/stream.go +++ b/internal/api/handlers/stream.go @@ -133,70 +133,35 @@ func (h *StreamHandler) HandleStream(w http.ResponseWriter, r *http.Request) { return } setPlaybackSessionLogContext(r, sessionID) - if h.StreamDeny.Denied(r.Context(), sessionID) { - writeDeniedPlaybackSession(w, r, h.PlanStoreV3, sessionID) - return - } - // Look up the session, reconstructing it from the recipe card on a not-found - // miss (e.g. after a server restart) so a direct/remux stream resumes instead - // of 404-ing. The client re-supplies its position (HTTP Range for direct, the - // ?seek= query for remux), so no runtime beyond the Session needs rebuilding. - // Without a token (or signing secret) reconstruct is off, collapsing to a - // plain GetSession + ownership check. - card, claims := verifiedStreamCardFromToken(r.URL.Query().Get(streamTokenParam), sessionID, h.JWTSecret) - loadCard := card - if _, err := h.sessionMgr.GetSession(sessionID); err == nil { - // A live route may have been replanned since this token was issued. Do not - // let stale recipe routing override the current session, and do not revive - // the stale recipe if the live session disappears during this request. - loadCard = nil - } else if errors.Is(err, playback.ErrSessionNotFound) { - if loadCard == nil { - // A header-authenticated session carries no token; its recipe is the - // server-side recovery card. - var recipeErr error - if loadCard, recipeErr = h.storedSessionRecipeV3(r.Context(), sessionID, userID); recipeErr != nil { - writeError(w, http.StatusInternalServerError, "internal_error", "Failed to load playback session") - return - } - } - if !requireNativeRecipeAPIEgressV3(w, loadCard) { + // Fast path for live sessions in memory: check GetSession once and overlap + // the Redis deny check with the Postgres media file lookup instead of + // running them serially or calling GetSession twice. + var ( + session *playback.Session + claims *streamtoken.Claims + file *models.MediaFile + fileErr error + ) + if rawToken := r.URL.Query().Get(streamTokenParam); rawToken != "" && h.JWTSecret != "" { + _, claims = verifiedStreamCardFromToken(rawToken, sessionID, h.JWTSecret) + } + if liveSession, getErr := h.sessionMgr.GetSession(sessionID); getErr == nil { + var ok bool + session, file, fileErr, ok = h.resolveLiveStreamSession(w, r, liveSession, sessionID, userID) + if !ok { return } } else { - // Do not turn an inconsistent backend read into authority to reconstruct - // from a recipe whose route was never checked against a clean miss. - loadCard = nil - } - session, status, _ := h.TM.LoadOrReconstructSessionDetail(r.Context(), h.sessionMgr.GetSession, sessionID, userID, loadCard) - switch status { - case playback.SessionMissing: - writePlaybackSessionNotFound(w) - return - case playback.SessionLoadFailed: - writeError(w, http.StatusInternalServerError, "internal_error", "Failed to load playback session") - return - case playback.SessionForbidden: - writeError(w, http.StatusForbidden, "forbidden", "Session belongs to another user") - return - case playback.SessionUnauthorized: - // Defensive against invariant drift, not a reachable path: this caller - // resolves a non-zero user before loading. Falling through would - // dereference the nil session the status carries. - writeError(w, http.StatusUnauthorized, "unauthorized", "Authentication required") - return - } - if !requireNativeSessionAPIEgressV3(w, session) { - return - } - if !requireOwningProfile(w, r, session) { - return + var ok bool + session, claims, file, fileErr, ok = h.resolveReconstructedStreamSession(w, r, sessionID, userID, getErr, claims) + if !ok { + return + } } - file, err := h.fileResolver.GetByID(r.Context(), session.MediaFileID) - if err != nil { - if isPlaybackFileLookupMissing(err) { + if fileErr != nil { + if isPlaybackFileLookupMissing(fileErr) { h.abortPlaybackSession(r.Context(), session) writeError(w, http.StatusNotFound, "not_found", "Media file not found") return diff --git a/internal/api/handlers/stream_session_resolve.go b/internal/api/handlers/stream_session_resolve.go new file mode 100644 index 00000000000..b2bf5ec9cd5 --- /dev/null +++ b/internal/api/handlers/stream_session_resolve.go @@ -0,0 +1,115 @@ +package handlers + +import ( + "errors" + "net/http" + "sync" + + apimw "github.com/Silo-Server/silo-server/internal/api/middleware" + "github.com/Silo-Server/silo-server/internal/models" + "github.com/Silo-Server/silo-server/internal/playback" + "github.com/Silo-Server/silo-server/internal/streamtoken" +) + +func (h *StreamHandler) rejectLiveStreamMismatch(w http.ResponseWriter, r *http.Request, liveSession *playback.Session, sessionID string, userID int) bool { + if h.StreamDeny.Denied(r.Context(), sessionID) { + writeDeniedPlaybackSession(w, r, h.PlanStoreV3, sessionID) + return true + } + if liveSession.UserID != userID { + writeError(w, http.StatusForbidden, "forbidden", "Session belongs to another user") + return true + } + if !requireNativeSessionAPIEgressV3(w, liveSession) { + return true + } + return !requireOwningProfile(w, r, liveSession) +} + +func (h *StreamHandler) resolveLiveStreamSession(w http.ResponseWriter, r *http.Request, liveSession *playback.Session, sessionID string, userID int) (*playback.Session, *models.MediaFile, error, bool) { + profileID := apimw.GetProfileID(r.Context()) + profileMismatch := profileID != "" && liveSession.ProfileID != "" && profileID != liveSession.ProfileID + egressStatus := nativeAPIEgressStatusV3(liveSession.RoutingWorkload, liveSession.RoutingExecution, liveSession.RoutingEgress) + if (liveSession.UserID != userID || egressStatus != 0 || profileMismatch) && + h.rejectLiveStreamMismatch(w, r, liveSession, sessionID, userID) { + return nil, nil, nil, false + } + var ( + denied bool + file *models.MediaFile + fileErr error + wg sync.WaitGroup + ) + wg.Add(2) + go func() { + defer wg.Done() + denied = h.StreamDeny.Denied(r.Context(), sessionID) + }() + go func() { + defer wg.Done() + if h.fileResolver != nil { + file, fileErr = h.fileResolver.GetByID(r.Context(), liveSession.MediaFileID) + } + }() + wg.Wait() + if denied { + writeDeniedPlaybackSession(w, r, h.PlanStoreV3, sessionID) + return nil, nil, nil, false + } + return liveSession, file, fileErr, true +} + +func (h *StreamHandler) loadReconstructCardForStream(w http.ResponseWriter, r *http.Request, sessionID string, userID int) (*playback.RecipeCard, *streamtoken.Claims, bool) { + loadCard, verifiedClaims := verifiedStreamCardFromToken(r.URL.Query().Get(streamTokenParam), sessionID, h.JWTSecret) + if loadCard == nil { + var recipeErr error + loadCard, recipeErr = h.storedSessionRecipeV3(r.Context(), sessionID, userID) + if recipeErr != nil { + writeError(w, http.StatusInternalServerError, "internal_error", "Failed to load playback session") + return nil, verifiedClaims, false + } + } + if !requireNativeRecipeAPIEgressV3(w, loadCard) { + return nil, verifiedClaims, false + } + return loadCard, verifiedClaims, true +} + +func (h *StreamHandler) resolveReconstructedStreamSession(w http.ResponseWriter, r *http.Request, sessionID string, userID int, getErr error, claims *streamtoken.Claims) (*playback.Session, *streamtoken.Claims, *models.MediaFile, error, bool) { + if h.StreamDeny.Denied(r.Context(), sessionID) { + writeDeniedPlaybackSession(w, r, h.PlanStoreV3, sessionID) + return nil, claims, nil, nil, false + } + // Reconstruct from recipe card on a not-found miss (e.g. after restart). + var loadCard *playback.RecipeCard + if errors.Is(getErr, playback.ErrSessionNotFound) { + var ok bool + loadCard, claims, ok = h.loadReconstructCardForStream(w, r, sessionID, userID) + if !ok { + return nil, claims, nil, nil, false + } + } + session, status, _ := h.TM.LoadOrReconstructSessionDetail(r.Context(), h.sessionMgr.GetSession, sessionID, userID, loadCard) + switch status { + case playback.SessionMissing: + writePlaybackSessionNotFound(w) + return nil, claims, nil, nil, false + case playback.SessionLoadFailed: + writeError(w, http.StatusInternalServerError, "internal_error", "Failed to load playback session") + return nil, claims, nil, nil, false + case playback.SessionForbidden: + writeError(w, http.StatusForbidden, "forbidden", "Session belongs to another user") + return nil, claims, nil, nil, false + case playback.SessionUnauthorized: + writeError(w, http.StatusUnauthorized, "unauthorized", "Authentication required") + return nil, claims, nil, nil, false + } + if !requireNativeSessionAPIEgressV3(w, session) { + return nil, claims, nil, nil, false + } + if !requireOwningProfile(w, r, session) { + return nil, claims, nil, nil, false + } + file, fileErr := h.fileResolver.GetByID(r.Context(), session.MediaFileID) + return session, claims, file, fileErr, true +} diff --git a/internal/api/middleware/viewer_access.go b/internal/api/middleware/viewer_access.go index 32392a4cb91..5375153b92f 100644 --- a/internal/api/middleware/viewer_access.go +++ b/internal/api/middleware/viewer_access.go @@ -34,6 +34,17 @@ func NewViewerAccessMiddleware(resolver ViewerResolver) *ViewerAccessMiddleware // RequireViewerAccess resolves viewer scope from auth + profile headers. func (m *ViewerAccessMiddleware) RequireViewerAccess(next http.Handler) http.Handler { + return m.requireViewerAccess(next, false) +} + +// RequireMediaViewerAccess resolves viewer scope for media delivery routes +// without loading browsing-only viewer preferences (Next Up, card overlays, +// disabled libraries, metadata language). +func (m *ViewerAccessMiddleware) RequireMediaViewerAccess(next http.Handler) http.Handler { + return m.requireViewerAccess(next, true) +} + +func (m *ViewerAccessMiddleware) requireViewerAccess(next http.Handler, skipPreferences bool) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { claims := GetClaims(r.Context()) if claims == nil { @@ -41,6 +52,7 @@ func (m *ViewerAccessMiddleware) RequireViewerAccess(next http.Handler) http.Han return } + var resolvedPolicy access.ResolvedUserPolicy profileID := r.Header.Get("X-Profile-Id") input := access.ResolveInput{ UserID: claims.UserID, @@ -55,6 +67,8 @@ func (m *ViewerAccessMiddleware) RequireViewerAccess(next http.Handler) http.Han claims.TokenType == auth.TokenTypeApplePushDisplay || claims.TokenType == auth.TokenTypeDirectDownloadLink || claims.TokenType == auth.TokenTypeStreamReference, + SkipViewerPreferences: skipPreferences, + EffectivePolicyOut: &resolvedPolicy, } scope, err := m.resolver.Resolve(r.Context(), input) @@ -101,6 +115,9 @@ func (m *ViewerAccessMiddleware) RequireViewerAccess(next http.Handler) http.Han } ctx := access.SetScope(r.Context(), scope) + if resolvedPolicy.Resolved { + ctx = access.SetResolvedUserPolicy(ctx, resolvedPolicy) + } if profileID != "" { ctx = SetProfileID(ctx, profileID) } diff --git a/internal/api/router.go b/internal/api/router.go index f3558374753..fde9d575932 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -874,6 +874,14 @@ func newChiRouter(deps Dependencies) chi.Router { } if deps.SessionMgr != nil && userRepo != nil { deps.SessionMgr.SetLimitProvider(func(ctx context.Context, userID int) (playback.SessionLimits, error) { + if effective, ok := access.GetResolvedUserPolicy(ctx, userID); ok { + return playback.SessionLimits{ + MaxStreams: effective.MaxStreams, + MaxTranscodes: effective.MaxTranscodes, + TranscodingDisabled: !effective.TranscodeAllowed, + AudioTranscodingDisabled: !effective.AudioTranscodeAllowed, + }, nil + } user, err := userRepo.GetByID(ctx, userID) if err != nil { return playback.SessionLimits{}, err diff --git a/internal/apiv2/gates.go b/internal/apiv2/gates.go index 4e0956cffd0..1465020def2 100644 --- a/internal/apiv2/gates.go +++ b/internal/apiv2/gates.go @@ -50,14 +50,15 @@ func classGate(deps Dependencies) func(huma.Context, func(huma.Context)) { profileOptional, _ := op.Metadata[metaProfileOptional].(bool) household, _ := op.Metadata[metaHouseholdGate].(bool) bucket, _ := op.Metadata[metaRateLimitBucket].(string) - chain, missing := gateChain(deps, class, permission, libraryScoped, demoRestricted, profileOptional, household, bucket) + mediaDelivery := streamReferenceOperations[op.OperationID] + chain, missing := buildGateChain(deps, class, permission, libraryScoped, demoRestricted, profileOptional, household, bucket, mediaDelivery) if op.OperationID == notificationApplePushDisplayOperation { chain, missing = notificationDisplayGateChain(deps) } if link, _ := op.Metadata[metaDirectDownloadLink].(bool); link && missing == "" { chain = directDownloadGateChain(deps, chain) } - if streamReferenceOperations[op.OperationID] && missing == "" { + if mediaDelivery && missing == "" { chain = streamReferenceGateChain(deps, chain) } if attach, _ := op.Metadata[metaAttachSession].(bool); attach && class == ClassPublic && deps.Auth != nil { @@ -93,6 +94,10 @@ func classGate(deps Dependencies) func(huma.Context, func(huma.Context)) { // refused before any permission gate or handler sees it. The second result // names the first gate the wiring lacks. func gateChain(deps Dependencies, class Class, permission string, libraryScoped, demoRestricted, profileOptional, household bool, bucket string) ([]func(http.Handler) http.Handler, string) { + return buildGateChain(deps, class, permission, libraryScoped, demoRestricted, profileOptional, household, bucket, false) +} + +func buildGateChain(deps Dependencies, class Class, permission string, libraryScoped, demoRestricted, profileOptional, household bool, bucket string, mediaDelivery bool) ([]func(http.Handler) http.Handler, string) { if class == ClassPublic { // A public operation with a named budget runs the per-endpoint // limiter and nothing else; a missing limiter leaves it unlimited, @@ -123,9 +128,13 @@ func gateChain(deps Dependencies, class Class, permission string, libraryScoped, if household && deps.HouseholdProfile == nil { return nil, "household profile gate" } + viewerAccessGate := deps.ViewerAccess.RequireViewerAccess + if mediaDelivery { + viewerAccessGate = deps.ViewerAccess.RequireMediaViewerAccess + } switch class { case ClassProfileScoped: - chain = append(chain, deps.ViewerAccess.RequireViewerAccess) + chain = append(chain, viewerAccessGate) if !profileOptional { chain = append(chain, apimw.RequireProfile) } else if household { @@ -135,7 +144,7 @@ func gateChain(deps Dependencies, class Class, permission string, libraryScoped, if deps.ActingAdmin == nil { return nil, "acting admin" } - chain = append(chain, deps.ViewerAccess.RequireViewerAccess, apimw.RequireActingAdminWith(deps.ActingAdmin)) + chain = append(chain, viewerAccessGate, apimw.RequireActingAdminWith(deps.ActingAdmin)) case ClassPermissionGated: gate := deps.PermissionGates[permission] if libraryScoped { @@ -144,7 +153,7 @@ func gateChain(deps Dependencies, class Class, permission string, libraryScoped, if gate == nil { return nil, "permission " + permission } - chain = append(chain, deps.ViewerAccess.RequireViewerAccess) + chain = append(chain, viewerAccessGate) if household { chain = append(chain, deps.HouseholdProfile) } diff --git a/internal/httpstream/compress.go b/internal/httpstream/compress.go index dcbeb1bc855..712413dfcf9 100644 --- a/internal/httpstream/compress.go +++ b/internal/httpstream/compress.go @@ -16,7 +16,8 @@ import ( // listener names none. HLS playlists and SRT/ASS subtitles are deliberately // absent: their handlers state Content-Length, and a ranged reader such as // AetherEngine on Apple platforms opens a length-less 200 as a non-seekable -// stream. +// stream. Playlists are gzipped by playback.WriteHLSManifest instead, which +// holds the whole body and states its encoded length. var defaultCompressibleTypes = []string{ "text/html", "text/css", @@ -158,11 +159,53 @@ func (b *heldBody) Write(p []byte) (int, error) { // malformed weight is ignored (RFC 9110 12.5.3). A missing or empty field gets // identity. identityRefused reports a field that weights identity q=0. func negotiate(values []string) (best *coding, identityRefused bool) { - var weights [len(codings)]float64 + weights, star, identity := acceptWeights(values) + bestQ := 0.0 + for i, q := range weights { + if q < 0 { + q = star + } + if q > bestQ { + best, bestQ = codings[i], q + } + } + if identity < 0 { + identity = star + } + if identity > bestQ { + best = nil + } + return best, identity == 0 +} + +// AcceptsGzip reports whether Accept-Encoding field lines admit a gzip body +// over identity, by the rules negotiate applies: a positive gzip weight (named, +// as x-gzip, or through `*`) that identity does not outweigh. It is for a +// handler that encodes one body itself and can offer only gzip. +func AcceptsGzip(values []string) bool { + weights, star, identity := acceptWeights(values) + gzipQ := -1.0 + for i, c := range codings { + if c.name == codingGzip { + gzipQ = weights[i] + } + } + if gzipQ < 0 { + gzipQ = star + } + if identity < 0 { + identity = star + } + return gzipQ > 0 && identity <= gzipQ +} + +// acceptWeights reads Accept-Encoding field lines into a weight per offered +// coding, the `*` weight, and the identity weight; -1 marks one not named. +func acceptWeights(values []string) (weights [len(codings)]float64, star, identity float64) { for i := range weights { weights[i] = -1 } - star, identity := -1.0, -1.0 + star, identity = -1.0, -1.0 for _, value := range values { for element := range strings.SplitSeq(value, ",") { name, params, _ := strings.Cut(element, ";") @@ -186,22 +229,7 @@ func negotiate(values []string) (best *coding, identityRefused bool) { } } } - bestQ := 0.0 - for i, q := range weights { - if q < 0 { - q = star - } - if q > bestQ { - best, bestQ = codings[i], q - } - } - if identity < 0 { - identity = star - } - if identity > bestQ { - best = nil - } - return best, identity == 0 + return weights, star, identity } // qValue reads the weight from an element's parameters: 1 when it has none, diff --git a/internal/httpstream/compress_test.go b/internal/httpstream/compress_test.go index d42d1df4ea0..b9a6be6668e 100644 --- a/internal/httpstream/compress_test.go +++ b/internal/httpstream/compress_test.go @@ -226,3 +226,25 @@ func decodeBody(coding string, b []byte) (string, error) { out, err := io.ReadAll(r) return string(out), err } + +func TestAcceptsGzipNegotiatesLikeTheCompressor(t *testing.T) { + cases := []struct { + values []string + want bool + }{ + {nil, false}, + {[]string{"gzip, deflate, br"}, true}, + {[]string{"x-gzip"}, true}, + {[]string{"*"}, true}, + {[]string{"gzip;q=0, identity"}, false}, + {[]string{"gzip;q=0.5, identity;q=1"}, false}, + {[]string{"gzip;q=abc"}, false}, + {[]string{"deflate", "gzip"}, true}, + {[]string{"identity"}, false}, + } + for _, tc := range cases { + if got := AcceptsGzip(tc.values); got != tc.want { + t.Errorf("AcceptsGzip(%q) = %v, want %v", tc.values, got, tc.want) + } + } +} diff --git a/internal/nodeauth/nodeauth.go b/internal/nodeauth/nodeauth.go index 454e46fa303..4ccc4fb2245 100644 --- a/internal/nodeauth/nodeauth.go +++ b/internal/nodeauth/nodeauth.go @@ -32,6 +32,7 @@ import ( "net/url" "strconv" "strings" + "sync" "sync/atomic" "time" ) @@ -361,14 +362,45 @@ func workerPath(target *url.URL, nodeURL string) string { return path } +type hkdfKeyCacheEntry struct { + label string + secret string +} + +var ( + hkdfKeyCache sync.Map + hkdfKeyCacheCount atomic.Int32 +) + +func derivedMACKey(label, secret string) ([]byte, error) { + cacheKey := hkdfKeyCacheEntry{label: label, secret: secret} + if cached, ok := hkdfKeyCache.Load(cacheKey); ok { + if keyBytes, ok := cached.([]byte); ok { + return keyBytes, nil + } + } + key, err := hkdf.Key(sha256.New, []byte(secret), nil, label, sha256.Size) + if err != nil { + return nil, fmt.Errorf("node auth: derive key: %w", err) + } + if hkdfKeyCacheCount.Load() >= 256 { + hkdfKeyCache.Clear() + hkdfKeyCacheCount.Store(0) + } + if _, loaded := hkdfKeyCache.LoadOrStore(cacheKey, key); !loaded { + hkdfKeyCacheCount.Add(1) + } + return key, nil +} + // requestMAC signs the canonical form of one request in direction dir. An // empty path is the root, which is what a client puts on the wire for it. In a // direction that signs the source grant, the SourceGrantHeader value in header // (empty when absent) is the last line; header values cannot hold a newline. func requestMAC(dir direction, secret, timestamp, method, path, rawQuery, bodyHash string, header http.Header) ([]byte, error) { - key, err := hkdf.Key(sha256.New, []byte(secret), nil, dir.label, sha256.Size) + key, err := derivedMACKey(dir.label, secret) if err != nil { - return nil, fmt.Errorf("node auth: derive key: %w", err) + return nil, err } if path == "" { path = "/" diff --git a/internal/nodecontrol/client.go b/internal/nodecontrol/client.go index ab00883a027..e641da66a6a 100644 --- a/internal/nodecontrol/client.go +++ b/internal/nodecontrol/client.go @@ -57,13 +57,28 @@ func NewClient(coreURL, nodeKey string) (*Client, error) { } noRedirect := func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } return &Client{coreURL: coreURL, nodeID: nodeID, key: nodeKey, http: &http.Client{ - Timeout: requestTimeout, + Transport: controlTransport(), + Timeout: requestTimeout, // A redirect would send the signed request somewhere it was not // signed for. CheckRedirect: noRedirect, }, sources: &http.Client{Transport: sourceTransport(), CheckRedirect: noRedirect}}, nil } +// controlTransport keeps a warm pool of connections to the core for control +// calls (resolve, sources/open, reports, config) instead of sharing +// http.DefaultTransport's 2-idle-connection-per-host limit. +func controlTransport() http.RoundTripper { + base, ok := http.DefaultTransport.(*http.Transport) + if !ok { + return http.DefaultTransport + } + t := base.Clone() + t.DialContext = nodepool.NodeDialContext() + t.MaxIdleConnsPerHost = 32 + return t +} + // sourceTransport is the transport of source byte reads: straight to the // core, never through a proxy, asking for no compression, with an answer due // within requestTimeout and enough pooled connections for the reads a busy diff --git a/internal/nodepool/health.go b/internal/nodepool/health.go index d73f6efe0d6..c5cd34c2e9d 100644 --- a/internal/nodepool/health.go +++ b/internal/nodepool/health.go @@ -168,9 +168,19 @@ func CheckNodeReport(ctx context.Context, n *Node) HealthReport { return report } +var healthCheckClient = func() *http.Client { + base, ok := http.DefaultTransport.(*http.Transport) + if !ok { + base = &http.Transport{} + } + t := base.Clone() + t.DialContext = NodeDialContext() + t.MaxIdleConnsPerHost = 32 + return &http.Client{Transport: t, Timeout: 5 * time.Second, CheckRedirect: RefuseRedirects} +}() + func checkNodeReport(ctx context.Context, n *Node) HealthReport { unreachable := HealthReport{DrainState: DrainStateNone, Reason: UnhealthyUnreachable} - client := &http.Client{Timeout: 5 * time.Second, CheckRedirect: RefuseRedirects} ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() @@ -179,7 +189,7 @@ func checkNodeReport(ctx context.Context, n *Node) HealthReport { return unreachable } - resp, err := client.Do(req) + resp, err := healthCheckClient.Do(req) if err != nil { return unreachable } diff --git a/internal/playback/candidate_routes_v3.go b/internal/playback/candidate_routes_v3.go index 1a1f1809130..06b538ea974 100644 --- a/internal/playback/candidate_routes_v3.go +++ b/internal/playback/candidate_routes_v3.go @@ -92,7 +92,7 @@ func convertRemuxAudioV3(plan *PlanV3, channels int, reason, message string) { func (p *candidatePlannerV3) progressiveCandidate(c candidateV3) *PlannerResultV3 { f, a, request, source := &p.video, &p.video.remuxAudio, p.input.Request, p.source - if !f.remuxSubtitleOK || c.video == candidateServerStripV3 && !f.stripProgressive { + if !f.remuxActive || !f.remuxSubtitleOK || c.video == candidateServerStripV3 && !f.stripProgressive { return nil } channels := 0 @@ -123,7 +123,7 @@ func (p *candidatePlannerV3) progressiveCandidate(c candidateV3) *PlannerResultV func (p *candidatePlannerV3) hlsRemuxCandidate(c candidateV3) *PlannerResultV3 { f, a, request, source := &p.video, &p.video.remuxAudio, p.input.Request, p.source - if !deliveryAvailableV3(request, DeliveryClassHLSV3) || !f.hlsSubtitleOK || c.video == candidateServerStripV3 && !f.stripHLS || + if !f.remuxActive || !deliveryAvailableV3(request, DeliveryClassHLSV3) || !f.hlsSubtitleOK || c.video == candidateServerStripV3 && !f.stripHLS || a.hlsConverts && !audioRemuxFitsServerCapV3(p.input, p.file, a.hlsAACChannels) { return nil } diff --git a/internal/playback/candidate_video_v3.go b/internal/playback/candidate_video_v3.go index c79376383ab..a2e10f1a0fb 100644 --- a/internal/playback/candidate_video_v3.go +++ b/internal/playback/candidate_video_v3.go @@ -24,6 +24,7 @@ type videoFactsV3 struct { audioOK, originalAudioOK, noAudioTrack bool audioClaims AudioClaimsV3 stripProgressive, stripHLS bool + stripDeferred bool clientDV81, clientHDR10, serverDV81 bool base PlanV3 // mustAdapt means no route that copies the video can work. @@ -136,30 +137,66 @@ func (p *candidatePlannerV3) videoFacts() *PlannerResultV3 { // dolbyVisionFacts settles which Dolby Vision conversions are open. Each // delivery asks its own executor pool, and the RPU probe runs only once one -// of them offers the strip. It reports a strip the source itself cannot take. +// of them offers the strip. When the client can already play the original +// file's dynamic range, strip probing is deferred until a copy-remux route is +// actually entered so direct plays never pay for an FFmpeg bitstream probe. +// It reports a strip the source itself cannot take. func (p *candidatePlannerV3) dolbyVisionFacts() bool { in, source, f := p.input, p.source, &p.video request := in.Request hlsOK := deliveryAvailableV3(request, DeliveryClassHLSV3) - if source.DynamicRange == DynamicRangeDolbyVisionV3 && clientSupportsHDR10V3(request, source) && - (source.DVProfile == 7 || source.DVProfile == 8 && source.DVBLCompatID == 1) { - if deliveryAvailableV3(request, DeliveryClassProgressiveV3) { - f.stripProgressive = canStripDolbyVisionToHDR10V3(source, request, in.progressiveRemuxRegistry()) - } - if hlsOK { - f.stripHLS = canStripDolbyVisionToHDR10V3(source, request, in.hlsRemuxRegistry()) - } + f.clientDV81 = canClientTransformDV7ToDV81V3(source, request) + f.serverDV81 = hlsOK && canServerConvertDV7ToDV81V3(source, p.file, request, in.hlsRemuxRegistry) + f.clientHDR10 = canClientTransformDV7ToHDR10V3(source, request) + stripEligible := source.DynamicRange == DynamicRangeDolbyVisionV3 && clientSupportsHDR10V3(request, source) && + (source.DVProfile == 7 || source.DVProfile == 8 && source.DVBLCompatID == 1) + if !stripEligible { + return false + } + if f.originalRangeOK() || f.clientDV81 || f.clientHDR10 { + f.stripDeferred = deliveryAvailableV3(request, DeliveryClassProgressiveV3) || hlsOK + return false + } + return p.probeDVStripCapabilities() +} + +func (p *candidatePlannerV3) probeDVStripCapabilities() bool { + in, source, f := p.input, p.source, &p.video + request := in.Request + if deliveryAvailableV3(request, DeliveryClassProgressiveV3) { + f.stripProgressive = canStripDolbyVisionToHDR10V3(source, request, in.progressiveRemuxRegistry()) + } + if deliveryAvailableV3(request, DeliveryClassHLSV3) { + f.stripHLS = canStripDolbyVisionToHDR10V3(source, request, in.hlsRemuxRegistry()) } stripUnsupported := (f.stripProgressive || f.stripHLS) && !in.dvRPUStrippable() if stripUnsupported { f.stripProgressive, f.stripHLS = false, false } - f.clientDV81 = canClientTransformDV7ToDV81V3(source, request) - f.serverDV81 = hlsOK && canServerConvertDV7ToDV81V3(source, p.file, request, in.hlsRemuxRegistry) - f.clientHDR10 = canClientTransformDV7ToHDR10V3(source, request) return stripUnsupported } +func (p *candidatePlannerV3) resolveDeferredDVStrip() { + f := &p.video + if !f.stripDeferred { + return + } + f.stripDeferred = false + if !f.remuxActive { + return + } + if p.probeDVStripCapabilities() { + f.base.DegradationWarnings = append(f.base.DegradationWarnings, DegradationWarningV3{Code: "dolby_vision_strip_unsupported_by_source", Message: "This source's Dolby Vision metadata cannot be removed cleanly, so the validated HDR10 route is unavailable for it."}) + } + remuxRangeOK := f.rangeOK && p.source.DVProfile != 7 || f.serverDV81 + f.remuxActive = !f.mustAdapt && !f.sourceFailsOnClient && (remuxRangeOK || f.stripProgressive || f.stripHLS) && + (f.remuxSubtitleOK || f.hlsSubtitleOK) + if !f.remuxActive { + anySubtitle := f.originalSubtitleOK || f.remuxSubtitleOK || f.hlsSubtitleOK + p.transcodeStageFacts(f.evidenceInsufficient, anySubtitle) + } +} + func (p *candidatePlannerV3) videoBase(videoClaims VideoClaimsV3, passthrough, stripUnsupported bool) { f := &p.video // Every delivery's policy addresses the same selected track. @@ -209,7 +246,7 @@ func (p *candidatePlannerV3) routeFacts(evidenceInsufficient bool) { // A remux maps only the base layer, so Profile 7 is never copied as is. remuxRangeOK := f.rangeOK && source.DVProfile != 7 || f.serverDV81 f.sourceFailsOnClient = source.VideoCopyUnsafe && strictParameterSetWebV3(in.Request) - f.remuxActive = !f.mustAdapt && !f.sourceFailsOnClient && (remuxRangeOK || f.stripProgressive || f.stripHLS) && + f.remuxActive = !f.mustAdapt && !f.sourceFailsOnClient && (remuxRangeOK || f.stripProgressive || f.stripHLS || f.stripDeferred) && (f.remuxSubtitleOK || f.hlsSubtitleOK) if f.remuxActive { p.remuxAudioFacts() @@ -302,7 +339,7 @@ func (p *candidatePlannerV3) videoCandidates() []candidateV3 { } add(candidateV3{route: candidateSurroundBitstreamV3, video: candidateCopyV3, audio: candidateAudioConvertV3, delivery: candidateHLSV3}, len(p.surroundBitstreamCodecs()) > 0, sidecar...) if f.remuxActive { - strip := f.stripProgressive || f.stripHLS + strip := f.stripProgressive || f.stripHLS || f.stripDeferred a := &f.remuxAudio for video, ok := range map[candidateVideoV3]bool{ candidateServerDV81V3: f.serverDV81, @@ -323,6 +360,9 @@ func (p *candidatePlannerV3) videoCandidates() []candidateV3 { // enterVideoRoute holds the refusals that end planning between routes. func (p *candidatePlannerV3) enterVideoRoute(route candidateRouteV3) *PlannerResultV3 { + if route == candidateRemuxV3 { + p.resolveDeferredDVStrip() + } a := &p.video.remuxAudio switch { case !p.video.remuxActive: diff --git a/internal/playback/copy_seek_anchor.go b/internal/playback/copy_seek_anchor.go index 544e578e308..2274897db5d 100644 --- a/internal/playback/copy_seek_anchor.go +++ b/internal/playback/copy_seek_anchor.go @@ -8,6 +8,7 @@ import ( "math" "strconv" "strings" + "sync" "time" "golang.org/x/sync/singleflight" @@ -16,13 +17,25 @@ import ( ) const ( - maxConcurrentCopySeekProbes = 4 - copySeekProbeTimeout = 15 * time.Second + maxConcurrentCopySeekProbes = 4 + copySeekProbeTimeout = 15 * time.Second + maxCopySeekAnchorCacheEntries = 2048 ) +type copySeekAnchorCacheKey struct { + ffmpegPath string + inputPath string + fileSize int64 + modTimeNS int64 + seekMillis int64 + segmentDuration int +} + var ( - copySeekProbeGroup singleflight.Group - copySeekProbeSlots = make(chan struct{}, maxConcurrentCopySeekProbes) + copySeekProbeGroup singleflight.Group + copySeekProbeSlots = make(chan struct{}, maxConcurrentCopySeekProbes) + copySeekAnchorCacheMu sync.RWMutex + copySeekAnchorCache = map[copySeekAnchorCacheKey]copySeekAnchor{} ) type copySeekAnchor struct { @@ -60,6 +73,25 @@ func ResolveCopySeekAnchor( } resolvedFFmpegPath := ResolveFFmpegPath(ffmpegPath) + var cacheKey copySeekAnchorCacheKey + canCache := false + if info, statErr := fspath.StatContext(ctx, inputPath); statErr == nil && info != nil { + cacheKey = copySeekAnchorCacheKey{ + ffmpegPath: resolvedFFmpegPath, + inputPath: inputPath, + fileSize: info.Size(), + modTimeNS: info.ModTime().UnixNano(), + seekMillis: int64(math.Round(requestedSeekSeconds * 1000)), + segmentDuration: segmentDuration, + } + canCache = true + copySeekAnchorCacheMu.RLock() + if cached, ok := copySeekAnchorCache[cacheKey]; ok { + copySeekAnchorCacheMu.RUnlock() + return cached.seconds, cached.segment, nil + } + copySeekAnchorCacheMu.RUnlock() + } key := strings.Join([]string{ resolvedFFmpegPath, inputPath, @@ -76,7 +108,16 @@ func ResolveCopySeekAnchor( return copySeekAnchor{}, probeCtx.Err() } seconds, segment, err := resolveCopySeekAnchor(probeCtx, resolvedFFmpegPath, inputPath, requestedSeekSeconds, segmentDuration) - return copySeekAnchor{seconds: seconds, segment: segment}, err + anchor := copySeekAnchor{seconds: seconds, segment: segment} + if err == nil && canCache { + copySeekAnchorCacheMu.Lock() + if len(copySeekAnchorCache) >= maxCopySeekAnchorCacheEntries { + clear(copySeekAnchorCache) + } + copySeekAnchorCache[cacheKey] = anchor + copySeekAnchorCacheMu.Unlock() + } + return anchor, err }) select { @@ -99,11 +140,12 @@ func resolveCopySeekAnchor( segmentDuration int, ) (float64, int, error) { + analyzeDuration, probeSize := inputProbeBudget(inputPath, false) cmd := fspath.CommandContext(ctx, ffmpegPath, "-v", "error", "-fflags", "+genpts+fastseek", - "-analyzeduration", "3000000", - "-probesize", "5000000", + "-analyzeduration", analyzeDuration, + "-probesize", probeSize, "-ss", fmt.Sprintf("%.3f", requestedSeekSeconds), "-i", inputPath, // Match the remux transport's 0:V:0 map. Uppercase V excludes attached diff --git a/internal/playback/manifest_http.go b/internal/playback/manifest_http.go new file mode 100644 index 00000000000..a9659fe8dd5 --- /dev/null +++ b/internal/playback/manifest_http.go @@ -0,0 +1,74 @@ +package playback + +import ( + "bytes" + "compress/gzip" + "net/http" + "strconv" + + "github.com/Silo-Server/silo-server/internal/httpstream" +) + +const hlsManifestGzipMinBytes = 1024 + +// ManifestRelayAcceptEncoding returns the Accept-Encoding value a relay hop +// should send upstream for an HLS playlist so Go's http.Transport does not +// strip Content-Length via transparent decompression. +func ManifestRelayAcceptEncoding(r *http.Request) string { + if acceptsGzipEncoding(r) { + return "gzip" + } + return "identity" +} + +// WriteHLSManifest writes an in-memory HLS playlist with an explicit +// Content-Length. Playlists at or above 1 KiB are gzip-compressed in memory +// when the client advertises gzip support, preserving non-chunked framing and +// shrinking multi-thousand-segment VOD playlists by ~20x on the wire. +func WriteHLSManifest(w http.ResponseWriter, r *http.Request, manifest []byte) { + w.Header().Set("Content-Type", "application/vnd.apple.mpegurl") + // no-transform keeps proxies and CDNs from re-encoding the playlist, + // which drops the Content-Length below (Cloudflare does). + w.Header().Set("Cache-Control", "no-store, no-transform, max-age=0") + w.Header().Set("Pragma", "no-cache") + w.Header().Add("Vary", "Accept-Encoding") + + payload := manifest + if len(manifest) >= hlsManifestGzipMinBytes && acceptsGzipEncoding(r) { + if compressed, ok := gzipManifestBytes(manifest); ok && len(compressed) < len(manifest) { + w.Header().Set("Content-Encoding", "gzip") + payload = compressed + } + } + + // The playlist is complete in memory, so state its exact wire length. + // Without it a playlist past net/http's small write buffer goes out + // chunked, and a player that opens HLS sources with a ranged byte reader + // takes a length-less 200 for a non-seekable stream. + w.Header().Set("Content-Length", strconv.Itoa(len(payload))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(payload) +} + +func gzipManifestBytes(raw []byte) ([]byte, bool) { + var buf bytes.Buffer + buf.Grow(len(raw) / 8) + gz, err := gzip.NewWriterLevel(&buf, gzip.BestSpeed) + if err != nil { + return nil, false + } + if _, err := gz.Write(raw); err != nil { + _ = gz.Close() + return nil, false + } + if err := gz.Close(); err != nil { + return nil, false + } + return buf.Bytes(), true +} + +// acceptsGzipEncoding reports whether the request's Accept-Encoding admits a +// gzip playlist, negotiated as the API's response compressor negotiates. +func acceptsGzipEncoding(r *http.Request) bool { + return r != nil && httpstream.AcceptsGzip(r.Header.Values("Accept-Encoding")) +} diff --git a/internal/playback/manifest_http_test.go b/internal/playback/manifest_http_test.go new file mode 100644 index 00000000000..07985ea0511 --- /dev/null +++ b/internal/playback/manifest_http_test.go @@ -0,0 +1,75 @@ +package playback + +import ( + "compress/gzip" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" +) + +func TestWriteHLSManifestGzipAndIdentity(t *testing.T) { + var b strings.Builder + b.WriteString("#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:2\n") + for i := range 200 { + b.WriteString("#EXTINF:2.000,\nsegment/seg_") + b.WriteString(strconv.Itoa(i)) + b.WriteString(".ts\n") + } + b.WriteString("#EXT-X-ENDLIST\n") + raw := []byte(b.String()) + + t.Run("compresses large manifest when client accepts gzip with exact Content-Length", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/master.m3u8", nil) + req.Header.Set("Accept-Encoding", "gzip, deflate") + rr := httptest.NewRecorder() + + WriteHLSManifest(rr, req, raw) + + if rr.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rr.Code) + } + if got := rr.Header().Get("Content-Encoding"); got != "gzip" { + t.Fatalf("Content-Encoding = %q, want gzip", got) + } + if got := rr.Header().Get("Content-Length"); got != strconv.Itoa(rr.Body.Len()) { + t.Fatalf("Content-Length = %q, want %d", got, rr.Body.Len()) + } + if rr.Body.Len() >= len(raw)/2 { + t.Fatalf("expected strong compression, got %d bytes from %d", rr.Body.Len(), len(raw)) + } + zr, err := gzip.NewReader(rr.Body) + if err != nil { + t.Fatalf("gzip.NewReader: %v", err) + } + defer func() { _ = zr.Close() }() + decoded, err := io.ReadAll(zr) + if err != nil { + t.Fatalf("read gunzipped body: %v", err) + } + if string(decoded) != string(raw) { + t.Fatalf("decoded manifest mismatch") + } + }) + + t.Run("preserves uncompressed bytes for Accept-Encoding identity", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/master.m3u8", nil) + req.Header.Set("Accept-Encoding", "identity") + rr := httptest.NewRecorder() + + WriteHLSManifest(rr, req, raw) + + if got := rr.Header().Get("Content-Encoding"); got != "" { + t.Fatalf("Content-Encoding = %q, want empty", got) + } + if got := rr.Header().Get("Content-Length"); got != strconv.Itoa(len(raw)) { + t.Fatalf("Content-Length = %q, want %d", got, len(raw)) + } + if rr.Body.String() != string(raw) { + t.Fatalf("identity body mismatch") + } + }) + +} diff --git a/internal/playback/plan_v3_dv_strip_fallback_test.go b/internal/playback/plan_v3_dv_strip_fallback_test.go index dbdde1621ce..3aa877d3805 100644 --- a/internal/playback/plan_v3_dv_strip_fallback_test.go +++ b/internal/playback/plan_v3_dv_strip_fallback_test.go @@ -173,3 +173,46 @@ func TestPlanPlaybackV3Profile7ConvertsToDV81BeforeStrip(t *testing.T) { } } } + +func TestPlanPlaybackV3DirectPlaySkipsDVRPUProbe(t *testing.T) { + file, req := dv81NativeAndHDR10FixtureV3() + stripProbes := 0 + progRegistryLookups := 0 + hlsRegistryLookups := 0 + input := PlannerInputV3{ + Request: req, RequestedFile: file, EffectiveFile: file, AudioTrackIndex: 0, + Settings: PlannerSettingsV3{TranscodeEnabled: true, Allow4KTranscode: true}, + Registry: dvStripFallbackRegistryV3(), + ProgressiveRemuxRegistry: func() *TransformationRegistryV3 { + progRegistryLookups++ + return dvStripFallbackRegistryV3() + }, + HLSRemuxRegistry: func() *TransformationRegistryV3 { + hlsRegistryLookups++ + return dvStripFallbackRegistryV3() + }, + DVRPUStrippable: func() bool { + stripProbes++ + return true + }, + } + + direct := PlanPlaybackV3(input) + if direct.Plan == nil || direct.PlayMethod != PlayDirect || direct.Plan.Delivery != DeliveryOriginalHTTPV3 { + t.Fatalf("initial plan = %#v, terminal = %#v; want direct original_http", direct.Plan, direct.Terminal) + } + if stripProbes != 0 || progRegistryLookups != 0 || hlsRegistryLookups != 0 { + t.Fatalf("direct play eagerly probed DV strip (stripProbes=%d progReg=%d hlsReg=%d), want all 0", + stripProbes, progRegistryLookups, hlsRegistryLookups) + } + + // Once original_http has been attempted, fallback enters remux and probes RPU stripping. + input.AttemptedKeys = []string{direct.Plan.PlanAttemptKey} + fallback := PlanPlaybackV3(input) + if fallback.Plan == nil || fallback.PlayMethod != PlayRemux { + t.Fatalf("fallback plan = %#v, terminal = %#v; want remux", fallback.Plan, fallback.Terminal) + } + if stripProbes != 1 { + t.Fatalf("fallback stripProbes = %d, want 1", stripProbes) + } +} diff --git a/internal/playback/planstore/postgres.go b/internal/playback/planstore/postgres.go index 4277ce7be4c..5c838b16151 100644 --- a/internal/playback/planstore/postgres.go +++ b/internal/playback/planstore/postgres.go @@ -96,6 +96,30 @@ func (s *Postgres) SaveAttempt(ctx context.Context, record playback.AttemptRecor if err != nil { return err } + const insertAttemptSQL = ` + INSERT INTO playback_v3_attempts ( + playback_attempt_id, session_id, user_id, profile_id, + requested_media_file_id, effective_media_file_id, + current_plan_id, current_replan_request_id, current_plan, frozen_recipe, + normalized_request, start_response, request_digest, expires_at, server_bitrate_cap_kbps, + desired_tracks, login_session_id, plan_attribution + ) VALUES ($1, NULLIF($2, '')::uuid, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) + ON CONFLICT DO NOTHING` + // Fast path: brand-new attempt/session UUIDs have no conflict, so a single + // autocommit INSERT avoids three extra BEGIN/DELETE/COMMIT round trips. + fastResult, err := s.db.Exec(ctx, insertAttemptSQL, + record.PlaybackAttemptID, record.SessionID, record.UserID, record.ProfileID, + record.RequestedMediaFileID, record.EffectiveMediaFileID, + record.CurrentPlanID, record.CurrentReplanRequestID, planJSON, recipeJSON, + requestJSON, responseJSON, record.RequestDigest, record.ExpiresAt, record.ServerBitrateCapKbps, + desiredJSON, record.LoginSessionID, attributionJSON) + if err != nil { + return err + } + if fastResult.RowsAffected() > 0 { + return nil + } + tx, err := s.db.BeginTx(ctx, pgx.TxOptions{}) if err != nil { return err @@ -111,15 +135,7 @@ func (s *Postgres) SaveAttempt(ctx context.Context, record playback.AttemptRecor record.PlaybackAttemptID, record.SessionID); err != nil { return err } - result, err := tx.Exec(ctx, ` - INSERT INTO playback_v3_attempts ( - playback_attempt_id, session_id, user_id, profile_id, - requested_media_file_id, effective_media_file_id, - current_plan_id, current_replan_request_id, current_plan, frozen_recipe, - normalized_request, start_response, request_digest, expires_at, server_bitrate_cap_kbps, - desired_tracks, login_session_id, plan_attribution - ) VALUES ($1, NULLIF($2, '')::uuid, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) - ON CONFLICT DO NOTHING`, + result, err := tx.Exec(ctx, insertAttemptSQL, record.PlaybackAttemptID, record.SessionID, record.UserID, record.ProfileID, record.RequestedMediaFileID, record.EffectiveMediaFileID, record.CurrentPlanID, record.CurrentReplanRequestID, planJSON, recipeJSON, diff --git a/internal/playback/remux.go b/internal/playback/remux.go index eb00f2f4ab0..adfb4f353d9 100644 --- a/internal/playback/remux.go +++ b/internal/playback/remux.go @@ -273,8 +273,8 @@ const ( // buildRemuxArgs constructs the ffmpeg argument list for a remux operation. // The args perform codec copy (-c copy) into the target container format, -// using fragmented output for streaming (frag_keyframe+delay_moov+default_base_moof, plus -// a 2-second fragment duration for audio-only output) and pipe:1 for stdout output. +// using fragmented output for streaming (delay_moov+default_base_moof, 500 ms +// fragments, 2 s for audio-only output) and pipe:1 for stdout output. // When transcodeAudio is true, video is copied but audio is transcoded to // stereo AAC (handles cases like DTS/TrueHD that browsers cannot decode). // dvProfile is the file's Dolby Vision profile (0 = none). Profile 7 remuxes @@ -445,14 +445,9 @@ func buildRemuxArgsWithLeadingPictureDropV3(filePath, outputFormat string, seekS "-hide_banner", "-loglevel", "error", } - // Cap the input probe to speed up startup on large MKV containers - // (defaults scan up to 5 seconds / several MB). Mirrors the transcode - // pipeline, which has run these caps in production without issue. - inputFlags := []string{ - "-fflags", "+genpts+fastseek", - "-analyzeduration", "3000000", - "-probesize", "5000000", - } + // Cap the input probe where the container allows it (mirrors transcode). + analyzeDuration, probeSize := inputProbeBudget(filePath, false) + inputFlags := []string{"-fflags", "+genpts+fastseek", "-analyzeduration", analyzeDuration, "-probesize", probeSize} audioInput := 0 if primer != nil { args = append(args, inputFlags...) @@ -478,6 +473,9 @@ func buildRemuxArgsWithLeadingPictureDropV3(filePath, outputFormat string, seekS // at the requested position, which lies past it. args = append(args, "-itsoffset", strconv.FormatFloat(seekSeconds-primer.anchorSeconds, 'f', 6, 64)) } + if transcodeAudio { + args = append(args, "-threads", "1") + } args = append(args, "-i", filePath) @@ -551,6 +549,7 @@ func buildRemuxArgsWithLeadingPictureDropV3(filePath, outputFormat string, seekS "-c:a", "aac", "-ac", strconv.Itoa(channels), "-b:a", strconv.Itoa(bitrateKbps)+"k", + "-aac_coder", "fast", ) args = appendAACEncodeFilterArgs(args, sourceAudioChannels, "aac", targetAudioChannels, channels) } else { @@ -558,20 +557,23 @@ func buildRemuxArgsWithLeadingPictureDropV3(filePath, outputFormat string, seekS args = appendCopiedAACToMP4Args(args, copyAudioCodec) } + fragDuration := "500000" + if audioOnly { // no GOP to wait for; 2 s keeps a long book in fewer fragments + fragDuration = "2000000" + } args = append(args, "-avoid_negative_ts", "make_zero", "-f", outputFormat, // delay_moov lets the MP4 muxer inspect the first audio packet before // writing codec configuration. empty_moov fails immediately for copied // E-AC-3/Atmos tracks because their frame size is not known at header time. - "-movflags", "frag_keyframe+delay_moov+default_base_moof", + // Using -frag_duration (500ms) instead of frag_keyframe flushes moov and + // the first playable fragment (which starts on the initial keyframe) in + // ~100ms rather than buffering an entire 4-10s source GOP. Consumers read + // from byte 0, so a fragment may start between keyframes. + "-movflags", "delay_moov+default_base_moof", + "-frag_duration", fragDuration, ) - if audioOnly { - // frag_keyframe only cuts at video keyframes, so audio-only output - // would be one fragment that FFmpeg writes when the whole book is done. - // Cut one every 2 seconds (in microseconds) so the first audio arrives at once. - args = append(args, "-frag_duration", "2000000") - } args = append(args, "pipe:1") return args @@ -580,7 +582,7 @@ func buildRemuxArgsWithLeadingPictureDropV3(filePath, outputFormat string, seekS // StartRemux starts an ffmpeg process that copies codecs to a new container. // When transcodeAudio is false the command is: // -// ffmpeg -i {input} -c copy -f {format} -movflags frag_keyframe+delay_moov+default_base_moof pipe:1 +// ffmpeg -i {input} -c copy -f {format} -movflags delay_moov+default_base_moof -frag_duration 500000 pipe:1 // // When transcodeAudio is true video is copied but audio is transcoded to AAC. // The caller must call Close() when done to clean up resources. diff --git a/internal/playback/streamdeny.go b/internal/playback/streamdeny.go index 28ed222099c..8b6d28ba129 100644 --- a/internal/playback/streamdeny.go +++ b/internal/playback/streamdeny.go @@ -115,6 +115,10 @@ func (d *StreamDeny) Denied(ctx context.Context, sessionID string) bool { // Presence is the marker; the value only documents intent. denied = true case errors.Is(err, redis.Nil): + case ctx.Err() != nil: + // The caller went away mid-lookup, which says nothing about the + // marker. Leave it uncached so the next request reads Redis. + return false default: if d.shouldWarn() { d.logger().WarnContext(ctx, "stream deny marker lookup failed; failing open", diff --git a/internal/playback/streamdeny_test.go b/internal/playback/streamdeny_test.go index d3d03fbe520..459d55115fe 100644 --- a/internal/playback/streamdeny_test.go +++ b/internal/playback/streamdeny_test.go @@ -51,6 +51,10 @@ func (f *fakeStreamDenyClient) Get(ctx context.Context, key string) *redis.Strin f.mu.Lock() defer f.mu.Unlock() f.gets++ + if err := ctx.Err(); err != nil { + cmd.SetErr(err) + return cmd + } if f.err != nil { cmd.SetErr(f.err) return cmd @@ -225,6 +229,19 @@ func TestStreamDenyFailsOpenAndRateLimitsWarnings(t *testing.T) { } } +func TestStreamDenyLeavesAbandonedLookupsUncached(t *testing.T) { + deny, client, _, _ := newTestStreamDeny(t) + client.keys[StreamDenyKey("sid-1")] = fakeStreamDenyKey{value: "deny", ttl: MaxTokenTTL} + + abandoned, cancel := context.WithCancel(t.Context()) + cancel() + deny.Denied(abandoned, "sid-1") + + if !deny.Denied(t.Context(), "sid-1") { + t.Fatal("a lookup the caller abandoned was cached as not denied") + } +} + func TestStreamDenySweepsExpiredCacheEntries(t *testing.T) { deny, _, clock, _ := newTestStreamDeny(t) for i := range streamDenyCacheSweepAt { diff --git a/internal/playback/transcode.go b/internal/playback/transcode.go index 8759d959c79..b81389b82f3 100644 --- a/internal/playback/transcode.go +++ b/internal/playback/transcode.go @@ -13,6 +13,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "slices" "strconv" "strings" @@ -1071,6 +1072,57 @@ func ResolveToneMapExecutor(ctx context.Context, opts TranscodeOpts) (TranscodeO return opts, nil } +type primaryVideoProbeCacheKey struct { + ffprobePath string + inputPath string + fileSize int64 + modTimeNS int64 + fileHash string +} + +const maxPrimaryVideoProbeCacheEntries = 2048 + +var ( + primaryVideoProbeCacheMu sync.RWMutex + primaryVideoProbeCache = map[primaryVideoProbeCacheKey]models.VideoTrack{} +) + +func probePrimaryVideoTrackCached(ctx context.Context, ffprobePath, inputPath string, rev tonemap.SourceRevision) (models.VideoTrack, error) { + info, statErr := fspath.StatContext(ctx, inputPath) + var key primaryVideoProbeCacheKey + canCache := statErr == nil && info != nil + if canCache { + key = primaryVideoProbeCacheKey{ + ffprobePath: ffprobePath, + inputPath: inputPath, + fileSize: info.Size(), + modTimeNS: info.ModTime().UnixNano(), + fileHash: rev.FileHash, + } + primaryVideoProbeCacheMu.RLock() + cached, ok := primaryVideoProbeCache[key] + primaryVideoProbeCacheMu.RUnlock() + if ok { + return cached, nil + } + } + probeCtx, cancel := context.WithTimeout(ctx, ManifestStartupTimeout) + defer cancel() + liveTrack, err := mediaprobe.ProbePrimaryVideoTrack(probeCtx, ffprobePath, inputPath) + if err != nil { + return models.VideoTrack{}, err + } + if canCache { + primaryVideoProbeCacheMu.Lock() + if len(primaryVideoProbeCache) >= maxPrimaryVideoProbeCacheEntries { + clear(primaryVideoProbeCache) + } + primaryVideoProbeCache[key] = liveTrack + primaryVideoProbeCacheMu.Unlock() + } + return liveTrack, nil +} + // validateToneMapSource rechecks the source revision and, for ambiguous // classifications, runs the selected executor's representative-frame preflight. func validateToneMapSource(ctx context.Context, opts TranscodeOpts) error { @@ -1083,12 +1135,11 @@ func validateToneMapSource(ctx context.Context, opts TranscodeOpts) error { } return fmt.Errorf("%w: %w", ErrToneMapSourceValidationUnavailable, err) } - probeCtx, cancel := context.WithTimeout(ctx, ManifestStartupTimeout) - defer cancel() - liveTrack, err := mediaprobe.ProbePrimaryVideoTrack( - probeCtx, + liveTrack, err := probePrimaryVideoTrackCached( + ctx, mediaprobe.FFprobePathFromFFmpeg(ResolveFFmpegPath(opts.FFmpegPath)), opts.InputPath, + opts.ToneMapSourceRevision, ) if err != nil { if errors.Is(err, mediaprobe.ErrPrimaryVideoNotFound) { @@ -1168,12 +1219,23 @@ func buildFFmpegArgs(opts TranscodeOpts) []string { // Limit input probing to speed up startup, especially on network storage. // -fflags +genpts generates PTS for files with missing timestamps; // +fastseek enables faster input seeking (matches Jellyfin). + // Keyframe-planned copy keeps the wide probe whatever the container. + analyzeDuration, probeSize := inputProbeBudget(opts.InputPath, opts.copyGroupPrefix != "") args = append(args, "-fflags", "+genpts+fastseek", - "-analyzeduration", "3000000", // 3 seconds (default 5s) - "-probesize", "5000000", // 5 MB (default 5MB, explicit for clarity) + "-analyzeduration", analyzeDuration, + "-probesize", probeSize, ) + // Bound CPU decoder thread count before -i on live transcodes so FFmpeg + // does not spawn 16+ frame-threading decode workers and buffer a dozen + // decoded frames before emitting frame 0. + if !opts.preparedFileEncode { + if decodeThreads := softwareDecodeThreadLimit(opts, isVideoCopy, isAudioCopy); decodeThreads > 0 { + args = append(args, "-threads", strconv.Itoa(decodeThreads)) + } + } + // Seek before input for fast seeking. if opts.SeekSeconds > 0 { args = append(args, "-ss", fmt.Sprintf("%.3f", opts.SeekSeconds)) @@ -1604,6 +1666,86 @@ func appendHWAccelArgs(args []string, opts TranscodeOpts) []string { // delay its first segments by about 5%. const restartX264Params = "mbtree=1:rc-lookahead=10" +// fastStartX264Params removes x264's lookahead and frame-threading delay on +// fresh live starts so segment 0 flushes sooner. A fresh generation encodes +// the whole title until a seek restarts it, so only latency settings belong +// here: B-frames, adaptive quantization, and partition analysis cost bitrate +// and quality for the entire session while adding no measurable startup time. +const fastStartX264Params = "sync-lookahead=0:rc-lookahead=0:sliced-threads=1" + +// inputProbeBudget returns the -analyzeduration and -probesize for an FFmpeg +// input. Matroska and MP4 describe their tracks in the container header, so a +// tight probe avoids scanning megabytes of sparse subtitle packets before +// frame 0. MPEG transport and program streams describe a track only through +// its packets, so they keep the wide 3 s / 5 MB probe; so does wide, for +// callers that need it regardless of the container. +func inputProbeBudget(path string, wide bool) (analyzeDuration, probeSize string) { + if wide || needsWideInputProbe(path) { + return "3000000", "5000000" + } + return "500000", "500000" +} + +// needsWideInputProbe reports whether an input may carry stream parameters +// only in its packets: an MPEG transport or program stream by its extension, +// or an input whose container the path cannot tell, such as the relay URL a +// transcode node reads a source through when it lacks the media mount. +func needsWideInputProbe(path string) bool { + if strings.Contains(path, "://") { + return true + } + switch strings.ToLower(filepath.Ext(path)) { + case ".ts", ".m2ts", ".mts", ".m2t", ".trp", ".mpg", ".mpeg", ".vob", ".m2p", ".evo": + return true + default: + return false + } +} + +// softwareDecodeThreadLimit bounds FFmpeg's input decoder thread count for +// live CPU-decoded starts. On high-core hosts FFmpeg's auto-threading opens up +// to 16 frame threads that buffer ~16 decoded frames before handing frame 0 to +// the filter graph. +func softwareDecodeThreadLimit(opts TranscodeOpts, isVideoCopy, isAudioCopy bool) int { + if isVideoCopy { + if !isAudioCopy { + return 1 + } + return 0 + } + if !opts.SoftwareVideoDecode && isHardwareTranscodeBackend(opts.HWAccel) { + return 0 + } + cpus := runtime.NumCPU() + capThreads := 4 + if opts.ToneMapMode == tonemap.ModeSoftware { + capThreads = 8 + } else if h, ok := scaleTargetHeight(opts.TargetResolution); ok && h > 1080 { + capThreads = 8 + } + if cpus < capThreads { + return cpus + } + return capThreads +} + +// softwareEncodeThreadLimit bounds FFmpeg's encoder and filter thread pool on +// high-core servers while giving 4K software tone-mapping enough parallelism +// for zscale + tonemapx + sliced libx264. +func softwareEncodeThreadLimit(opts TranscodeOpts) int { + cpus := runtime.NumCPU() + capThreads := 8 + if opts.ToneMapMode == tonemap.ModeSoftware { + capThreads = 16 + } else if h, ok := scaleTargetHeight(opts.TargetResolution); ok && h > 1080 { + capThreads = 12 + } + if cpus < capThreads { + return cpus + } + return capThreads +} + // videoPreset returns an encoder-compatible preset. CPU encoders use superfast // for a fresh start, and software H.264 for its restarts too (see // restartX264Params); software HEVC restarts use veryfast. QSV stays on the @@ -1647,6 +1789,9 @@ func appendVideoArgs(args []string, opts TranscodeOpts) []string { switch { case opts.HWAccel == "qsv" && codec == transcodeCodecH264: args = append(args, "-c:v", "h264_qsv", "-preset", preset) + if !opts.preparedFileEncode { + args = append(args, "-async_depth", "1", "-bf", "0", "-look_ahead", "0") + } if hasBitrateCap { args = appendCappedVBRArgs(args, opts.TargetBitrateKbps) } else { @@ -1654,6 +1799,9 @@ func appendVideoArgs(args []string, opts TranscodeOpts) []string { } case opts.HWAccel == "qsv" && codec == transcodeCodecHEVC: args = append(args, "-c:v", "hevc_qsv", "-preset", preset) + if !opts.preparedFileEncode { + args = append(args, "-async_depth", "1", "-bf", "0") + } if hasBitrateCap { args = appendCappedVBRArgs(args, opts.TargetBitrateKbps) } else { @@ -1676,6 +1824,9 @@ func appendVideoArgs(args []string, opts TranscodeOpts) []string { } case opts.HWAccel == transcodeHWNVENC && codec == transcodeCodecH264: args = append(args, "-c:v", "h264_nvenc", "-rc:v", "vbr") + if !opts.preparedFileEncode { + args = append(args, "-preset", "p2", "-rc-lookahead", "0") + } if hasBitrateCap { args = appendCappedVBRArgs(args, opts.TargetBitrateKbps) } else { @@ -1683,6 +1834,9 @@ func appendVideoArgs(args []string, opts TranscodeOpts) []string { } case opts.HWAccel == transcodeHWNVENC && codec == transcodeCodecHEVC: args = append(args, "-c:v", "hevc_nvenc", "-rc:v", "vbr") + if !opts.preparedFileEncode { + args = append(args, "-preset", "p2", "-rc-lookahead", "0") + } if hasBitrateCap { args = appendCappedVBRArgs(args, opts.TargetBitrateKbps) } else { @@ -1712,8 +1866,20 @@ func appendVideoArgs(args []string, opts TranscodeOpts) []string { // CPU fallback — match Jellyfin's proven browser-compatible settings. // Force yuv420p to ensure 8-bit output (10-bit sources produce High 10 // Profile which browsers cannot decode via MSE). + if !opts.preparedFileEncode { + if t := softwareEncodeThreadLimit(opts); t > 0 { + ts := strconv.Itoa(t) + args = append(args, "-threads", ts) + if opts.ToneMapMode == tonemap.ModeSoftware { + args = append(args, "-filter_threads", ts) + } + } + } if codec == transcodeCodecHEVC { args = append(args, "-c:v", "libx265", "-preset", preset, "-crf", "28", "-pix_fmt", "yuv420p") + if !opts.preparedFileEncode && opts.FastStart { + args = append(args, "-x265-params", "rc-lookahead=5") + } } else { args = append(args, "-c:v", "libx264", "-preset", preset, "-crf", "23", "-pix_fmt", "yuv420p", "-profile:v", "high") @@ -1721,7 +1887,9 @@ func appendVideoArgs(args []string, opts TranscodeOpts) []string { // so libx264 picks the level from the actual output instead. if !opts.preparedFileEncode { args = append(args, "-level", "4.1") - if !opts.FastStart { + if opts.FastStart { + args = append(args, "-x264-params", fastStartX264Params) + } else { args = append(args, "-x264-params", restartX264Params) } } @@ -1892,6 +2060,9 @@ func appendToneMapExecutorFilterArgs(args []string, opts TranscodeOpts) []string func toneMapScaleFilter(opts TranscodeOpts) string { switch opts.ToneMapMode { case tonemap.ModeSoftware: + if height, ok := scaleTargetHeight(opts.TargetResolution); ok && opts.ToneMapSourceKind != tonemap.SourceDolbyVision { + return tonemap.SoftwareFilterScaled(opts.ToneMapSourceKind, opts.ToneMapFilter, height) + } filter := tonemap.SoftwareFilter(opts.ToneMapSourceKind, opts.ToneMapFilter) if scale := resolutionToScale(opts.TargetResolution); scale != "" { filter += "," + scale @@ -2207,7 +2378,7 @@ func appendAudioArgs(args []string, opts TranscodeOpts) []string { } default: channels, bitrateKbps := ResolveAACOutputV3(opts.TargetAudioChannels, opts.TargetAudioBitrateKbps) - args = append(args, "-c:a", "aac", "-b:a", strconv.Itoa(bitrateKbps)+"k", "-ac", strconv.Itoa(channels)) + args = append(args, "-c:a", "aac", "-b:a", strconv.Itoa(bitrateKbps)+"k", "-ac", strconv.Itoa(channels), "-aac_coder", "fast") args = appendAACEncodeFilterArgs(args, opts.SourceAudioChannels, opts.TargetCodecAudio, opts.TargetAudioChannels, channels) } @@ -2902,37 +3073,39 @@ func prepareSubtitleFilterInput(ctx context.Context, opts *TranscodeOpts) error return nil } -// minManifestSegments is the standard startup lead for actively encoded HLS. -// True video transcodes benefit from a larger cushion so playback does not -// outrun the encoder immediately after the first frame appears. +// minManifestSegments is the startup lead for reconstructed generations that +// do not carry FastStart. const minManifestSegments = 3 // minCopyManifestSegments is the startup lead for codec-copy sessions. -// Copying video while transcoding only audio can produce startup files far -// faster than real-time encoding, so waiting for 3 full segments adds -// unnecessary latency at playback start. -const minCopyManifestSegments = 2 - -// minFreshHardwareManifestSegments keeps one complete fragment of headroom -// after the first playable fragment. A fresh hardware encoder produces that -// window comfortably ahead of real time, while CPU encodes and reconstructed -// generations retain the larger three-fragment safety margin below. -const minFreshHardwareManifestSegments = 2 +// One complete, atomically renamed segment (plus init.mp4) already proves the +// demuxer, audio encoder, and HLS muxer are healthy and gives the player a +// full source GOP while FFmpeg copies ahead at many times real time. +const minCopyManifestSegments = 1 + +// minFreshHardwareStartupSegments is the startup lead for fresh live starts on +// a hardware encoder. Once one full 2-second segment is flushed and renamed on +// disk, hardware fallback checks have passed, and the encoder runs far enough +// ahead of real time that the player does not catch up with it. +const minFreshHardwareStartupSegments = 1 + +// minFreshSoftwareStartupSegments keeps one segment of headroom for a fresh +// CPU encode. A heavy CPU encode (4K tone mapping, bitmap burn-in) runs close +// to real time, so with a one-segment lead the player would stall on the next +// segments instead of waiting a little longer for the first frame. +const minFreshSoftwareStartupSegments = 2 func startupSegmentRequirement(opts TranscodeOpts) int { if strings.EqualFold(opts.TargetCodecVideo, "copy") { return minCopyManifestSegments } - if opts.FastStart { - switch opts.HWAccel { - case transcodeHWQSV, transcodeHWVAAPI, transcodeHWNVENC: - if bitmapBurnInActive(opts) { - return 1 - } - return minFreshHardwareManifestSegments - } + if !opts.FastStart { + return minManifestSegments + } + if isHardwareTranscodeBackend(opts.EffectiveEncoderHWAccel()) { + return minFreshHardwareStartupSegments } - return minManifestSegments + return minFreshSoftwareStartupSegments } // GetManifest returns the HLS m3u8 manifest content. @@ -3048,7 +3221,9 @@ func sameManifestFile(current, inherited os.FileInfo) bool { // segment into place or rewrites the playlist, so a finished file can go // unnoticed for up to one interval. Every transcoded startup and seek waits on // output at least once. A check opens or stats one file, or reads the playlist -// and stats its startup segments, so a short interval costs little. +// and stats its startup segments, so a short interval costs little. It drives +// every segment wait for the life of a session, not only startup, so it stays +// at 10 ms. const outputPollInterval = 10 * time.Millisecond // WaitForManifest polls until the manifest is ready for playback or the timeout diff --git a/internal/playback/transcode_args_test.go b/internal/playback/transcode_args_test.go index 6bb8d7e3fdf..260d2ecc190 100644 --- a/internal/playback/transcode_args_test.go +++ b/internal/playback/transcode_args_test.go @@ -592,8 +592,8 @@ var buildFFmpegArgsEmitsRecipeTokensCases = []ffmpegArgsTokenCase{ InputPath: "/media/movie.mkv", OutputDir: "/tmp/out", SessionID: "session-start", TargetCodecVideo: "h264", TargetCodecAudio: "aac", SegmentDuration: 2, HWAccel: HWAccelNone, FastStart: true, TargetResolution: "1080p", TargetBitrateKbps: 6000, }, - want: []string{"-c:v libx264 -preset superfast -crf 23", "-level 4.1 -maxrate 6000k"}, - forbid: []string{"-x264-params"}, + want: []string{"-c:v libx264 -preset superfast -crf 23", "-level 4.1 -x264-params sync-lookahead=0:rc-lookahead=0:sliced-threads=1 -maxrate 6000k"}, + forbid: []string{"mbtree=1:rc-lookahead=10"}, }, { // The player waits on a seek restart as on a fresh start, so software @@ -1434,3 +1434,38 @@ func TestResolveBitmapSubtitleFitPinsTheStart(t *testing.T) { t.Fatalf("a start that resolved the plain overlay switched to the fitted graph:\n%s", graph) } } + +func TestQSVLiveStartupFlagsOmittedForPreparedEncode(t *testing.T) { + for _, tc := range []struct { + codec string + want []string + }{ + {codec: transcodeCodecH264, want: []string{"-c:v h264_qsv", "-async_depth 1", "-bf 0", "-look_ahead 0"}}, + {codec: transcodeCodecHEVC, want: []string{"-c:v hevc_qsv", "-async_depth 1", "-bf 0"}}, + } { + t.Run(tc.codec, func(t *testing.T) { + live := strings.Join(buildFFmpegArgs(TranscodeOpts{ + InputPath: "/media/movie.mkv", OutputDir: t.TempDir(), + SourceVideoCodec: "h264", TargetCodecVideo: tc.codec, TargetCodecAudio: "aac", + HWAccel: transcodeHWQSV, + }), " ") + for _, token := range tc.want { + if !strings.Contains(live, token) { + t.Fatalf("live QSV args missing %q:\n%s", token, live) + } + } + if tc.codec == transcodeCodecHEVC && strings.Contains(live, "-look_ahead") { + t.Fatalf("hevc_qsv does not accept -look_ahead:\n%s", live) + } + + prepared := strings.Join(appendVideoArgs(nil, TranscodeOpts{ + TargetCodecVideo: tc.codec, HWAccel: transcodeHWQSV, preparedFileEncode: true, + }), " ") + for _, forbid := range []string{"-async_depth", "-bf 0", "-look_ahead"} { + if strings.Contains(prepared, forbid) { + t.Fatalf("prepared-file QSV encode unexpectedly included %q:\n%s", forbid, prepared) + } + } + }) + } +} diff --git a/internal/playback/transcode_manager.go b/internal/playback/transcode_manager.go index e244622870e..788293830d6 100644 --- a/internal/playback/transcode_manager.go +++ b/internal/playback/transcode_manager.go @@ -1479,6 +1479,7 @@ var remoteTranscodeControlClient = func() *http.Client { } transport := base.Clone() transport.DialContext = nodepool.NodeDialContext() + transport.MaxIdleConnsPerHost = 32 return &http.Client{Transport: transport, CheckRedirect: nodepool.RefuseRedirects} }() diff --git a/internal/playback/transcode_manifest_test.go b/internal/playback/transcode_manifest_test.go index c4582c9ea2c..34587402c59 100644 --- a/internal/playback/transcode_manifest_test.go +++ b/internal/playback/transcode_manifest_test.go @@ -34,13 +34,14 @@ func TestStartupSegmentRequirementScopesFastHardwareWindowsToFreshGenerations(t want int }{ {name: "fresh hardware bitmap burn in", opts: func() TranscodeOpts { o := bitmap; o.HWAccel = transcodeHWQSV; return o }(), want: 1}, - {name: "CPU bitmap burn in", opts: func() TranscodeOpts { o := bitmap; o.HWAccel = HWAccelNone; return o }(), want: 3}, + {name: "CPU bitmap burn in", opts: func() TranscodeOpts { o := bitmap; o.HWAccel = HWAccelNone; return o }(), want: 2}, {name: "reconstructed hardware bitmap burn in", opts: func() TranscodeOpts { o := bitmap; o.HWAccel = transcodeHWQSV; o.FastStart = false; return o }(), want: 3}, - {name: "ordinary fresh hardware transcode", opts: TranscodeOpts{TargetCodecVideo: "h264", HWAccel: transcodeHWQSV, FastStart: true}, want: 2}, + {name: "ordinary fresh hardware transcode", opts: TranscodeOpts{TargetCodecVideo: "h264", HWAccel: transcodeHWQSV, FastStart: true}, want: 1}, {name: "ordinary hardware restart", opts: TranscodeOpts{TargetCodecVideo: "h264", HWAccel: transcodeHWQSV, FastStart: false}, want: 3}, - {name: "ordinary CPU transcode", opts: TranscodeOpts{TargetCodecVideo: "h264", HWAccel: HWAccelNone, FastStart: true}, want: 3}, - {name: "unknown backend falls back to CPU", opts: TranscodeOpts{TargetCodecVideo: "h264", HWAccel: "stale-backend", FastStart: true}, want: 3}, - {name: "copy video", opts: TranscodeOpts{TargetCodecVideo: "copy", HWAccel: transcodeHWQSV, FastStart: true}, want: 2}, + {name: "ordinary CPU transcode", opts: TranscodeOpts{TargetCodecVideo: "h264", HWAccel: HWAccelNone, FastStart: true}, want: 2}, + {name: "GPU tone map with a CPU encoder", opts: TranscodeOpts{TargetCodecVideo: "h264", HWAccel: transcodeHWQSV, EncoderHWAccel: HWAccelNone, FastStart: true}, want: 2}, + {name: "unknown backend falls back to CPU", opts: TranscodeOpts{TargetCodecVideo: "h264", HWAccel: "stale-backend", FastStart: true}, want: 2}, + {name: "copy video", opts: TranscodeOpts{TargetCodecVideo: "copy", HWAccel: transcodeHWQSV, FastStart: true}, want: 1}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/playback/transformations_v3.go b/internal/playback/transformations_v3.go index 8e9ddc9af42..23b5520d6bf 100644 --- a/internal/playback/transformations_v3.go +++ b/internal/playback/transformations_v3.go @@ -7,6 +7,7 @@ import ( "os/exec" "sort" "strings" + "sync" "time" "github.com/Silo-Server/silo-server/internal/procgroup" @@ -52,20 +53,71 @@ func ProbeTransformationRegistryWithToneMapV3Result(ctx context.Context, ffmpegP // Resolve exactly like the execution paths (remux and transcode) so every // capability advertised here holds for the binary that later runs. ffmpegPath = ResolveFFmpegPath(ffmpegPath) - bsfCtx, cancelBSF := context.WithTimeout(ctx, 3*time.Second) - bsfs, bsfErr := procgroup.CommandContext(bsfCtx, ffmpegPath, "-hide_banner", "-bsfs").Output() - bsfContextErr := bsfCtx.Err() - cancelBSF() - encoderCtx, cancelEncoders := context.WithTimeout(ctx, 3*time.Second) - encoders, encoderErr := procgroup.CommandContext(encoderCtx, ffmpegPath, "-hide_banner", "-encoders").Output() - encoderContextErr := encoderCtx.Err() - cancelEncoders() - normalizeRecipeErr, normalizeRecipeContextErr := probeAudioRecipeFilterV3(ctx, ffmpegPath, "stereo", aacTimestampNormalizeFilterV3) - downmixRecipeErr, downmixRecipeContextErr := probeAudioRecipeFilterV3(ctx, ffmpegPath, "5.1", stereoDownmixBoostFilterV3) - hevcRecipeErr, hevcRecipeContextErr := probeHEVCRecipeV3(ctx, ffmpegPath, encoders) - eac3RecipeErr, eac3RecipeContextErr := probeSurroundBitstreamRecipeV3(ctx, ffmpegPath, encoders, surroundBitstreamCodecEAC3V3) - ac3RecipeErr, ac3RecipeContextErr := probeSurroundBitstreamRecipeV3(ctx, ffmpegPath, encoders, surroundBitstreamCodecAC3V3) - _, ffmpegErr := exec.LookPath(ffmpegPath) + // Phase 1: run independent listing and audio-filter smoke probes in parallel. + var ( + bsfs []byte + bsfErr, bsfContextErr error + encoders []byte + encoderErr error + encoderContextErr error + normalizeRecipeErr error + normalizeRecipeContextErr error + downmixRecipeErr error + downmixRecipeContextErr error + ffmpegErr error + phase1 sync.WaitGroup + ) + phase1.Add(5) + go func() { + defer phase1.Done() + bsfCtx, cancelBSF := context.WithTimeout(ctx, 3*time.Second) + defer cancelBSF() + bsfs, bsfErr = procgroup.CommandContext(bsfCtx, ffmpegPath, "-hide_banner", "-bsfs").Output() + bsfContextErr = bsfCtx.Err() + }() + go func() { + defer phase1.Done() + encoderCtx, cancelEncoders := context.WithTimeout(ctx, 3*time.Second) + defer cancelEncoders() + encoders, encoderErr = procgroup.CommandContext(encoderCtx, ffmpegPath, "-hide_banner", "-encoders").Output() + encoderContextErr = encoderCtx.Err() + }() + go func() { + defer phase1.Done() + normalizeRecipeErr, normalizeRecipeContextErr = probeAudioRecipeFilterV3(ctx, ffmpegPath, "stereo", aacTimestampNormalizeFilterV3) + }() + go func() { + defer phase1.Done() + downmixRecipeErr, downmixRecipeContextErr = probeAudioRecipeFilterV3(ctx, ffmpegPath, "5.1", stereoDownmixBoostFilterV3) + }() + go func() { + defer phase1.Done() + _, ffmpegErr = exec.LookPath(ffmpegPath) + }() + phase1.Wait() + + // Phase 2: run encoder-dependent smoke probes in parallel using the + // encoder listing collected above. + var ( + hevcRecipeErr, hevcRecipeContextErr error + eac3RecipeErr, eac3RecipeContextErr error + ac3RecipeErr, ac3RecipeContextErr error + phase2 sync.WaitGroup + ) + phase2.Add(3) + go func() { + defer phase2.Done() + hevcRecipeErr, hevcRecipeContextErr = probeHEVCRecipeV3(ctx, ffmpegPath, encoders) + }() + go func() { + defer phase2.Done() + eac3RecipeErr, eac3RecipeContextErr = probeSurroundBitstreamRecipeV3(ctx, ffmpegPath, encoders, surroundBitstreamCodecEAC3V3) + }() + go func() { + defer phase2.Done() + ac3RecipeErr, ac3RecipeContextErr = probeSurroundBitstreamRecipeV3(ctx, ffmpegPath, encoders, surroundBitstreamCodecAC3V3) + }() + phase2.Wait() registry := NewTransformationRegistryV3([]TransformationSpecV3{ {Name: TransformationServerDV7HDR10V3, RecipeVersion: TransformationServerDV7HDR10RecipeVersionV3, Available: bytes.Contains(bsfs, []byte("dovi_rpu")) && bytes.Contains(bsfs, []byte("filter_units")), RequiredCapability: "ffmpeg_bsf:dovi_rpu+filter_units", PromisedDynamicRange: DynamicRangeHDR10V3, ValidatedClaims: DV7ToHDR10ClaimsV3(), TerminalReason: TerminalDVConversionUnsupportedV3}, {Name: TransformationServerDV7DV81V3, RecipeVersion: TransformationServerDV7DV81RecipeVersionV3, Available: bytes.Contains(bsfs, []byte("filter_units")), RequiredCapability: "ffmpeg_bsf:filter_units", PromisedDynamicRange: DynamicRangeDolbyVisionV3, ValidatedClaims: DV7ToDV81ClaimsV3(), TerminalReason: TerminalDVConversionUnsupportedV3}, diff --git a/internal/policy/viewer_resolver.go b/internal/policy/viewer_resolver.go index 191895834d6..59518ffd8f6 100644 --- a/internal/policy/viewer_resolver.go +++ b/internal/policy/viewer_resolver.go @@ -136,7 +136,10 @@ func (r *ViewerResolver) resolveEach(ctx context.Context, input access.ResolveIn return access.Scope{}, access.ErrProfileNotFound } } - preferences := access.ResolveViewerPreferences(ctx, store, r.defaults, input.ProfileID) + var preferences access.ViewerPreferences + if !input.SkipViewerPreferences { + preferences = access.ResolveViewerPreferences(ctx, store, r.defaults, input.ProfileID) + } return r.ResolveFacts(ctx, input, user, profile, effective, preferences) } @@ -184,9 +187,13 @@ func (r *ViewerResolver) resolveBatched(ctx context.Context, input access.Resolv return access.Scope{}, access.ErrProfileNotFound } } - // Without a profile ResolveViewerPreferences reads nothing, and none was + // Without a profile (or when browsing preferences are skipped on media + // delivery routes) ResolveViewerPreferences reads nothing, and none was // queued. - preferences := access.ResolveViewerPreferences(ctx, reads.preferences, r.defaults, input.ProfileID) + var preferences access.ViewerPreferences + if !input.SkipViewerPreferences { + preferences = access.ResolveViewerPreferences(ctx, reads.preferences, r.defaults, input.ProfileID) + } return r.ResolveFacts(ctx, input, user, reads.profile, effective, preferences) } @@ -206,7 +213,7 @@ func (r *ViewerResolver) sendViewerReads(ctx context.Context, input access.Resol readProfile = pgstore.QueueProfile(batch, input.UserID, input.ProfileID) } var readPreferences func(pgx.BatchResults) ([]userstore.SettingValue, error) - if strings.TrimSpace(input.ProfileID) != "" { + if !input.SkipViewerPreferences && strings.TrimSpace(input.ProfileID) != "" { readPreferences = pgstore.QueueSettingValuesForResolution(batch, input.UserID, access.ViewerPreferenceQuery(input.ProfileID)) } @@ -338,6 +345,13 @@ func (r *ViewerResolver) ResolveFacts(ctx context.Context, input access.ResolveI allowedTitles = profile.AllowedTitleIDs } } + if input.EffectivePolicyOut != nil { + *input.EffectivePolicyOut = access.ResolvedUserPolicy{ + UserID: user.ID, + Policy: effective, + Resolved: true, + } + } return access.Scope{ UserID: user.ID, ProfileID: input.ProfileID, diff --git a/internal/proxy/capability_snapshot_test.go b/internal/proxy/capability_snapshot_test.go index 0e0be0c9ef3..a3e43f36783 100644 --- a/internal/proxy/capability_snapshot_test.go +++ b/internal/proxy/capability_snapshot_test.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "slices" + "sync/atomic" "testing" "github.com/Silo-Server/silo-server/internal/nodeauth/nodeauthtest" @@ -188,3 +189,26 @@ func TestProxyAdvertisesReceiptsOnlyWhenItKnowsItsNodeID(t *testing.T) { }) } } + +// A build that reads the node identity before it is registered describes the +// proxy without it. Caching that report under the identity registered while +// the build ran would serve it as current until the next scheduled refresh. +func TestProxyCapabilitiesNotCachedUnderIdentityLearnedMidBuild(t *testing.T) { + const secret = "capability-secret" + server := newCapabilityProxyServer(t, secret) + var reads atomic.Int32 + server.nodeRowID = func() (int, bool) { + // The pre-build key and the build itself see no row; registration + // lands before the build finishes. + if reads.Add(1) <= 2 { + return 0, false + } + return 11, true + } + fetchProxyCapabilities(t, server, secret) + second := fetchProxyCapabilities(t, server, secret) + if !slices.Contains(second.TransportFeatures, playback.TransportFeatureConnectionReceiptV1) { + t.Fatalf("node row 11 is registered but the served report still lacks %s: %v", + playback.TransportFeatureConnectionReceiptV1, second.TransportFeatures) + } +} diff --git a/internal/proxy/mediagrant.go b/internal/proxy/mediagrant.go index b080c1b85f7..e3a36c548af 100644 --- a/internal/proxy/mediagrant.go +++ b/internal/proxy/mediagrant.go @@ -7,6 +7,7 @@ import ( "net/http" "strconv" "strings" + "sync" "github.com/Silo-Server/silo-server/internal/logredact" @@ -93,12 +94,42 @@ func (s *Server) authorizeGrant(w http.ResponseWriter, r *http.Request) (*playba writeGrantError(w, http.StatusUnauthorized, "unauthorized", "Invalid or expired token") return nil, false } - authority, valid, err := s.loginSessions.ActiveSession(r.Context(), claims.SessionID, claims.UserID) - if err != nil { + // Overlap login-session check (Postgres), grant read (Redis), and + // session-id deny lookup (Redis) instead of paying three serial RTTs on + // every media request, while preserving exact error precedence and + // immediate revocation. + var ( + authority auth.SessionAuthority + valid bool + authErr error + card *playback.RecipeCard + ok bool + sessionIDDenied bool + wg sync.WaitGroup + ) + wg.Add(2) + go func() { + defer wg.Done() + authority, valid, authErr = s.loginSessions.ActiveSession(r.Context(), claims.SessionID, claims.UserID) + }() + go func() { + defer wg.Done() + card, ok = s.grants.Get(r.Context(), sessionID) + }() + if s.streamDeny != nil { + wg.Add(1) + go func() { + defer wg.Done() + sessionIDDenied = s.streamDeny.Denied(r.Context(), sessionID) + }() + } + wg.Wait() + + if authErr != nil { // The session could not be checked, which says nothing about the // credential: a retryable 503, never a 401 that signs the client out. if r.Context().Err() == nil { - slog.WarnContext(r.Context(), "login session check failed", "component", "proxy", "error", logredact.SanitizeText(err.Error()), "playback_session_id", sessionID) + slog.WarnContext(r.Context(), "login session check failed", "component", "proxy", "error", logredact.SanitizeText(authErr.Error()), "playback_session_id", sessionID) } w.Header().Set("Retry-After", strconv.Itoa(auth.SessionCheckRetryAfterSeconds)) writeGrantError(w, http.StatusServiceUnavailable, "service_unavailable", "Sign-in could not be checked right now; try again shortly") @@ -108,8 +139,6 @@ func (s *Server) authorizeGrant(w http.ResponseWriter, r *http.Request) (*playba writeGrantError(w, http.StatusUnauthorized, "unauthorized", "Session is no longer valid") return nil, false } - - card, ok := s.grants.Get(r.Context(), sessionID) if !ok || card == nil { writeGrantError(w, http.StatusNotFound, "playback_session_not_found", "Playback session not found") return nil, false @@ -126,7 +155,16 @@ func (s *Server) authorizeGrant(w http.ResponseWriter, r *http.Request) (*playba // 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. - if grantClaims := card.ToClaims(); s.sessionDenied(r.Context(), &grantClaims) { + denied := sessionIDDenied + if !denied && s.streamDeny != nil { + grantClaims := card.ToClaims() + if grantClaims.SessionID != "" && grantClaims.SessionID != sessionID && s.streamDeny.Denied(r.Context(), grantClaims.SessionID) { + denied = true + } else if transport := transcodeTransportIDFromClaims(&grantClaims); transport != "" && transport != sessionID && transport != grantClaims.SessionID && s.streamDeny.Denied(r.Context(), transport) { + denied = true + } + } + if denied { writeGrantError(w, http.StatusGone, "playback_session_ended", "Playback session ended") return nil, false } diff --git a/internal/proxy/reprobe.go b/internal/proxy/reprobe.go index edc2e5b8274..33b704b15ae 100644 --- a/internal/proxy/reprobe.go +++ b/internal/proxy/reprobe.go @@ -58,6 +58,8 @@ func (s *Server) handleReprobeCapabilities(w http.ResponseWriter, r *http.Reques return } + s.cachedCapability.Store(nil) + key := s.currentCapabilityKey() playback.InvalidateHWProbeCache() tonemap.InvalidateProbeCache() mediasample.InvalidateCapabilities() @@ -78,7 +80,10 @@ func (s *Server) handleReprobeCapabilities(w http.ResponseWriter, r *http.Reques return } previous := s.storedCapabilityHash() - s.storeCapabilityHash(info.CapabilityHash) + if !s.storeCapabilitySnapshotLocked(key, info) { + http.Error(w, "capability probe unavailable", http.StatusServiceUnavailable) + return + } slog.InfoContext(r.Context(), "proxy capabilities re-probed", "component", "proxy", "previous_hash", previous, "hash", info.CapabilityHash, "resolved", info.Resolved) w.Header().Set("Content-Type", "application/json") diff --git a/internal/proxy/segment_completion_test.go b/internal/proxy/segment_completion_test.go index fe59cba4e16..428c591a5ae 100644 --- a/internal/proxy/segment_completion_test.go +++ b/internal/proxy/segment_completion_test.go @@ -36,6 +36,7 @@ func TestTranscodeProxyAcknowledgesOnlyFullDownstreamResponse(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var acknowledgements atomic.Int32 + acked := make(chan struct{}, 4) seenRange := make(chan string, 1) node := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.Method { @@ -51,6 +52,7 @@ func TestTranscodeProxyAcknowledgesOnlyFullDownstreamResponse(t *testing.T) { t.Errorf("ack generation = %q, want %q", r.Header.Get(transcodeproxy.GenerationHeader), generation) } acknowledgements.Add(1) + acked <- struct{}{} w.WriteHeader(http.StatusNoContent) default: http.Error(w, "unexpected method", http.StatusMethodNotAllowed) @@ -74,6 +76,13 @@ func TestTranscodeProxyAcknowledgesOnlyFullDownstreamResponse(t *testing.T) { if got := rr.Header().Get(transcodeproxy.GenerationHeader); got != "" { t.Fatalf("internal generation leaked downstream: %q", got) } + for range tt.wantAck { + select { + case <-acked: + case <-time.After(5 * time.Second): + t.Fatalf("timed out waiting for async segment acknowledgement") + } + } if got := acknowledgements.Load(); got != tt.wantAck { t.Fatalf("acknowledgements = %d, want %d", got, tt.wantAck) } diff --git a/internal/proxy/server.go b/internal/proxy/server.go index c6782cdd175..4d0e9babb4f 100644 --- a/internal/proxy/server.go +++ b/internal/proxy/server.go @@ -96,6 +96,12 @@ type Server struct { // request completes. capabilityHash atomic.Pointer[string] + // cachedCapability holds the last complete capability snapshot assembled for + // the active ffmpeg config and node identity. /hw-capabilities serves it + // directly instead of re-running ffmpeg smoke probes on every API fetch, + // while the 15-minute background refresh and operator re-probe rebuild live. + cachedCapability atomic.Pointer[cachedProxyCapabilitySnapshot] + // metrics samples host and GPU resources in the background. Nil until // StartMetricsSampler runs, which leaves health exactly as it was before. metrics *nodemetrics.Sampler @@ -356,7 +362,22 @@ func (s *Server) router() chi.Router { // every proxy a full GPU smoke-encode matrix every 15 minutes to produce an // answer no planner consults. func (s *Server) handleHWCapabilities(w http.ResponseWriter, r *http.Request) { + if r.Context().Err() != nil { + http.Error(w, "capability probe unavailable", http.StatusServiceUnavailable) + return + } + if snap := s.cachedCapability.Load(); snap != nil && snap.key == s.currentCapabilityKey() { + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(snap.info); err != nil { + slog.WarnContext(r.Context(), "encode proxy capabilities", "component", "proxy", "error", err) + } + return + } info, err := s.buildCapabilitySnapshot(r.Context()) + if errors.Is(err, errCapabilitySnapshotSuperseded) { + // The configuration or identity changed mid-build; describe the new one. + info, err = s.buildCapabilitySnapshot(r.Context()) + } if err != nil { // An incomplete probe would hash differently from the same ffmpeg probed // successfully, so serving it would announce a capability change that did @@ -365,9 +386,6 @@ func (s *Server) handleHWCapabilities(w http.ResponseWriter, r *http.Request) { http.Error(w, "capability probe unavailable", http.StatusServiceUnavailable) return } - // A served report is as authoritative as a scheduled snapshot, so health - // starts advertising this hash immediately rather than at the next tick. - s.storeCapabilityHash(info.CapabilityHash) w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(info); err != nil { slog.WarnContext(r.Context(), "encode proxy capabilities", "component", "proxy", "error", err) @@ -386,9 +404,23 @@ func (s *Server) handleHWCapabilities(w http.ResponseWriter, r *http.Request) { func (s *Server) buildCapabilitySnapshot(ctx context.Context) (playback.HWAccelInfo, error) { s.capabilityBuildMu.Lock() defer s.capabilityBuildMu.Unlock() - return s.buildCapabilitySnapshotLocked(ctx) + key := s.currentCapabilityKey() + info, err := s.buildCapabilitySnapshotLocked(ctx) + if err != nil { + return playback.HWAccelInfo{}, err + } + // A built report is as authoritative as a scheduled snapshot, so health + // starts advertising its hash immediately rather than at the next tick. + if !s.storeCapabilitySnapshotLocked(key, info) { + return playback.HWAccelInfo{}, errCapabilitySnapshotSuperseded + } + return info, nil } +// errCapabilitySnapshotSuperseded reports a build whose configuration or +// identity changed before it could be stored. +var errCapabilitySnapshotSuperseded = errors.New("capability snapshot superseded by a configuration change") + // buildCapabilitySnapshotLocked is buildCapabilitySnapshot's body. Callers must // hold capabilityBuildMu; the re-probe takes it itself so its cache // invalidation and its rebuild are one step no other builder can interleave @@ -476,6 +508,7 @@ func (s *Server) StartCapabilitySnapshots(ctx context.Context) { } func (s *Server) refreshCapabilitySnapshot(ctx context.Context) { + previous := s.storedCapabilityHash() info, err := s.buildCapabilitySnapshot(ctx) if err != nil { // Keep the previous hash: a failed probe is not evidence this proxy's @@ -484,11 +517,50 @@ func (s *Server) refreshCapabilitySnapshot(ctx context.Context) { slog.WarnContext(ctx, "proxy capability snapshot incomplete", "component", "proxy", "error", err) return } - if previous := s.storedCapabilityHash(); previous != "" && previous != info.CapabilityHash { + if previous != "" && previous != info.CapabilityHash { slog.InfoContext(ctx, "proxy capabilities changed", "component", "proxy", "previous_hash", previous, "hash", info.CapabilityHash, "resolved", info.Resolved) } +} + +type proxyCapabilityKey struct { + ffmpegPath string + nodeRowID int + nodeRowKnown bool +} + +type cachedProxyCapabilitySnapshot struct { + key proxyCapabilityKey + info playback.HWAccelInfo +} + +func (s *Server) currentCapabilityKey() proxyCapabilityKey { + key := proxyCapabilityKey{} + if s.watcher != nil { + if cfg := s.watcher.Config(); cfg != nil { + key.ffmpegPath = cfg.Playback.FFmpegPath + } + } + key.nodeRowID, key.nodeRowKnown = s.currentNodeRowID() + return key +} + +// storeCapabilitySnapshotLocked caches info as the report for key, the +// configuration and identity read before the build, and publishes its hash. +// The caller holds capabilityBuildMu, so a scheduled refresh cannot overwrite a +// re-probe that finished after it. Nothing is published unless key is still +// current: a build that read configuration changing underneath it describes +// neither the old key nor the new one. +func (s *Server) storeCapabilitySnapshotLocked(key proxyCapabilityKey, info playback.HWAccelInfo) bool { + if key != s.currentCapabilityKey() { + // Health keeps the previous hash: the next build describes the new + // key, and advertising this one would move the hash twice. + s.cachedCapability.Store(nil) + return false + } s.storeCapabilityHash(info.CapabilityHash) + s.cachedCapability.Store(&cachedProxyCapabilitySnapshot{key: key, info: info}) + return true } // storedCapabilityHash returns the last published capability hash, or empty @@ -1265,6 +1337,8 @@ func (s *Server) proxyToTranscodeNode(w http.ResponseWriter, r *http.Request, cl } if isSegmentRoute { transcodeproxy.PrepareRequest(req, r) + } else if strings.HasSuffix(path, ".m3u8") { + req.Header.Set("Accept-Encoding", playback.ManifestRelayAcceptEncoding(r)) } // Forward the verified stream token so the transcode node can self-reconstruct // a lost session after its OWN restart: the token carries the full byte-affecting @@ -1351,9 +1425,10 @@ func (s *Server) proxyToTranscodeNode(w http.ResponseWriter, r *http.Request, cl } if isMediaSegment && generation != "" && r.Method == http.MethodGet && sw.CompletedFullResponse(transcodeproxy.FullRepresentationSize(resp)) { - if ackErr := transcodeproxy.Acknowledge(r.Context(), s.httpClient, nodeURL, path, s.nodeKeys, generation); ackErr != nil { - slog.WarnContext(r.Context(), "acknowledge transcode segment completion", "component", "proxy", "error", ackErr, "playback_session_id", claims.SessionID) - } + _ = http.NewResponseController(w).Flush() + transcodeproxy.AcknowledgeAsync(r.Context(), s.httpClient, nodeURL, path, s.nodeKeys, generation, func(ackErr error) { + slog.WarnContext(context.WithoutCancel(r.Context()), "acknowledge transcode segment completion", "component", "proxy", "error", ackErr, "playback_session_id", claims.SessionID) + }) } } diff --git a/internal/tonemap/dri_access.go b/internal/tonemap/dri_access.go new file mode 100644 index 00000000000..6ea2ce2dad2 --- /dev/null +++ b/internal/tonemap/dri_access.go @@ -0,0 +1,39 @@ +package tonemap + +import ( + "os" + "strings" +) + +// probeDeviceOpenable reports whether a DRM device path can be opened by this +// process. Tests override it to model hosts exposing a subset of a cluster-wide +// hw_device setting. +var probeDeviceOpenable = defaultProbeDeviceOpenable + +func defaultProbeDeviceOpenable(device string) bool { + f, err := os.Open(device) //nolint:gosec // device is an operator-configured DRM render node path + if err != nil { + return false + } + _ = f.Close() + return true +} + +// probeDevicesForHost narrows a cluster-wide DRM device list to the nodes this +// process can actually open, matching playback's hardware detection filter. +// Without that filter, a server exposing only renderD128 under a cluster-wide +// "renderD128,renderD129" setting fails every smoke on renderD129, discards the +// working renderD128 capabilities, and re-probes every probeNegativeTTL. +func probeDevicesForHost(value, backend string, checkDeviceAccess bool) []string { + devices := probeDevices(value, backend) + if !checkDeviceAccess || (backend != BackendQSV && backend != BackendVAAPI) { + return devices + } + accessible := make([]string, 0, len(devices)) + for _, device := range devices { + if !strings.ContainsRune(device, '/') || probeDeviceOpenable(device) { + accessible = append(accessible, device) + } + } + return accessible +} diff --git a/internal/tonemap/probe.go b/internal/tonemap/probe.go index 79f3641b918..95ea6c7c181 100644 --- a/internal/tonemap/probe.go +++ b/internal/tonemap/probe.go @@ -90,12 +90,22 @@ var probeCache = struct { // Probe returns the cached, smoke-tested tone-map capabilities for an FFmpeg // binary and hardware configuration. func Probe(ctx context.Context, ffmpegPath, hardwareBackend, hardwareDevice string) (Capabilities, error) { - return probeCached(ctx, ffmpegPath, hardwareBackend, hardwareDevice, runCommand, time.Now) + return probeCachedWithAccess(ctx, ffmpegPath, hardwareBackend, hardwareDevice, runCommand, time.Now, true) } // probeCached coalesces identical probes without allowing one caller's // cancellation to abort the shared work needed by other playback requests. func probeCached(ctx context.Context, ffmpegPath, hardwareBackend, hardwareDevice string, run CommandRunner, now func() time.Time) (Capabilities, error) { + return probeCachedWithAccess(ctx, ffmpegPath, hardwareBackend, hardwareDevice, run, now, false) +} + +func probeCachedWithAccess( + ctx context.Context, + ffmpegPath, hardwareBackend, hardwareDevice string, + run CommandRunner, + now func() time.Time, + checkDeviceAccess bool, +) (Capabilities, error) { probeCache.Lock() key := probeCacheKey(probeCache.generation, ffmpegPath, hardwareBackend, hardwareDevice) if cached, ok := probeCache.entries[key]; ok && probeCacheEntryCurrent(cached, now()) { @@ -121,7 +131,7 @@ func probeCached(ctx context.Context, ffmpegPath, hardwareBackend, hardwareDevic } probeCtx, cancel := context.WithTimeout(context.Background(), ProbeTotalTimeout(hardwareBackend, hardwareDevice)) defer cancel() - result, verdict, dolbyVisionUnsettled, err := probeWithRunner(probeCtx, ffmpegPath, hardwareBackend, hardwareDevice, run) + result, verdict, dolbyVisionUnsettled, err := probeWithRunner(probeCtx, ffmpegPath, hardwareBackend, hardwareDevice, run, checkDeviceAccess) if err != nil { logProbeUnfinished(probeCtx, key, ffmpegPath, hardwareBackend, hardwareDevice, verdict, err) return nil, err @@ -129,7 +139,7 @@ func probeCached(ctx context.Context, ffmpegPath, hardwareBackend, hardwareDevic logProbeResult(probeCtx, key, ffmpegPath, hardwareBackend, hardwareDevice, result, verdict) entry := probeCacheEntry{capabilities: append(Capabilities(nil), result...)} switch { - case !probeCapabilitiesComplete(result, hardwareBackend): + case !CapabilitiesComplete(result, hardwareBackend): entry.expiresAt = now().Add(probeNegativeTTL) case dolbyVisionUnsettled: entry.expiresAt = now().Add(probeUnsettledDolbyVisionTTL) @@ -173,6 +183,7 @@ func probeWithRunner( ctx context.Context, ffmpegPath, hardwareBackend, hardwareDevice string, run CommandRunner, + checkDeviceAccess bool, ) (Capabilities, hardwareProbeVerdict, bool, error) { var transientErr error timedOut := "" @@ -200,7 +211,7 @@ func probeWithRunner( } return output, err } - capabilities, verdict := probeInventory(ctx, ffmpegPath, hardwareBackend, hardwareDevice, trackingRunner) + capabilities, verdict := probeInventory(ctx, ffmpegPath, hardwareBackend, hardwareDevice, trackingRunner, checkDeviceAccess) transientErr = errors.Join(transientErr, ctx.Err()) if transientErr != nil { if timedOut == "" { @@ -300,8 +311,23 @@ func probeCacheEntryCurrent(entry probeCacheEntry, now time.Time) bool { return entry.expiresAt.IsZero() || now.Before(entry.expiresAt) } -// probeCapabilitiesComplete reports whether discovery found a reusable result -// for every executor class it was asked to inspect. A software capability does +// ProbeRetryAt reports when Probe will next run for these inputs instead of +// answering from its cache, for a result it keeps only until a retry: an +// incomplete inventory, or a Dolby Vision smoke that failed for a passing +// reason. ok is false for a settled result or none. +func ProbeRetryAt(ffmpegPath, hardwareBackend, hardwareDevice string) (time.Time, bool) { + probeCache.Lock() + defer probeCache.Unlock() + entry, ok := probeCache.entries[probeCacheKey(probeCache.generation, ffmpegPath, hardwareBackend, hardwareDevice)] + if !ok || entry.expiresAt.IsZero() { + return time.Time{}, false + } + return entry.expiresAt, true +} + +// CapabilitiesComplete reports whether discovery found a reusable result for +// every executor class it was asked to inspect: a Probe result Probe keeps +// rather than retries after the negative-cache interval. A software capability does // not make a missing configured hardware executor permanent: temporary device // contention must be retried after the negative-cache interval. // @@ -311,7 +337,7 @@ func probeCacheEntryCurrent(entry probeCacheEntry, now time.Time) bool { // genuine answer for that build, and executors that cannot apply an RPU never // run it; counting it would re-probe those devices every negative-cache // interval for good. -func probeCapabilitiesComplete(capabilities Capabilities, hardwareBackend string) bool { +func CapabilitiesComplete(capabilities Capabilities, hardwareBackend string) bool { if !capabilityCoversAllSourceKinds(capabilities, ModeSoftware, BackendSoftware) { return false } @@ -413,7 +439,7 @@ func ProbeWithRunner( ffmpegPath, hardwareBackend, hardwareDevice string, run CommandRunner, ) Capabilities { - capabilities, _ := probeInventory(ctx, ffmpegPath, hardwareBackend, hardwareDevice, run) + capabilities, _ := probeInventory(ctx, ffmpegPath, hardwareBackend, hardwareDevice, run, false) return capabilities } @@ -448,12 +474,14 @@ func probeInventory( ctx context.Context, ffmpegPath, hardwareBackend, hardwareDevice string, run CommandRunner, + checkDeviceAccess bool, ) (Capabilities, hardwareProbeVerdict) { if strings.TrimSpace(ffmpegPath) == "" { ffmpegPath = "ffmpeg" } backend := strings.ToLower(strings.TrimSpace(hardwareBackend)) - verdict := hardwareProbeVerdict{filter: hardwareFilter(backend, hardwareDevice)} + devices := probeDevicesForHost(hardwareDevice, backend, checkDeviceAccess) + verdict := hardwareProbeVerdict{filter: hardwareFilterForDevices(backend, devices)} filters, filterErr := runBounded(ctx, run, ffmpegPath, ffmpegHideBannerArg, "-filters") encoders, encoderErr := runBounded(ctx, run, ffmpegPath, ffmpegHideBannerArg, "-encoders") if filterErr != nil || encoderErr != nil { @@ -484,7 +512,7 @@ func probeInventory( filter := verdict.filter if hardwareProbeAvailable(backend, filter, filters, encoders) { verdict.listed = true - kinds, failure := hardwareSmokeSourceKinds(ctx, run, ffmpegPath, fixturePath, backend, filter, hardwareDevice) + kinds, failure := hardwareSmokeSourceKinds(ctx, run, ffmpegPath, fixturePath, backend, filter, devices) verdict.failure = failure if len(kinds) > 0 { capabilities = append(capabilities, Capability{Mode: ModeHardware, Backend: backend, Filter: filter, SourceKinds: kinds}) @@ -494,11 +522,13 @@ func probeInventory( } // hardwareSmokeSourceKinds returns only source kinds converted successfully on -// every configured device so the advertised union is safe for later selection, -// and the first failed conversion's error line. -func hardwareSmokeSourceKinds(ctx context.Context, run CommandRunner, ffmpegPath, fixturePath, backend, filter, hardwareDevice string) ([]SourceKind, string) { +// every configured device accessible to this process so the advertised union +// is safe for later selection, and the first failed conversion's error line. +func hardwareSmokeSourceKinds(ctx context.Context, run CommandRunner, ffmpegPath, fixturePath, backend, filter string, devices []string) ([]SourceKind, string) { + if len(devices) == 0 { + return nil, "configured hardware device is not accessible on this node" + } firstFailure := "" - devices := probeDevices(hardwareDevice, backend) validated := smokeKindsForFilter(filter) for _, device := range devices { if filter == HardwareFilterVAAPI && drmVendorUnreadable(device) { @@ -590,6 +620,10 @@ func intersectSourceKinds(left, right []SourceKind) []SourceKind { // hardwareFilter returns the FFmpeg tone-map filter a backend uses on the // configured devices. func hardwareFilter(backend, hardwareDevice string) string { + return hardwareFilterForDevices(backend, probeDevices(hardwareDevice, backend)) +} + +func hardwareFilterForDevices(backend string, devices []string) string { switch backend { case BackendQSV: return HardwareFilterOpenCL @@ -598,7 +632,7 @@ func hardwareFilter(backend, hardwareDevice string) string { case BackendVideoToolbox: return HardwareFilterVideoToolbox case BackendVAAPI: - return vaapiFilter(hardwareDevice) + return vaapiFilterForDevices(devices) default: return HardwareFilterVAAPI } @@ -676,7 +710,7 @@ func smokeKindsForFilter(filter string) []SourceKind { } // requiredSourceKinds lists the kinds a complete inventory for filter must -// contain; see probeCapabilitiesComplete. +// contain; see CapabilitiesComplete. func requiredSourceKinds(filter string) []SourceKind { kinds := StandardSourceKinds() if FilterConvertsFullRange(filter) { diff --git a/internal/tonemap/probe_test.go b/internal/tonemap/probe_test.go index 8c6025bf3af..0d2497688b1 100644 --- a/internal/tonemap/probe_test.go +++ b/internal/tonemap/probe_test.go @@ -517,6 +517,9 @@ func TestProbeTransientDolbyVisionSmokeFailureRetries(t *testing.T) { if got := probe(); got.Supports(ModeSoftware, SourceDolbyVision) || !got.Supports(ModeSoftware, SourcePQ) { t.Fatalf("first capabilities = %#v, want PQ without Dolby Vision", got) } + if retryAt, ok := ProbeRetryAt("/ffmpeg-dovi-busy", BackendSoftware, ""); !ok || !retryAt.Equal(now.Add(probeUnsettledDolbyVisionTTL)) { + t.Fatalf("ProbeRetryAt = %v, %v, want the unsettled Dolby Vision retry", retryAt, ok) + } firstCalls := calls now = now.Add(probeUnsettledDolbyVisionTTL - time.Second) probe() @@ -527,6 +530,74 @@ func TestProbeTransientDolbyVisionSmokeFailureRetries(t *testing.T) { if got := probe(); !got.Supports(ModeSoftware, SourceDolbyVision) { t.Fatalf("retried capabilities = %#v, want Dolby Vision once the smoke passes", got) } + if _, ok := ProbeRetryAt("/ffmpeg-dovi-busy", BackendSoftware, ""); ok { + t.Fatal("ProbeRetryAt still reports a retry once the smoke passed") + } }) } } + +func TestProbeSkipsInaccessibleDRIDevicesInClusterList(t *testing.T) { + resetProbeCache(t) + prevOpenable := probeDeviceOpenable + t.Cleanup(func() { probeDeviceOpenable = prevOpenable }) + + const ( + qsvFilters = " .S. zscale V->V\n .S. tonemapx V->V\n .S. sidedata V->V\n .S. tonemap_opencl V->V\n .S. hwmap V->V\n .S. scale_vaapi V->V\n .S. overlay_opencl VV->V\n .S. scale_opencl V->V\n" + qsvEncoders = "libx264 h264_qsv" + ) + + probeDeviceOpenable = func(device string) bool { + return device == "/dev/dri/renderD128" + } + now := time.Unix(100, 0) + calls := 0 + var probedRender129 atomic.Bool + runner := listingRunner(&calls, qsvFilters, qsvEncoders, func(args string) ([]byte, error) { + if strings.Contains(args, "/dev/dri/renderD129") { + probedRender129.Store(true) + return []byte("Failed to create a VAAPI device. Error code: Invalid argument"), errors.New("exit status 1") + } + return nil, nil + }) + + got, err := probeCachedWithAccess(t.Context(), "/ffmpeg-cluster-dri", BackendQSV, "/dev/dri/renderD128,/dev/dri/renderD129", runner, func() time.Time { return now }, true) + if err != nil { + t.Fatalf("cluster DRI probe error = %v", err) + } + if probedRender129.Load() { + t.Fatal("probe spawned smoke command for inaccessible /dev/dri/renderD129") + } + for _, kind := range StandardSourceKinds() { + if !got.Supports(ModeHardware, kind) { + t.Fatalf("capabilities = %#v, missing hardware %q on accessible renderD128", got, kind) + } + } + firstCalls := calls + now = now.Add(probeNegativeTTL + time.Minute) + if _, err := probeCachedWithAccess(t.Context(), "/ffmpeg-cluster-dri", BackendQSV, "/dev/dri/renderD128,/dev/dri/renderD129", runner, func() time.Time { return now }, true); err != nil { + t.Fatalf("cached cluster DRI probe error = %v", err) + } + if calls != firstCalls { + t.Fatalf("complete cluster DRI probe reran after negative TTL: calls = %d, want %d", calls, firstCalls) + } + + probeDeviceOpenable = func(string) bool { return false } + var hwSmokes atomic.Int32 + noDevRunner := listingRunner(nil, qsvFilters, qsvEncoders, func(args string) ([]byte, error) { + if strings.Contains(args, "-init_hw_device") { + hwSmokes.Add(1) + } + return nil, nil + }) + noDevCaps, err := probeCachedWithAccess(t.Context(), "/ffmpeg-no-dri", BackendQSV, "/dev/dri/renderD128,/dev/dri/renderD129", noDevRunner, func() time.Time { return now }, true) + if err != nil { + t.Fatalf("inaccessible DRI probe error = %v", err) + } + if hwSmokes.Load() != 0 { + t.Fatalf("inaccessible DRI probe ran %d hardware smoke commands, want 0", hwSmokes.Load()) + } + if noDevCaps.Supports(ModeHardware, SourcePQ) { + t.Fatalf("inaccessible DRI probe advertised hardware capabilities: %#v", noDevCaps) + } +} diff --git a/internal/tonemap/tonemap.go b/internal/tonemap/tonemap.go index 2ecc7da9511..d4eec1a9346 100644 --- a/internal/tonemap/tonemap.go +++ b/internal/tonemap/tonemap.go @@ -721,17 +721,34 @@ func SourceParameters(kind SourceKind) string { // data. Still-image outputs (MJPEG) never carry HDR side data and may run on // FFmpeg builds whose sidedata filter does not know DOVI_RPU_BUFFER. func SoftwareConversionFilter(kind SourceKind, filterName string) string { + return SoftwareConversionFilterScaled(kind, filterName, 0) +} + +// SoftwareConversionFilterScaled builds the software HDR-to-SDR conversion +// graph, optionally downscaling to height before tone mapping when safe. +// Scaling in 10-bit HDR space before tonemapx/tonemap avoids running per-pixel +// tone-mapping math across 4K pixels only to discard 75-89% of them afterward. +// SourceDolbyVision keeps full-resolution frames ahead of RPU reshaping so L5 +// active-area coordinates remain aligned with the source frame. +func SoftwareConversionFilterScaled(kind SourceKind, filterName string, height int) string { + scaleSuffix := "" + scalePrefix := "" + if height > 0 && kind != SourceDolbyVision { + scaleSuffix = ":w=-2:h=" + strconv.Itoa(height) + ":f=bilinear" + scalePrefix = ",zscale=w=-2:h=" + strconv.Itoa(height) + ":f=bilinear" + } if IsSDRSource(kind) { return SourceParameters(kind) + - ",zscale=p=bt709:t=bt709:m=bt709:r=tv,format=yuv420p" + ",zscale=p=bt709:t=bt709:m=bt709:r=tv" + scaleSuffix + ",format=yuv420p" } if filterName == SoftwareFilterBT2390 { return SourceParameters(kind) + + scalePrefix + ",tonemapx=tonemap=bt2390" + toneMapPeakOption + softwareDolbyVisionOption(kind) + ",zscale=p=bt709:t=bt709:m=bt709:r=tv,format=yuv420p" } return SourceParameters(kind) + - ",zscale=t=linear:npl=100,format=gbrpf32le,tonemap=hable" + + ",zscale=t=linear:npl=100" + scaleSuffix + ",format=gbrpf32le,tonemap=hable" + ",zscale=p=bt709:t=bt709:m=bt709:r=tv,format=yuv420p" } @@ -741,6 +758,12 @@ func SoftwareFilter(kind SourceKind, filterName string) string { return SoftwareConversionFilter(kind, filterName) + "," + HDRMetadataRemovalFilter() } +// SoftwareFilterScaled builds the complete software conversion graph with +// optional pre-tonemap downscaling to height. +func SoftwareFilterScaled(kind SourceKind, filterName string, height int) string { + return SoftwareConversionFilterScaled(kind, filterName, height) + "," + HDRMetadataRemovalFilter() +} + // SelectSoftwareFilter inspects an FFmpeg -filters listing and returns the // preferred software tone-map filter. It is intentionally only a listing // probe; playback capability advertising additionally runs an encode smoke diff --git a/internal/tonemap/vaapi_vendor.go b/internal/tonemap/vaapi_vendor.go index 00735fb96be..89bd0cb53f9 100644 --- a/internal/tonemap/vaapi_vendor.go +++ b/internal/tonemap/vaapi_vendor.go @@ -13,15 +13,15 @@ var sysfsRoot = "/sys" const intelPCIVendorID = "0x8086" -// vaapiFilter returns the tone-map filter the VAAPI backend uses for the -// configured devices. Intel's VAAPI tone mapper turns HLG teal and inverted and -// crushes PQ midtones (#2414), so when any device is an Intel GPU, VAAPI tone -// maps HDR on OpenCL with the graph QSV uses (IntelFilter). Other vendors keep +// vaapiFilterForDevices returns the tone-map filter the VAAPI backend uses for +// devices. Intel's VAAPI tone mapper turns HLG teal and inverted and crushes PQ +// midtones (#2414), so when any device is an Intel GPU, VAAPI tone maps HDR on +// OpenCL with the graph QSV uses (IntelFilter). Other vendors keep // tonemap_vaapi. One filter covers the whole device list, and FFmpeg maps VAAPI // frames to OpenCL only on Intel, so a non-Intel device listed beside an Intel // one fails the HDR smoke and HDR is offered on neither. -func vaapiFilter(hardwareDevice string) string { - if slices.ContainsFunc(probeDevices(hardwareDevice, BackendVAAPI), isIntelDRMDevice) { +func vaapiFilterForDevices(devices []string) string { + if slices.ContainsFunc(devices, isIntelDRMDevice) { return HardwareFilterOpenCL } return HardwareFilterVAAPI diff --git a/internal/transcodenode/capability_snapshot_test.go b/internal/transcodenode/capability_snapshot_test.go index b2d5dbbc864..a6e8859d241 100644 --- a/internal/transcodenode/capability_snapshot_test.go +++ b/internal/transcodenode/capability_snapshot_test.go @@ -8,10 +8,12 @@ import ( "path/filepath" "slices" "testing" + "time" "github.com/Silo-Server/silo-server/internal/config" "github.com/Silo-Server/silo-server/internal/nodeauth/nodeauthtest" "github.com/Silo-Server/silo-server/internal/playback" + "github.com/Silo-Server/silo-server/internal/tonemap" ) // newCapabilityTestServer builds a node whose configured ffmpeg is a script @@ -104,3 +106,108 @@ func TestHWCapabilitiesWithholdsProgressiveRemuxWithoutNodeIdentity(t *testing.T t.Fatalf("transport features = %v, want progressive remux withheld without a resolved node row", info.TransportFeatures) } } + +// A snapshot that a transient failure produced expires and is rebuilt soon; one +// with nothing that could recover is served until the next scheduled refresh, +// so a node without a GPU does not re-probe every minute. +func TestConfiguredHardwareVerifiedSettlesOnlyRecoverableFailures(t *testing.T) { + software := tonemap.Capability{ + Mode: tonemap.ModeSoftware, Backend: tonemap.BackendSoftware, + Filter: tonemap.SoftwareFilterBT2390, SourceKinds: append(tonemap.StandardSourceKinds(), tonemap.SourcePQFullRange), + } + qsvToneMap := tonemap.Capability{ + Mode: tonemap.ModeHardware, Backend: tonemap.BackendQSV, + Filter: tonemap.HardwareFilterOpenCL, SourceKinds: tonemap.StandardSourceKinds(), + } + softwareOnly := tonemap.Capabilities{software} + cases := []struct { + name string + configured string + info playback.HWAccelInfo + want bool + }{ + {"no backend configured", playback.HWAccelNone, + playback.HWAccelInfo{Resolved: playback.HWAccelNone, ToneMapCapabilities: softwareOnly}, true}, + {"auto with no device to try", playback.HWAccelAuto, + playback.HWAccelInfo{Resolved: playback.HWAccelNone, ToneMapCapabilities: softwareOnly}, true}, + // Detection keeps an explicit backend as Resolved even with no device, + // and lists only backends whose hardware is present. + {"qsv configured but absent", "qsv", + playback.HWAccelInfo{Resolved: "qsv", ToneMapCapabilities: softwareOnly}, true}, + {"nvenc present but failed its probe", "nvenc", + playback.HWAccelInfo{Resolved: "nvenc", ToneMapCapabilities: softwareOnly, + DetectedBackends: []playback.DetectedBackend{{Backend: "nvenc"}}}, false}, + {"auto videotoolbox failed its probe", playback.HWAccelAuto, + playback.HWAccelInfo{Resolved: playback.HWAccelNone, ToneMapCapabilities: softwareOnly, + DetectedBackends: []playback.DetectedBackend{{Backend: "videotoolbox"}}}, false}, + {"qsv device failed its probe", "qsv", + playback.HWAccelInfo{Resolved: playback.HWAccelNone, ToneMapCapabilities: softwareOnly, + DetectedBackends: []playback.DetectedBackend{{Backend: "qsv", Devices: []string{"/dev/dri/renderD128"}}}}, false}, + {"auto device failed its probe", playback.HWAccelAuto, + playback.HWAccelInfo{Resolved: playback.HWAccelNone, ToneMapCapabilities: softwareOnly, + DetectedBackends: []playback.DetectedBackend{{Backend: "vaapi", Devices: []string{"/dev/dri/renderD128"}}}}, false}, + {"qsv verified with hardware tone mapping", "qsv", + playback.HWAccelInfo{Resolved: "qsv", ToneMapCapabilities: tonemap.Capabilities{software, qsvToneMap}, + DetectedBackends: []playback.DetectedBackend{{Backend: "qsv", Verified: true, Devices: []string{"/dev/dri/renderD128"}}}}, true}, + {"qsv verified but hardware tone mapping failed", "qsv", + playback.HWAccelInfo{Resolved: "qsv", ToneMapCapabilities: softwareOnly, + DetectedBackends: []playback.DetectedBackend{{Backend: "qsv", Verified: true, Devices: []string{"/dev/dri/renderD128"}}}}, false}, + } + for _, tc := range cases { + if got := configuredHardwareVerified(tc.configured, tc.info); got != tc.want { + t.Errorf("%s: configuredHardwareVerified = %v, want %v", tc.name, got, tc.want) + } + } +} + +// The scheduled refresh rebuilds a missing snapshot, or one for another +// configuration, at once, and any other at its refreshAt. +func TestCapabilitySnapshotDue(t *testing.T) { + now := time.Unix(1_000_000, 0) + s := &Server{} + key := s.currentCapabilityKey() + other := key + other.ffmpegPath = "/other/ffmpeg" + cases := []struct { + name string + snap *cachedTranscodeCapabilitySnapshot + want bool + }{ + {"none stored", nil, true}, + {"another configuration", &cachedTranscodeCapabilitySnapshot{key: other, refreshAt: now.Add(time.Hour)}, true}, + {"not yet due", &cachedTranscodeCapabilitySnapshot{key: key, refreshAt: now.Add(time.Second)}, false}, + {"due", &cachedTranscodeCapabilitySnapshot{key: key, refreshAt: now}, true}, + } + for _, tc := range cases { + s.cachedCapability.Store(tc.snap) + if got := s.capabilitySnapshotDue(now); got != tc.want { + t.Errorf("%s: capabilitySnapshotDue = %v, want %v", tc.name, got, tc.want) + } + } +} + +// An unsettled build that repeats the previous answer waits twice as long for +// its scheduled rebuild each time, up to the settled interval, so a backend +// this FFmpeg cannot tone map on does not re-probe every minute for good. +func TestUnsettledCapabilitySnapshotBacksOff(t *testing.T) { + s := &Server{} + key := s.currentCapabilityKey() + unsettled := playback.HWAccelInfo{Resolved: playback.HWAccelNone, CapabilityHash: "same"} + var waits []time.Duration + for range 6 { + before := time.Now() + if !s.storeCapabilitySnapshotLocked(key, unsettled) { + t.Fatal("snapshot for the current key was not stored") + } + waits = append(waits, s.cachedCapability.Load().refreshAt.Sub(before).Round(time.Minute)) + } + want := []time.Duration{time.Minute, 2 * time.Minute, 4 * time.Minute, 8 * time.Minute, capabilitySnapshotInterval, capabilitySnapshotInterval} + if !slices.Equal(waits, want) { + t.Fatalf("scheduled waits = %v, want %v", waits, want) + } + unsettled.CapabilityHash = "changed" + s.storeCapabilitySnapshotLocked(key, unsettled) + if got := s.cachedCapability.Load().unsettledStreak; got != 0 { + t.Fatalf("streak after a changed answer = %d, want 0", got) + } +} diff --git a/internal/transcodenode/reprobe.go b/internal/transcodenode/reprobe.go index ded05c74bd4..bc2f584f9b7 100644 --- a/internal/transcodenode/reprobe.go +++ b/internal/transcodenode/reprobe.go @@ -81,6 +81,8 @@ func (s *Server) handleReprobeCapabilities(w http.ResponseWriter, r *http.Reques s.capabilityBuildMu.Lock() defer s.capabilityBuildMu.Unlock() + s.cachedCapability.Store(nil) + key := s.currentCapabilityKey() playback.InvalidateHWProbeCache() tonemap.InvalidateProbeCache() mediasample.InvalidateCapabilities() @@ -102,7 +104,10 @@ func (s *Server) handleReprobeCapabilities(w http.ResponseWriter, r *http.Reques previous := s.storedCapabilityHash() // A re-probed report is as authoritative as a scheduled snapshot, so health // starts advertising this hash immediately rather than at the next tick. - s.storeCapabilityHash(info.CapabilityHash) + if !s.storeCapabilitySnapshotLocked(key, info) { + http.Error(w, "capability probe unavailable", http.StatusServiceUnavailable) + return + } slog.InfoContext(r.Context(), "transcode node capabilities re-probed", "component", "transcodenode", "previous_hash", previous, "hash", info.CapabilityHash, "resolved", info.Resolved) w.Header().Set("Content-Type", "application/json") diff --git a/internal/transcodenode/server.go b/internal/transcodenode/server.go index f2bf00bf7a4..ee5889add8d 100644 --- a/internal/transcodenode/server.go +++ b/internal/transcodenode/server.go @@ -13,6 +13,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "strconv" "strings" "sync" @@ -560,6 +561,13 @@ type Server struct { // request completes. capabilityHash atomic.Pointer[string] + // cachedCapability holds the last complete capability snapshot assembled for + // the active config and node identity. /hw-capabilities serves it directly + // instead of re-running ffmpeg transformation smoke probes on every API + // cache refresh, while the 15-minute background refresh and operator + // re-probe bypass it and rebuild against live hardware. + cachedCapability atomic.Pointer[cachedTranscodeCapabilitySnapshot] + // metrics samples host and GPU resources in the background. Nil until // StartMetricsSampler runs, which leaves health exactly as it was before. metrics *nodemetrics.Sampler @@ -599,6 +607,149 @@ func (s *Server) storeCapabilityHash(hash string) { s.capabilityHash.Store(&hash) } +type transcodeCapabilityKey struct { + ffmpegPath string + hwAccel string + hwDevice string + nodeRowID int + nodeRowKnown bool + hasCoreAndOpener bool +} + +type cachedTranscodeCapabilitySnapshot struct { + key transcodeCapabilityKey + info playback.HWAccelInfo + // expiresAt is zero for a settled snapshot, which serves until the key + // changes or a refresh replaces it. + expiresAt time.Time + // refreshAt is when the scheduled refresh rebuilds it. + refreshAt time.Time + // unsettledStreak counts the unsettled builds in a row that reported the + // same hash, and backs their scheduled rebuilds off. + unsettledStreak int +} + +// unsettledCapabilitySnapshotTTL bounds how long a snapshot whose configured +// hardware did not verify is served. A failed GPU probe is often transient (a +// busy or still-initializing device), and the probe caches under it retry +// after about this long, so the node picks working hardware back up instead of +// advertising a software-only inventory until the next scheduled refresh. +const unsettledCapabilitySnapshotTTL = 15 * time.Second + +func (s *Server) currentCapabilityKey() transcodeCapabilityKey { + key := transcodeCapabilityKey{ + hwAccel: playback.HWAccelNone, + hasCoreAndOpener: s.core != nil && s.opener != nil, + } + if s.watcher != nil { + if cfg := s.watcher.Config(); cfg != nil { + key.ffmpegPath = cfg.Playback.FFmpegPath + key.hwAccel = cfg.Playback.HWAccel + key.hwDevice = cfg.Playback.HWDevice + } + } + if s.nodeRowID != nil { + key.nodeRowID, key.nodeRowKnown = s.nodeRowID() + } + return key +} + +// cachedCapabilitySnapshot returns the snapshot to serve for key, if one is +// current. +func (s *Server) cachedCapabilitySnapshot(key transcodeCapabilityKey) (playback.HWAccelInfo, bool) { + snap := s.cachedCapability.Load() + if snap == nil || snap.key != key || (!snap.expiresAt.IsZero() && !time.Now().Before(snap.expiresAt)) { + return playback.HWAccelInfo{}, false + } + return snap.info, true +} + +// storeCapabilitySnapshotLocked caches info as the report for key, the +// configuration and identity read before the build, and publishes its hash. +// The caller holds capabilityBuildMu, so a scheduled refresh cannot overwrite a +// re-probe that finished after it. Nothing is published unless key is still +// current: a build that read configuration changing underneath it describes +// neither the old key nor the new one, and the caller must not serve it either. +func (s *Server) storeCapabilitySnapshotLocked(key transcodeCapabilityKey, info playback.HWAccelInfo) bool { + if key != s.currentCapabilityKey() { + // Health keeps the previous hash: the next build describes the new + // key, and advertising this one would move the hash twice. + s.cachedCapability.Store(nil) + return false + } + s.storeCapabilityHash(info.CapabilityHash) + now := time.Now() + snap := &cachedTranscodeCapabilitySnapshot{key: key, info: info, refreshAt: now.Add(capabilitySnapshotInterval)} + switch retryAt, probeRetries := tonemap.ProbeRetryAt(playback.ResolveFFmpegPath(key.ffmpegPath), info.Resolved, key.hwDevice); { + case !configuredHardwareVerified(key.hwAccel, info): + snap.expiresAt = now.Add(unsettledCapabilitySnapshotTTL) + // A failure that repeats with the same answer is less likely to be a + // passing one, and may be a backend this FFmpeg cannot tone map on, so + // each repeat waits twice as long, up to the settled interval. + if prev := s.cachedCapability.Load(); prev != nil && !prev.expiresAt.IsZero() && prev.key == key && prev.info.CapabilityHash == info.CapabilityHash { + snap.unsettledStreak = prev.unsettledStreak + 1 + } + snap.refreshAt = now.Add(min(unsettledCapabilityRefreshInterval< 0 { - notAnswering.Delete(nodepool.NormalizeNodeURL(b.nodeURL)) + notAnswering.Delete(b.nodeKey) } return n, err } func (b *watchedBody) Close() error { + b.reading.Store(0) + if b.watch != nil { + b.watch.timer.Stop() + b.watch.retire() + b.watch = nil + } b.cancel(nil) return b.ReadCloser.Close() } diff --git a/web/src/App.tsx b/web/src/App.tsx index 9956f0d50df..00a6663b1e8 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -70,7 +70,11 @@ import LegacyRequestDetailRedirect from "@/pages/LegacyRequestDetailRedirect"; import { buildLegacyWebhookSyncRedirectTarget } from "@/lib/webhookSync"; import { guardRedirectTarget } from "@/lib/authRedirect"; import { toast } from "sonner"; -import { prefetchRouteChunks, type RouteChunkImport } from "@/lib/routeChunkPrefetch"; +import { + prefetchRouteChunks, + scheduleWhenIdle, + type RouteChunkImport, +} from "@/lib/routeChunkPrefetch"; import { loadImageCapabilities } from "@/lib/artworkWidths"; import { useCriticalContentLoaded } from "@/lib/startupPriority"; import { importCatalog } from "@/pages/catalogRoute"; @@ -82,6 +86,8 @@ const importItemDetail = () => import("@/pages/ItemDetail/index"); const importPersonDetail = () => import("@/pages/PersonDetail"); const importCollections = () => import("@/pages/Collections"); const importRecommendations = () => import("@/pages/Recommendations"); +const importWatchRoute = () => import("@/pages/WatchRoute"); +const importWatchPage = () => import("@/player/components/WatchPage"); const AdminLayout = lazy(() => import("@/components/AdminLayout")); const AdminDownloadPreparationsRefresh = lazy( @@ -176,7 +182,7 @@ const AccountSettings = lazy(() => import("@/pages/settings/AccountSettings")); const WatchPartyHub = lazy(() => import("@/pages/watchtogether/WatchPartyHub")); const WatchPartyInvite = lazy(() => import("@/pages/watchtogether/WatchPartyInvite")); const WatchTogetherRoomPage = lazy(() => import("@/pages/watchtogether/WatchTogetherRoomPage")); -const WatchRoute = lazy(() => import("@/pages/WatchRoute")); +const WatchRoute = lazy(importWatchRoute); /** * Routes a browsing session reaches within the first few interactions. Home @@ -192,6 +198,8 @@ const HOT_ROUTE_CHUNKS: readonly RouteChunkImport[] = [ importPersonDetail, importRecommendations, importCollections, + importWatchRoute, + importWatchPage, ]; /** Announces route changes to screen readers via an aria-live region. */ @@ -916,6 +924,8 @@ function AdminRealtimeEventChannels() { } function PlaybackCapabilityPrewarmer() { + const { user } = useAuth(); + const isAuthenticated = Boolean(user); useEffect(() => { void import("@/player/hooks/useCodecDetection") .then(({ prewarmCodecDetection }) => prewarmCodecDetection()) @@ -924,6 +934,25 @@ function PlaybackCapabilityPrewarmer() { // failed warm-up only costs that probe's wait when playback starts. }); }, []); + useEffect(() => { + // The browser decoder probe can start a GPU process and compile shaders, + // which takes seconds on some drivers. Only a signed-in session can play, + // so the login screen never pays for it, and it waits for an idle moment + // rather than competing with the first paint. + if (!isAuthenticated) return; + return scheduleWhenIdle(() => { + void Promise.all([import("@/player/engine/settings"), import("@/player/engine/capabilities")]) + .then(([{ isBrowserDecodingEnabled }, { probeEngineCapabilities }]) => { + if (isBrowserDecodingEnabled()) { + return probeEngineCapabilities(); + } + return null; + }) + .catch(() => { + // The watch page probes on mount if idle warm-up failed. + }); + }); + }, [isAuthenticated]); return null; } diff --git a/web/src/hooks/queries/items.ts b/web/src/hooks/queries/items.ts index 78ab562b85c..996199aae6a 100644 --- a/web/src/hooks/queries/items.ts +++ b/web/src/hooks/queries/items.ts @@ -78,7 +78,7 @@ export function useWatchDetail(id: string | undefined, fileId?: number, libraryI queryKey: itemKeys.watchDetail(id!, fileId, libraryId), queryFn: () => fetchWatchDetail(id!, fileId, libraryId), enabled: !!id, - staleTime: 0, + staleTime: 15_000, }); } diff --git a/web/src/hooks/useViewTransition.ts b/web/src/hooks/useViewTransition.ts index 30bd4f35b86..e62debf1f4c 100644 --- a/web/src/hooks/useViewTransition.ts +++ b/web/src/hooks/useViewTransition.ts @@ -27,6 +27,9 @@ export function shouldUseRouteViewTransition( currentPathname: string, targetPathname: string, ): boolean { + // Navigating into the player should never wait on a full-page View Transition + // snapshot before mounting WatchRoute and starting playback. + if (targetPathname.startsWith("/watch/")) return false; if (!isHomeItemBoundary(currentPathname, targetPathname)) return true; if (typeof window === "undefined" || typeof window.matchMedia !== "function") return true; return !window.matchMedia(DESKTOP_SIDEBAR_QUERY).matches; diff --git a/web/src/pages/ItemDetail/components/ActionBar.tsx b/web/src/pages/ItemDetail/components/ActionBar.tsx index ec79216eb18..db6abcf9d29 100644 --- a/web/src/pages/ItemDetail/components/ActionBar.tsx +++ b/web/src/pages/ItemDetail/components/ActionBar.tsx @@ -15,6 +15,7 @@ import { } from "react"; import { createPortal } from "react-dom"; import { useLocation, useNavigate } from "react-router"; +import { useQueryClient } from "@tanstack/react-query"; import { type LucideIcon, Heart, @@ -60,7 +61,12 @@ import type { FileVersion, PlaybackVariant } from "@/api/types"; import { canReportIssues, type IssueTarget, type IssueTargetKind } from "@/api/v2/issues"; import { ReportProblemDialog } from "@/components/issues/ReportProblemDialog"; import { useIssueStatus } from "@/hooks/queries/issues"; -import type { RedetectMarkersKind, RefreshItemMetadataMode } from "@/hooks/queries/items"; +import { + fetchWatchDetail, + type RedetectMarkersKind, + type RefreshItemMetadataMode, +} from "@/hooks/queries/items"; +import { itemKeys } from "@/hooks/queries/keys"; import type { PlayerSubtitleTrackSignature, PrePlaySubtitleSelection, @@ -410,6 +416,7 @@ export default function ActionBar({ const navigate = useNavigate(); const location = useLocation(); const playbackController = useWatchPlaybackController(); + const queryClient = useQueryClient(); const [playChoiceOpen, setPlayChoiceOpen] = useState(false); const [overflowOpen, setOverflowOpen] = useState(false); // The admin and curation actions open in a second menu beside this one. @@ -540,6 +547,28 @@ export default function ActionBar({ selectedVersion, ], ); + // Prefetch the watch detail payload when the viewer reaches for Play, so the + // click can open the player and dispatch POST /api/v2/playback/start without + // a blocking watch-detail round trip. Doing it on intent rather than on mount + // keeps browsing from costing a watch-detail read for every page viewed. The + // player chunk is already warmed after sign-in (HOT_ROUTE_CHUNKS). + const prefetchPlayback = useCallback(() => { + if (!playHref) return; + const parsed = parseWatchHref(playHref); + if (!parsed) return; + const targetFileId = selectedVersion?.file_id ?? parsed.fileId; + void queryClient.prefetchQuery({ + queryKey: itemKeys.watchDetail(parsed.contentId, targetFileId, parsed.libraryId), + queryFn: () => fetchWatchDetail(parsed.contentId, targetFileId, parsed.libraryId), + staleTime: 15_000, + }); + }, [playHref, queryClient, selectedVersion?.file_id]); + const playIntentHandlers = { + onPointerEnter: prefetchPlayback, + onPointerDown: prefetchPlayback, + onFocus: prefetchPlayback, + }; + const handleResumePlayback = () => { if (!playHref) return; setPlayChoiceOpen(false); @@ -1138,6 +1167,7 @@ export default function ActionBar({ ) : playHref ? ( showPlayChoiceDialog ? ( ) : selectedVersion ? ( ) : (