Skip to content
Merged
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
60 changes: 43 additions & 17 deletions internal/api/handlers/playback.go
Original file line number Diff line number Diff line change
Expand Up @@ -1137,32 +1137,51 @@ func adjustPlaybackForSelectedAudio(
transcodeAudio bool,
audioTrackIndex int,
preserveDirectAudioSelection bool,
) (playback.PlayMethod, bool) {
) (playback.PlayMethod, bool, int) {
if file == nil || len(file.AudioTracks) == 0 || audioTrackIndex < 0 || audioTrackIndex >= len(file.AudioTracks) {
return method, transcodeAudio
return method, transcodeAudio, audioTrackIndex
}

selectedTrack := file.AudioTracks[audioTrackIndex]
audioSupported := clientSupportsAudioCodec(req, selectedTrack.Codec)
audioSupported := clientSupportsAudioCodec(req, file.AudioTracks[audioTrackIndex].Codec)

// When the selected track is undecodable, prefer switching tracks over
// re-encoding. A Blu-ray remux usually ships a lossy companion in the same
// language beside its lossless default, and copying that beats re-encoding
// on every axis: no CPU, no quality loss, and surround survives instead of
// collapsing to stereo. Only re-encode when no decodable track exists.
//
// Never applied when the caller named a track. An explicit audio_track_index
// is the user's choice, and silently playing different audio than they asked
// for is worse than re-encoding what they picked -- so re-selection only fills
// in for a default the client cannot decode, never overrides an instruction.
if !audioSupported && req.AudioTrackIndex == nil && !preserveDirectAudioSelection {
if idx, ok := playback.SelectClientPlayableAudioTrack(
file.AudioTracks, audioTrackIndex, req.CodecsAudio, req.MaxAudioChannels,
); ok {
audioTrackIndex = idx
audioSupported = true
}
}

switch method {
case playback.PlayDirect:
if preserveDirectAudioSelection {
return playback.PlayDirect, false
return playback.PlayDirect, false, audioTrackIndex
}
// Direct play cannot force the browser onto a non-default audio stream.
// Promote to remux so ffmpeg can map the selected track explicitly.
// Direct play cannot force the player onto a non-default audio stream --
// it serves the container and the player takes the default track. Promote
// to remux so ffmpeg can map the chosen one explicitly.
if audioTrackIndex != directPlayAudioTrackIndex(file) {
return playback.PlayRemux, !audioSupported
return playback.PlayRemux, !audioSupported, audioTrackIndex
}
if !audioSupported {
return playback.PlayRemux, true
return playback.PlayRemux, true, audioTrackIndex
}
return method, false
return method, false, audioTrackIndex
case playback.PlayRemux:
return method, !audioSupported
return method, !audioSupported, audioTrackIndex
default:
return method, transcodeAudio
return method, transcodeAudio, audioTrackIndex
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Expand Down Expand Up @@ -1193,9 +1212,9 @@ func resolvePlaybackMethodForFile(
req startPlaybackRequest,
audioTrackIndex int,
adminSettings playback.AdminSettings,
) (playback.PlayMethod, bool) {
) (playback.PlayMethod, bool, int) {
if file == nil {
return "", false
return "", false, audioTrackIndex
}

caps := playback.ClientCapabilities{
Expand Down Expand Up @@ -1225,7 +1244,7 @@ func (h *PlaybackHandler) resolveCapabilityPlaybackSelection(

audioTrackIndex = normalizeAudioTrackIndex(requestedFile, audioTrackIndex)
adminSettings := playbackAdminSettingsFromRequest(ctx, h.SettingsRepo, h.playbackConfig().TranscodeEnabled)
method, transcodeAudio := resolvePlaybackMethodForFile(requestedFile, req, audioTrackIndex, adminSettings)
method, transcodeAudio, audioTrackIndex := resolvePlaybackMethodForFile(requestedFile, req, audioTrackIndex, adminSettings)

if requestedFile.Resolution == "2160p" &&
method == playback.PlayTranscode &&
Expand All @@ -1248,7 +1267,7 @@ func (h *PlaybackHandler) resolveCapabilityPlaybackSelection(
)
}
audioTrackIndex = effectiveAudioTrackIndex
method, transcodeAudio = resolvePlaybackMethodForFile(effectiveFile, req, audioTrackIndex, adminSettings)
method, transcodeAudio, audioTrackIndex = resolvePlaybackMethodForFile(effectiveFile, req, audioTrackIndex, adminSettings)
return effectiveFile, method, transcodeAudio, audioTrackIndex
}
}
Expand Down Expand Up @@ -1853,7 +1872,7 @@ func (h *PlaybackHandler) handleStartPlaybackLegacy(w http.ResponseWriter, r *ht
preserveDirectAudioSelection := method == playback.PlayDirect &&
strings.EqualFold(req.PlayMethod, string(playback.PlayDirect)) &&
req.PreserveDirectAudioSelection
method, transcodeAudio = adjustPlaybackForSelectedAudio(
method, transcodeAudio, audioTrackIndex = adjustPlaybackForSelectedAudio(
effectiveFile,
req,
method,
Expand Down Expand Up @@ -3221,6 +3240,10 @@ func (h *PlaybackHandler) HandleStartTranscode(w http.ResponseWriter, r *http.Re
// TrueHD/MLP/DTS — software TrueHD decode is a known stall source.
audioTrackIndex := session.AudioTrackIndex
sourceAudioCodec := ""
// Probed channel count of the track we actually map. The channel resolvers
// need it to honor "never exceed the source" -- without it a stereo track
// asked for at a 5.1 ceiling gets upmixed into channels it does not have.
sourceAudioChannels := 0
if playback.TranscodesAudio(req.TargetCodecAudio) && len(file.AudioTracks) > 0 {
preferred := playback.PreferTranscodeFriendlyAudioTrack(file.AudioTracks, audioTrackIndex)
if preferred != audioTrackIndex {
Expand All @@ -3235,6 +3258,7 @@ func (h *PlaybackHandler) HandleStartTranscode(w http.ResponseWriter, r *http.Re
audioTrackIndex = preferred
}
sourceAudioCodec = playback.AudioTrackCodecAt(file.AudioTracks, audioTrackIndex)
sourceAudioChannels = playback.AudioTrackChannelsAt(file.AudioTracks, audioTrackIndex)
}

requestedFile := file
Expand Down Expand Up @@ -3449,6 +3473,7 @@ func (h *PlaybackHandler) HandleStartTranscode(w http.ResponseWriter, r *http.Re
InputPath: file.FilePath,
SourceVideoCodec: file.CodecVideo,
SourceAudioCodec: sourceAudioCodec,
SourceAudioChannels: sourceAudioChannels,
VideoBitstreamFilter: videoBitstreamFilter,
SeekSeconds: transportSeekSeconds,
StreamOriginSeconds: streamOriginSeconds,
Expand Down Expand Up @@ -3585,6 +3610,7 @@ func (h *PlaybackHandler) HandleStartTranscode(w http.ResponseWriter, r *http.Re
SessionID: req.SessionID,
SourceVideoCodec: file.CodecVideo,
SourceAudioCodec: sourceAudioCodec,
SourceAudioChannels: sourceAudioChannels,
VideoBitstreamFilter: videoBitstreamFilter,
SeekSeconds: transportSeekSeconds,
StreamOriginSeconds: streamOriginSeconds,
Expand Down
5 changes: 3 additions & 2 deletions internal/api/handlers/playback_v3.go
Original file line number Diff line number Diff line change
Expand Up @@ -711,8 +711,9 @@ func (h *PlaybackHandler) prepareLocalTransportV3(r *http.Request, session *play
seekSeconds, startSegment := configureHLSTimelineV3(result.Plan, videoCodec, 2, float64(file.Duration))
audioTrackIndex := plannedAudioTrackIndexV3(result, session.AudioTrackIndex, file.AudioTracks)
sourceAudioCodec := playback.AudioTrackCodecAt(file.AudioTracks, audioTrackIndex)
sourceAudioChannels := playback.AudioTrackChannelsAt(file.AudioTracks, audioTrackIndex)
unlock := h.tm.LockSessionLifecycle(session.ID)
ts, err := h.startLocalPlaybackTransport(r.Context(), playback.TranscodeOpts{InputPath: file.FilePath, OutputDir: outputDir, OutputSubdir: outputSubdir, SessionID: session.ID, SourceVideoCodec: file.CodecVideo, SourceAudioCodec: sourceAudioCodec, SourceHeight: playback.SourceVideoHeight(file), VideoBitstreamFilter: videoBitstreamFilterForPlanV3(result.Plan), SeekSeconds: seekSeconds, StartSegmentNumber: startSegment, TargetResolution: result.TargetResolution, TargetCodecVideo: videoCodec, TargetCodecAudio: result.TargetAudioCodec, TargetAudioChannels: result.TargetAudioChannels, TargetBitrateKbps: result.TargetBitrateKbps, SegmentDuration: 2, FFmpegPath: cfg.FFmpegPath, HWAccel: cfg.HWAccel, HWDevice: cfg.HWDevice, AudioTrackIndex: audioTrackIndex, SubtitleTrackIndex: result.SubtitleTransportTrackIndex, SubtitleBurnIn: result.SubtitleBurnIn, SubtitleCodec: result.SubtitleCodec, TotalDuration: float64(file.Duration), FastStart: true, NodeType: "integrated", ExecutionMode: "integrated", FFmpegLogSink: h.FFmpegLogSink})
ts, err := h.startLocalPlaybackTransport(r.Context(), playback.TranscodeOpts{InputPath: file.FilePath, OutputDir: outputDir, OutputSubdir: outputSubdir, SessionID: session.ID, SourceVideoCodec: file.CodecVideo, SourceAudioCodec: sourceAudioCodec, SourceAudioChannels: sourceAudioChannels, SourceHeight: playback.SourceVideoHeight(file), VideoBitstreamFilter: videoBitstreamFilterForPlanV3(result.Plan), SeekSeconds: seekSeconds, StartSegmentNumber: startSegment, TargetResolution: result.TargetResolution, TargetCodecVideo: videoCodec, TargetCodecAudio: result.TargetAudioCodec, TargetAudioChannels: result.TargetAudioChannels, TargetBitrateKbps: result.TargetBitrateKbps, SegmentDuration: 2, FFmpegPath: cfg.FFmpegPath, HWAccel: cfg.HWAccel, HWDevice: cfg.HWDevice, AudioTrackIndex: audioTrackIndex, SubtitleTrackIndex: result.SubtitleTransportTrackIndex, SubtitleBurnIn: result.SubtitleBurnIn, SubtitleCodec: result.SubtitleCodec, TotalDuration: float64(file.Duration), FastStart: true, NodeType: "integrated", ExecutionMode: "integrated", FFmpegLogSink: h.FFmpegLogSink})
if err != nil {
unlock()
return preparedTransportV3{}, &transportErrorV3{reason: "transcode_start_failed", message: "Failed to start the playback transport.", retryable: true, cause: err}
Expand Down Expand Up @@ -769,7 +770,7 @@ func (h *PlaybackHandler) prepareRemoteTransportV3(r *http.Request, session *pla
}
seekSeconds, startSegment := configureHLSTimelineV3(result.Plan, videoCodec, 2, float64(file.Duration))
audioTrackIndex := plannedAudioTrackIndexV3(result, session.AudioTrackIndex, file.AudioTracks)
req := transcodenode.TranscodeStartRequest{SessionID: transportID, InputPath: file.FilePath, SourceVideoCodec: file.CodecVideo, SourceAudioCodec: playback.AudioTrackCodecAt(file.AudioTracks, audioTrackIndex), VideoBitstreamFilter: videoBitstreamFilterForPlanV3(result.Plan), SeekSeconds: seekSeconds, StartSegmentNumber: startSegment, TargetResolution: result.TargetResolution, TargetCodecVideo: videoCodec, TargetCodecAudio: result.TargetAudioCodec, TargetAudioChannels: result.TargetAudioChannels, TargetBitrateKbps: result.TargetBitrateKbps, SegmentDuration: 2, HWAccel: h.playbackConfig().HWAccel, AudioTrackIndex: audioTrackIndex, SubtitleTrackIndex: result.SubtitleTransportTrackIndex, SubtitleBurnIn: result.SubtitleBurnIn, SubtitleCodec: result.SubtitleCodec, TotalDuration: float64(file.Duration), RequireReady: true}
req := transcodenode.TranscodeStartRequest{SessionID: transportID, InputPath: file.FilePath, SourceVideoCodec: file.CodecVideo, SourceAudioCodec: playback.AudioTrackCodecAt(file.AudioTracks, audioTrackIndex), SourceAudioChannels: playback.AudioTrackChannelsAt(file.AudioTracks, audioTrackIndex), VideoBitstreamFilter: videoBitstreamFilterForPlanV3(result.Plan), SeekSeconds: seekSeconds, StartSegmentNumber: startSegment, TargetResolution: result.TargetResolution, TargetCodecVideo: videoCodec, TargetCodecAudio: result.TargetAudioCodec, TargetAudioChannels: result.TargetAudioChannels, TargetBitrateKbps: result.TargetBitrateKbps, SegmentDuration: 2, HWAccel: h.playbackConfig().HWAccel, AudioTrackIndex: audioTrackIndex, SubtitleTrackIndex: result.SubtitleTransportTrackIndex, SubtitleBurnIn: result.SubtitleBurnIn, SubtitleCodec: result.SubtitleCodec, TotalDuration: float64(file.Duration), RequireReady: true}
nodeResp, status, err := h.startRemotePlaybackTransport(r.Context(), node.URL, req)
if err != nil {
// A timeout can fire after the node actually started the job; the
Expand Down
72 changes: 72 additions & 0 deletions internal/playback/audio_channels.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,75 @@ func AudioBitrateForChannels(channels int) string {
return "192k"
}
}

// ac3MaxChannels is the widest layout FFmpeg's AC-3 encoder accepts. Verified
// against the encoder in our own image rather than taken from documentation:
// `ffmpeg -h encoder=ac3` lists 5.1 as the largest supported channel layout,
// with no 6.1 or 7.1 mode (ATSC A/52 has none).
const ac3MaxChannels = audioChannels51

// EffectiveAC3Channels resolves the channel count to encode AC-3 at, or 0 to
// leave the layout to FFmpeg.
//
// This deliberately does not reuse EffectiveAudioChannels. That function's
// fragile-lossless rule collapses TrueHD to stereo, which is right for AAC --
// the stall it guards against is in the TrueHD-to-AAC path -- and wrong here:
// an AC-3 target exists precisely to carry surround to an HDMI receiver, so
// forcing stereo would defeat the only reason to choose it.
//
// Three caps, tightest wins:
//
// - Never exceed the source. Upmixing a stereo pair into a 5.1 bitstream
// invents channels and spends bitrate saying nothing.
// - Never exceed the client's declared ceiling (max_audio_channels). A device
// that reported 2 must not be handed 5.1.
// - Never exceed 5.1, which is all the encoder can do.
//
// Returns 0 when the source channel count is unknown and no client ceiling binds
// tighter than the encoder's own. FFmpeg's filter-graph negotiation then picks
// the widest layout the encoder supports that the input can fill -- which is the
// right answer, and better than the alternative of guessing 5.1 and upmixing a
// source that turns out to be stereo. Where we do know enough to choose, we
// choose: relying on negotiation is relying on it staying put.
//
// Unlike the AAC path, a client that declared nothing is left unconstrained
// rather than defaulted to stereo. Reaching this branch at all means something
// asked for an AC-3/E-AC-3 target, and that request is itself the surround
// signal the AAC default lacks.
func EffectiveAC3Channels(sourceChannels, maxChannels int) int {
ceiling := ac3MaxChannels
if maxChannels > 0 && maxChannels < ceiling {
ceiling = maxChannels
}
if sourceChannels > 0 && sourceChannels < ceiling {
ceiling = sourceChannels
}
if sourceChannels <= 0 && ceiling >= ac3MaxChannels {
return 0
}
for _, rung := range audioChannelLadder {
if rung <= ceiling {
return rung
}
}
// Unreachable while mono is the lowest rung, but a ladder change should not
// silently start returning 0 and re-enable negotiation by accident.
return audioChannelsMono
}

// AC3BitrateForChannels is the AC-3 bitrate to pair with a channel count.
//
// 448k is the conventional 5.1 rate (the format tops out at 640k); spending it
// on a stereo pair would only pad the stream.
func AC3BitrateForChannels(channels int) string {
switch {
case channels <= 0, channels >= audioChannels51:
// 0 means the layout is left to FFmpeg, which cannot exceed 5.1 here, so
// the surround rate is the safe pairing.
return "448k"
case channels >= audioChannelsStereo:
return "192k"
default:
return "96k"
}
}
69 changes: 69 additions & 0 deletions internal/playback/audio_channels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,72 @@ func TestEffectiveAudioChannelsPreservesMono(t *testing.T) {
t.Errorf("EffectiveAudioChannels(8, 1) = %d, want 1 (client ceiling)", got)
}
}

// EffectiveAC3Channels is capped by the encoder, the source, and the client's
// declared ceiling -- tightest wins. The 5.1 cap is not a style choice: our own
// image's `ffmpeg -h encoder=ac3` lists 5.1 as the widest supported layout.
func TestEffectiveAC3Channels(t *testing.T) {
cases := []struct {
name string
source, ceil int
want int
}{
{"7.1 source capped at the encoder's 5.1", 8, 8, 6},
{"no client ceiling still capped at 5.1", 8, 0, 6},
{"5.1 source passes through", 6, 6, 6},
{"stereo ceiling wins over a 5.1 source", 6, 2, 2},
{"stereo source is not upmixed to a 5.1 ceiling", 2, 6, 2},
{"mono source stays mono", 1, 6, 1},
{"mono ceiling honored from a surround source", 8, 1, 1},
{"odd ceiling snaps down to a real layout", 8, 5, 2},
{"unknown source with a binding ceiling still caps", 0, 2, 2},
{"over-claimed ceiling clamps to the encoder max", 8, 99, 6},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := EffectiveAC3Channels(tc.source, tc.ceil); got != tc.want {
t.Errorf("EffectiveAC3Channels(%d, %d) = %d, want %d", tc.source, tc.ceil, got, tc.want)
}
})
}
}

// 0 means "leave the layout to FFmpeg", which is only correct when we genuinely
// have nothing to go on. Guessing 5.1 there would upmix an unknown stereo source.
func TestEffectiveAC3ChannelsDefersWhenNothingIsKnown(t *testing.T) {
if got := EffectiveAC3Channels(0, 0); got != 0 {
t.Errorf("EffectiveAC3Channels(0, 0) = %d, want 0 (defer to FFmpeg)", got)
}
// A ceiling that does not bind tighter than the encoder tells us nothing the
// encoder would not already enforce, so it also defers.
if got := EffectiveAC3Channels(0, 8); got != 0 {
t.Errorf("EffectiveAC3Channels(0, 8) = %d, want 0", got)
}
}

// The AC-3 target exists to carry surround to a receiver. Inheriting the AAC
// path's TrueHD-to-stereo safety would defeat the only reason to pick it -- that
// stall is in the TrueHD-to-AAC path, not here.
func TestEffectiveAC3ChannelsIgnoresFragileLosslessDownmix(t *testing.T) {
if got := EffectiveAC3Channels(8, 6); got != 6 {
t.Errorf("EffectiveAC3Channels(8, 6) = %d, want 6 even for a TrueHD source", got)
}
// Contrast with the AAC path, which must downmix the same source.
if got := EffectiveAudioChannels(8, 6, "truehd"); got != 2 {
t.Errorf("EffectiveAudioChannels(8, 6, truehd) = %d, want 2", got)
}
}

func TestAC3BitrateForChannels(t *testing.T) {
cases := map[int]string{
0: "448k", // deferred layout cannot exceed 5.1, so pair the surround rate
6: "448k",
2: "192k",
1: "96k",
}
for channels, want := range cases {
if got := AC3BitrateForChannels(channels); got != want {
t.Errorf("AC3BitrateForChannels(%d) = %q, want %q", channels, got, want)
}
}
}
67 changes: 67 additions & 0 deletions internal/playback/audio_select.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,70 @@ func AudioTrackChannelsAt(tracks []models.AudioTrack, index int) int {
}
return tracks[index].Channels
}

// SelectClientPlayableAudioTrack finds the best track the client can decode
// itself, so an unplayable default can be answered by choosing a different
// track rather than by re-encoding.
//
// This is the difference between "the TV cannot play this audio" and "the TV
// cannot play this file". A Blu-ray remux typically ships a lossless default
// (TrueHD/DTS-HD) alongside a lossy companion in the same language, and the
// companion is usually both decodable and multichannel. Copying it beats
// re-encoding the lossless track on every axis: no CPU, no quality loss, and
// surround survives instead of being downmixed to stereo.
//
// Preference order, strongest first:
//
// 1. The client claims the codec. A track it cannot decode is no use however
// good it is.
// 2. Same language as the originally selected track. Correct language in
// stereo beats the wrong language in 5.1.
// 3. Most channels, bounded by maxChannels. A client that declared a 5.1
// ceiling gains nothing from a 7.1 track and may fail on it outright.
// 4. Lowest index, so the choice is deterministic for equal candidates.
//
// Reports false when no track qualifies, leaving the caller to fall back to
// re-encoding. maxChannels <= 0 means the client declared no ceiling, in which
// case channel count is still preferred but nothing is excluded for it -- a
// decodable track is better than a re-encode either way.
func SelectClientPlayableAudioTrack(
tracks []models.AudioTrack,
selected int,
claimedCodecs []string,
maxChannels int,
) (int, bool) {
if len(tracks) == 0 || len(claimedCodecs) == 0 {
return selected, false
}

preferredLang := ""
if selected >= 0 && selected < len(tracks) {
preferredLang = tracks[selected].Language
}

best := -1
bestLangMatch := false
bestChannels := -1
for i, track := range tracks {
if !audioCodecClaimed(claimedCodecs, track.Codec) {
continue
}
// A track above the client's ceiling is exactly what this exists to
// avoid handing over.
if maxChannels > 0 && track.Channels > maxChannels {
continue
}

langMatch := preferredLang == "" || track.Language == "" ||
langMatch(track.Language, preferredLang)
if best < 0 ||
(langMatch && !bestLangMatch) ||
(langMatch == bestLangMatch && track.Channels > bestChannels) {
best, bestLangMatch, bestChannels = i, langMatch, track.Channels
}
}
if best < 0 {
return selected, false
}
return best, true
}
Loading