Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/api/handlers/playback_v3.go
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ func (h *PlaybackHandler) localToneMapCapabilitiesV3(ctx context.Context) (tonem
if h.v3ToneMapProbe != nil {
probe = h.v3ToneMapProbe
}
capabilities, err := probe(ctx, ffmpegPath, resolved, hwDevice)
capabilities, err := probe(ctx, ffmpegPath, resolved, playback.ToneMapProbeDevice(hwDevice, resolved))
return append(tonemap.Capabilities(nil), capabilities...), err
}

Expand Down
2 changes: 1 addition & 1 deletion internal/downloads/artifacts.go
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ func (m *ArtifactManager) localToneMapCapabilities(ctx context.Context) (tonemap
if err := ctx.Err(); err != nil {
return nil, err
}
return tonemap.Probe(ctx, playback.ResolveFFmpegPath(cfg.Playback.FFmpegPath), backend, cfg.Playback.HWDevice)
return tonemap.Probe(ctx, playback.ResolveFFmpegPath(cfg.Playback.FFmpegPath), backend, playback.ToneMapProbeDevice(cfg.Playback.HWDevice, backend))
}

// is4KDownloadSource applies the download transcode gate to either probed track
Expand Down
2 changes: 1 addition & 1 deletion internal/jellycompat/handlers_playback.go
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,7 @@ func (h *PlaybackHandler) localToneMapCapabilities(ctx context.Context) (tonemap
if h.compatToneMapProbe != nil {
probe = h.compatToneMapProbe
}
return probe(ctx, playback.ResolveFFmpegPath(h.FFmpegPath), backend, hwDevice)
return probe(ctx, playback.ResolveFFmpegPath(h.FFmpegPath), backend, playback.ToneMapProbeDevice(hwDevice, backend))
}

// remoteToneMapCapabilities retrieves one transcode node's authenticated,
Expand Down
61 changes: 40 additions & 21 deletions internal/playback/hwdevice.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,38 @@ func hwAccelBalancesRenderDevices(hwAccel string) bool {
return hwAccel == "qsv" || hwAccel == "vaapi"
}

// defaultHWDevice is the render node a QSV or VAAPI workload runs on when
// playback.hw_device is empty, or "" when the host has none.
//
// It is the device auto-detection verified the backend on, not whatever sorts
// first under /dev/dri, which on a mixed-vendor host is a different GPU. With
// nothing verified it falls back to that first render node, the one
// appendHWAccelArgs resolves an empty value to. Nothing verified is not only the
// cold-process case: an explicitly configured backend short-circuits
// resolution, so a host running hw_accel=qsv with no hw_device never walks its
// hardware.
func defaultHWDevice(resolvedHWAccel string) string {
if verified := VerifiedHWDevice(resolvedHWAccel); verified != "" {
return verified
}
return detectRenderDevice(defaultDRIDir)
}

// ToneMapProbeDevice returns the hw_device value to probe hardware tone mapping
// with for a resolved backend: the configured value when there is one, and
// otherwise, for QSV and VAAPI, the render node a transcode will open
// (defaultHWDevice).
//
// Passing the empty configured value instead leaves the probe on tonemap's
// fixed /dev/dri/renderD128, so a host whose GPU is at another render node
// verifies QSV for encoding and still tone maps every HDR transcode in software.
func ToneMapProbeDevice(configured, resolvedHWAccel string) string {
Comment thread
Quick104 marked this conversation as resolved.
Resolved
if !ParseHWDeviceSet(configured).Empty() || !hwAccelBalancesRenderDevices(resolvedHWAccel) {
return configured
}
return defaultHWDevice(resolvedHWAccel)
}

// presentHWDevices filters a device list to the entries that exist, falling
// back to the first entry when none do so the failure mode stays
// deterministic (ffmpeg reports the missing device, matching the historical
Expand Down Expand Up @@ -205,9 +237,10 @@ var nvencMultiDeviceWarnOnce sync.Once
// "auto"). The returned release must be called exactly once when the ffmpeg
// process for this workload has exited; it is idempotent and a no-op for
// workloads that were not counted (a software accelerator, or a GPU accelerator
// with no configured device to name).
// with no device to name).
//
// - Empty value: returns "" so downstream auto-detection applies.
// - Empty value with QSV/VAAPI: the render node defaultHWDevice names,
// counted, or "" when the host has none, so FFmpeg picks downstream.
// - Single value: passes through unchanged for every accelerator, and is
// counted for the GPU accelerators, because a node with one GPU is the
// common deployment and its sessions have to be reportable too.
Expand Down Expand Up @@ -260,25 +293,11 @@ func acquireHWDevice(configured, resolvedHWAccel, avoidDevice string) (device, w
}
// No configured device. Resolving it here rather than leaving it to
// PickRenderDevice downstream fixes two things at once: the workload
// runs on the render node auto-detection actually verified this backend
// on — not on whatever sorts first under /dev/dri, which on a
// mixed-vendor host is a different GPU — and it becomes countable, so a
// default-configured node stops reporting zero sessions beside a busy
// engine. With no verified device (nothing probed yet, or a backend
// named explicitly and never walked) this falls through unchanged and
// ffmpeg picks one downstream exactly as before.
if verified := VerifiedHWDevice(resolvedHWAccel); verified != "" {
return verified, verified, countHWDeviceWorkload(verified)
}
// Nothing verified. That is not only the cold-process case: an
// explicitly configured backend short-circuits resolution, so a host
// running hw_accel=qsv with no hw_device never walks its hardware at all
// and would otherwise never name a device here — reporting zero GPU
// sessions for every transcode it runs. Fall back to the device
// execution is about to pick anyway, which is this same first render
// node; appendHWAccelArgs resolves an empty value the same way.
if detected := detectRenderDevice(defaultDRIDir); detected != "" {
return detected, detected, countHWDeviceWorkload(detected)
// runs on the render node defaultHWDevice names, and it becomes
// countable, so a default-configured node stops reporting zero sessions
// beside a busy engine.
if fallback := defaultHWDevice(resolvedHWAccel); fallback != "" {
return fallback, fallback, countHWDeviceWorkload(fallback)
}
return "", "", noop
}
Expand Down
57 changes: 57 additions & 0 deletions internal/playback/tone_map_source_validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package playback
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"

"github.com/Silo-Server/silo-server/internal/tonemap"
Expand All @@ -24,6 +26,61 @@ func TestToneMapPathHashFailureIsTransient(t *testing.T) {
}
}

// With hw_accel=auto and no hw_device, the tone-map probe has to smoke-test the
// GPU detection verified and execution will open: not a fixed renderD128 the
// host may not have (#5918), and not the first render node, which here belongs
// to another vendor.
func TestResolveToneMapExecutorProbesTheVerifiedRenderDevice(t *testing.T) {
env := setupHWAccelTest(t)
env.addRenderDevice(t, "renderD128", "0x1002")
env.addRenderDevice(t, "renderD129", "0x8086")
device := filepath.Join(env.driDir, "renderD129")
t.Cleanup(tonemap.InvalidateProbeCache)

dir := t.TempDir()
ffmpeg, logPath := filepath.Join(dir, "ffmpeg"), filepath.Join(dir, "commands.log")
script := "#!/bin/sh\n" +
fmt.Sprintf("printf '%%s\\n' \"$*\" >> %q\n", logPath) +
"case \"$*\" in\n" +
" *-hwaccels*) echo qsv ;;\n" +
" *-encoders*) printf ' V..... h264_qsv\\n V..... hevc_qsv\\n V..... libx264\\n' ;;\n" +
" *-filters*) printf ' ... tonemap_opencl\\n ... hwmap\\n ... scale_vaapi\\n ... overlay_opencl\\n ... scale_opencl\\n ... tonemapx\\n ... zscale\\n ... sidedata\\n' ;;\n" +
"esac\n"
if err := os.WriteFile(ffmpeg, []byte(script), 0o755); err != nil {
t.Fatal(err)
}

opts, err := ResolveToneMapExecutor(context.Background(), TranscodeOpts{
FFmpegPath: ffmpeg,
HWAccel: HWAccelAuto,
ToneMapPolicy: tonemap.PolicyHardwareOnly,
ToneMapMode: tonemap.ModeHardware,
ToneMapSourceKind: tonemap.SourcePQ,
ToneMapRecipeVersion: TransformationHDRToSDRToneMapRecipeVersionV3,
ToneMapSourceRevision: tonemap.SourceRevision{MediaFileID: 1, FileSize: 5},
})
if err != nil {
t.Fatalf("ResolveToneMapExecutor() error = %v, want the QSV executor detection verified", err)
}
if opts.HWAccel != transcodeHWQSV || opts.ToneMapFilter != tonemap.HardwareFilterOpenCL {
t.Fatalf("executor = %s/%s, want qsv/%s", opts.HWAccel, opts.ToneMapFilter, tonemap.HardwareFilterOpenCL)
}
logged := fakeFFmpegLog(t, fakeFFmpegBinary{path: ffmpeg, logPath: logPath})
smokes := 0
for _, line := range strings.Split(logged, "\n") {
if !strings.Contains(line, tonemap.HardwareFilterOpenCL) {
continue
}
smokes++
if !strings.Contains(line, device) {
t.Fatalf("hardware tone-map smoke ran on another device, want %s: %s", device, line)
}
}
if smokes == 0 {
t.Fatalf("no hardware tone-map smoke ran; commands:\n%s", logged)
}
}

func TestResolveToneMapExecutorClassifiesCanceledProbeAsUnavailable(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
Expand Down
2 changes: 1 addition & 1 deletion internal/playback/transcode.go
Original file line number Diff line number Diff line change
Expand Up @@ -1056,7 +1056,7 @@ func ResolveToneMapExecutor(ctx context.Context, opts TranscodeOpts) (TranscodeO
return opts, fmt.Errorf("incomplete tone-map recipe")
}
backend := ResolveHWAccelWithFFmpegContext(ctx, opts.HWAccel, opts.FFmpegPath, opts.HWDevice)
capabilities, err := tonemap.Probe(ctx, ResolveFFmpegPath(opts.FFmpegPath), backend, opts.HWDevice)
capabilities, err := tonemap.Probe(ctx, ResolveFFmpegPath(opts.FFmpegPath), backend, ToneMapProbeDevice(opts.HWDevice, backend))
if err != nil {
return opts, fmt.Errorf("%w: probe tone-map executor: %w", ErrToneMapExecutorUnavailable, err)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/transcodenode/capability_snapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ func TestUnsettledCapabilitySnapshotBacksOff(t *testing.T) {
var waits []time.Duration
for range 6 {
before := time.Now()
if !s.storeCapabilitySnapshotLocked(key, unsettled) {
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))
Expand All @@ -206,7 +206,7 @@ func TestUnsettledCapabilitySnapshotBacksOff(t *testing.T) {
t.Fatalf("scheduled waits = %v, want %v", waits, want)
}
unsettled.CapabilityHash = "changed"
s.storeCapabilitySnapshotLocked(key, unsettled)
s.storeCapabilitySnapshotLocked(key, unsettled, "")
if got := s.cachedCapability.Load().unsettledStreak; got != 0 {
t.Fatalf("streak after a changed answer = %d, want 0", got)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/transcodenode/reprobe.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (s *Server) handleReprobeCapabilities(w http.ResponseWriter, r *http.Reques

// buildCapabilitySnapshotLocked owns the probe deadline, so a re-probe can
// never cost more than a cold capability fetch already may.
info, err := s.buildCapabilitySnapshotLocked(r.Context())
info, toneMapDevice, err := s.buildCapabilitySnapshotLocked(r.Context())
if err != nil {
slog.WarnContext(r.Context(), "transcode node capability re-probe incomplete",
"component", "transcodenode", "error", err)
Expand All @@ -104,7 +104,7 @@ 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.
if !s.storeCapabilitySnapshotLocked(key, info) {
if !s.storeCapabilitySnapshotLocked(key, info, toneMapDevice) {
http.Error(w, "capability probe unavailable", http.StatusServiceUnavailable)
return
}
Expand Down
28 changes: 17 additions & 11 deletions internal/transcodenode/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -670,7 +670,10 @@ func (s *Server) cachedCapabilitySnapshot(key transcodeCapabilityKey) (playback.
// 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 {
// toneMapDevice is the device the build probed tone mapping on, which keys the
// probe's cache; the build hands it over so the retry lookup reads the entry
// that probe wrote.
func (s *Server) storeCapabilitySnapshotLocked(key transcodeCapabilityKey, info playback.HWAccelInfo, toneMapDevice string) 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.
Expand All @@ -680,7 +683,7 @@ func (s *Server) storeCapabilitySnapshotLocked(key transcodeCapabilityKey, info
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); {
switch retryAt, probeRetries := tonemap.ProbeRetryAt(playback.ResolveFFmpegPath(key.ffmpegPath), info.Resolved, toneMapDevice); {
case !configuredHardwareVerified(key.hwAccel, info):
snap.expiresAt = now.Add(unsettledCapabilitySnapshotTTL)
// A failure that repeats with the same answer is less likely to be a
Expand Down Expand Up @@ -1695,13 +1698,13 @@ func (s *Server) buildCapabilitySnapshot(ctx context.Context) (playback.HWAccelI
s.capabilityBuildMu.Lock()
defer s.capabilityBuildMu.Unlock()
key := s.currentCapabilityKey()
info, err := s.buildCapabilitySnapshotLocked(ctx)
info, toneMapDevice, 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) {
if !s.storeCapabilitySnapshotLocked(key, info, toneMapDevice) {
return playback.HWAccelInfo{}, errCapabilitySnapshotSuperseded
}
return info, nil
Expand All @@ -1710,8 +1713,10 @@ func (s *Server) buildCapabilitySnapshot(ctx context.Context) (playback.HWAccelI
// 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
// with.
func (s *Server) buildCapabilitySnapshotLocked(ctx context.Context) (playback.HWAccelInfo, error) {
// with. It also returns the device it probed tone mapping on, for
// storeCapabilitySnapshotLocked: with no hw_device that is the detected render
// node, which can change before the store, so it is chosen once, here.
func (s *Server) buildCapabilitySnapshotLocked(ctx context.Context) (playback.HWAccelInfo, string, error) {
ffmpegPath := ""
configuredHWAccel := playback.HWAccelNone
hwDevice := ""
Expand All @@ -1731,17 +1736,18 @@ func (s *Server) buildCapabilitySnapshotLocked(ctx context.Context) (playback.HW
// regression for hardware that is fine.
info, err := playback.DetectHWAccelWithFFmpegContextResult(resolveCtx, configuredHWAccel, ffmpegPath, hwDevice)
if err != nil {
return playback.HWAccelInfo{}, err
return playback.HWAccelInfo{}, "", err
}
info.ProbeRequestTimeoutMillis = playback.CapabilityRequestTimeout(configuredHWAccel, hwDevice).Milliseconds()
capabilities, err := tonemap.Probe(resolveCtx, playback.ResolveFFmpegPath(ffmpegPath), info.Resolved, hwDevice)
toneMapDevice := playback.ToneMapProbeDevice(hwDevice, info.Resolved)
capabilities, err := tonemap.Probe(resolveCtx, playback.ResolveFFmpegPath(ffmpegPath), info.Resolved, toneMapDevice)
if err != nil {
return playback.HWAccelInfo{}, err
return playback.HWAccelInfo{}, "", err
}
info.ToneMapCapabilities = capabilities
registry, err := playback.ProbeTransformationRegistryWithToneMapV3Result(resolveCtx, ffmpegPath, info.ToneMapCapabilities)
if err != nil {
return playback.HWAccelInfo{}, err
return playback.HWAccelInfo{}, "", err
}
info.Transformations = registry.Advertised()
// Progressive remux tokens bind execution to the stable stream_nodes row.
Expand All @@ -1761,7 +1767,7 @@ func (s *Server) buildCapabilitySnapshotLocked(ctx context.Context) (playback.HW
playback.TransportFeatureHLSSubtitleRenditionV1, playback.TransportFeatureHLSRemuxSubtitleRenditionV1,
playback.TransportFeatureHLSOnDemandSubtitleRenditionsV1, playback.TransportFeatureAudiobookHLSV1)
info.CapabilityHash = playback.ComputeCapabilityHash(info)
return info, nil
return info, toneMapDevice, nil
}

// handleHWCapabilities reports the node's smoke-tested capabilities: the
Expand Down