From ecbd4b7d5530113c1b9807589a718b8fe60434be Mon Sep 17 00:00:00 2001 From: Junker der Provinz Date: Tue, 10 Nov 2026 16:14:37 +0100 Subject: [PATCH] fix(transcoding): default DSD transcoded to lossless PCM to 88.2kHz MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(stream): cap DSD transcoded to lossless PCM at 88.2kHz DSD64 was sent as 352.8kHz FLAC/WAV, which many clients cannot play. Client and codec profile limits below 88.2kHz still apply. ffprobe already reports DSD at rate/8 with 8 bits per sample, so only rates read from tags are divided, and any DSD depth maps to 24-bit PCM. Probed files used to come out at 44.1kHz with a bit depth of 8. Fixes #6288 Co-authored-by: Olli Sulopuisto <1051255+ollisulopuisto@users.noreply.github.com> Signed-off-by: Junker der Provinz <133605895+junkerderprovinz@users.noreply.github.com> * fix(stream): let a client's sample rate limit replace the DSD cap The 88.2kHz cap on DSD transcoded to lossless PCM is meant for clients that say nothing about sample rates, like the legacy stream endpoint. Applied unconditionally, it also overrode clients that declared their own audioSamplerate limit: a client accepting up to 192kHz got 88.2kHz, and one accepting only 96kHz or 192kHz got no compatible profile at all. The cap now applies only when the client has no audioSamplerate limitation for the target codec. Otherwise the client's limit decides the rate. * refactor(stream): share the audio codec profile matcher Direct play checks, transcode limitations and the new DSD cap check each looped over the client's codec profiles with the same audio-type and codec alias filter. They now use one audioCodecProfiles iterator, so the DSD cap decision cannot drift from the limitations that are actually applied. targetSampleRate takes a single capDSD flag instead of two adjacent bools. * test(stream): table-drive the DSD to FLAC sample rate specs Six specs repeated the same DSD source and FLAC transcoding profile and differed only in the source rate, the client's codec profiles and the expected rate. A DescribeTable lists the cap policy case by case, and every entry now also checks the 24-bit depth. --------- Signed-off-by: Junker der Provinz <133605895+junkerderprovinz@users.noreply.github.com> Co-authored-by: Olli Sulopuisto <1051255+ollisulopuisto@users.noreply.github.com> Co-authored-by: Deluan Quintão --- core/stream/codec.go | 23 ++++- core/stream/decider.go | 31 +++--- core/stream/decider_test.go | 94 +++++++++++-------- core/stream/limitations.go | 23 +++++ .../subsonic/e2e/subsonic_transcode_test.go | 4 +- 5 files changed, 113 insertions(+), 62 deletions(-) diff --git a/core/stream/codec.go b/core/stream/codec.go index 56d163324..64b10343f 100644 --- a/core/stream/codec.go +++ b/core/stream/codec.go @@ -32,9 +32,10 @@ func isLosslessFormat(format string) bool { return false } -// normalizeSourceSampleRate adjusts the source sample rate for codecs that store -// it differently than PCM. Currently handles DSD (÷8): +// normalizeSourceSampleRate adjusts a sample rate read from tags for codecs that +// store it differently than PCM. Currently handles DSD (÷8): // DSD64=2822400→352800, DSD128=5644800→705600, etc. +// ffprobe already reports DSD at this rate, so probe data needs no adjustment. // For other codecs, returns the rate unchanged. func normalizeSourceSampleRate(sampleRate int, codec string) int { if strings.EqualFold(codec, "dsd") && sampleRate > 0 { @@ -43,14 +44,28 @@ func normalizeSourceSampleRate(sampleRate int, codec string) int { return sampleRate } +// dsdMaxPCMSampleRate caps DSD transcoded to lossless PCM. It divides every +// 44.1kHz-based DSD rate exactly, DSD carries mostly its own shaped noise above +// it, and many clients cannot play 352.8kHz PCM. +const dsdMaxPCMSampleRate = 88200 + +// targetSampleRate returns the sample rate for a transcoded stream before codec +// and client limits are applied, with DSD capped when capDSD is set. +func targetSampleRate(srcSampleRate int, srcCodec string, capDSD bool) int { + if capDSD && strings.EqualFold(srcCodec, "dsd") { + return min(srcSampleRate, dsdMaxPCMSampleRate) + } + return srcSampleRate +} + // targetBitDepth returns the bit depth for a transcoded stream: 0 for lossy // targets (they have no PCM bit depth), otherwise the source depth, with DSD -// adjusted to the 24-bit PCM that ffmpeg produces. +// (1 bit in tags, 8 in ffprobe) adjusted to the 24-bit PCM that ffmpeg produces. func targetBitDepth(srcBitDepth int, srcCodec string, targetIsLossless bool) int { if !targetIsLossless { return 0 } - if strings.EqualFold(srcCodec, "dsd") && srcBitDepth == 1 { + if strings.EqualFold(srcCodec, "dsd") { return 24 } return srcBitDepth diff --git a/core/stream/decider.go b/core/stream/decider.go index 38839cdf0..82d31db9b 100644 --- a/core/stream/decider.go +++ b/core/stream/decider.go @@ -143,7 +143,7 @@ func buildSourceStream(mf *model.MediaFile, probe *ffmpeg.AudioProbeResult) Deta } else { sd.Codec = mf.AudioCodec() sd.Bitrate = mf.BitRate - sd.SampleRate = mf.SampleRate + sd.SampleRate = normalizeSourceSampleRate(mf.SampleRate, sd.Codec) sd.BitDepth = gg.V(mf.BitDepth) sd.Channels = mf.Channels } @@ -224,11 +224,9 @@ func (s *deciderService) checkDirectPlayProfile(src *Details, profile *DirectPla } // Check codec-specific limitations - for _, codecProfile := range clientInfo.CodecProfiles { - if strings.EqualFold(codecProfile.Type, CodecProfileTypeAudio) && matchesCodec(src.Codec, []string{codecProfile.Name}) { - if reason := checkLimitations(src, codecProfile.Limitations); reason != "" { - return reason - } + for codecProfile := range audioCodecProfiles(clientInfo, src.Codec) { + if reason := checkLimitations(src, codecProfile.Limitations); reason != "" { + return reason } } @@ -265,17 +263,20 @@ func (s *deciderService) computeTranscodedStream(ctx context.Context, src *Detai return nil, "" } + targetCodec := strings.ToLower(profile.AudioCodec) + if targetCodec == "" { + targetCodec = targetFormat + } + capDSD := targetIsLossless && !hasCodecLimitation(clientInfo, targetCodec, LimitationAudioSamplerate) + ts := &Details{ Container: responseContainer, - Codec: strings.ToLower(profile.AudioCodec), - SampleRate: normalizeSourceSampleRate(src.SampleRate, src.Codec), + Codec: targetCodec, + SampleRate: targetSampleRate(src.SampleRate, src.Codec, capDSD), Channels: src.Channels, BitDepth: targetBitDepth(src.BitDepth, src.Codec, targetIsLossless), IsLossless: targetIsLossless, } - if ts.Codec == "" { - ts.Codec = targetFormat - } // Apply codec-intrinsic sample rate adjustments before codec profile limitations if fixedRate := codecFixedOutputSampleRate(ts.Codec); fixedRate > 0 { @@ -400,13 +401,7 @@ func (s *deciderService) computeBitrate(ctx context.Context, src *Details, targe // Returns false if the profile should be rejected. func (s *deciderService) applyCodecLimitations(ctx context.Context, sourceBitrate int, targetFormat string, targetIsLossless bool, clientInfo *ClientInfo, ts *Details) bool { targetCodec := ts.Codec - for _, codecProfile := range clientInfo.CodecProfiles { - if !strings.EqualFold(codecProfile.Type, CodecProfileTypeAudio) { - continue - } - if !matchesCodec(targetCodec, []string{codecProfile.Name}) { - continue - } + for codecProfile := range audioCodecProfiles(clientInfo, targetCodec) { for _, lim := range codecProfile.Limitations { result := applyLimitation(sourceBitrate, &lim, ts) if strings.EqualFold(lim.Name, LimitationAudioBitrate) && targetIsLossless && result == adjustAdjusted { diff --git a/core/stream/decider_test.go b/core/stream/decider_test.go index 01fef1249..8dc72c336 100644 --- a/core/stream/decider_test.go +++ b/core/stream/decider_test.go @@ -719,7 +719,7 @@ var _ = Describe("Decider", func() { Context("DSD sample rate conversion", func() { It("converts DSD sample rate to PCM-equivalent in decision", func() { - mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)}) + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 352800, BitDepth: new(8)}) ci := &ClientInfo{ MaxTranscodingAudioBitrate: 320, TranscodingProfiles: []Profile{ @@ -730,7 +730,7 @@ var _ = Describe("Decider", func() { Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) Expect(decision.TargetFormat).To(Equal("mp3")) - // DSD64 2822400 / 8 = 352800, capped by MP3 max of 48000 + // DSD64 probes as 352800, capped by MP3 max of 48000 Expect(decision.TranscodeStream.SampleRate).To(Equal(48000)) Expect(decision.TargetSampleRate).To(Equal(48000)) // MP3 is lossy: no bit depth on the transcoded stream @@ -738,54 +738,72 @@ var _ = Describe("Decider", func() { Expect(decision.TargetBitDepth).To(BeZero()) }) - It("converts DSD sample rate for FLAC target without codec limit", func() { - mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)}) - ci := &ClientInfo{ - TranscodingProfiles: []Profile{ - {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP}, + sampleRateLimit := func(codec, comparison string, values ...string) CodecProfile { + return CodecProfile{ + Type: CodecProfileTypeAudio, + Name: codec, + Limitations: []Limitation{ + {Name: LimitationAudioSamplerate, Comparison: comparison, Values: values, Required: true}, }, } - decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) - Expect(err).ToNot(HaveOccurred()) - Expect(decision.CanTranscode).To(BeTrue()) - Expect(decision.TargetFormat).To(Equal("flac")) - // DSD64 2822400 / 8 = 352800, FLAC has no hard max - Expect(decision.TranscodeStream.SampleRate).To(Equal(352800)) - Expect(decision.TargetSampleRate).To(Equal(352800)) - // DSD 1-bit → 24-bit PCM - Expect(decision.TranscodeStream.BitDepth).To(Equal(24)) - Expect(decision.TargetBitDepth).To(Equal(24)) - }) + } - It("applies codec profile limit to DSD-converted FLAC sample rate", func() { - mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)}) + DescribeTable("DSD to FLAC sample rate", + func(srcSampleRate int, codecProfiles []CodecProfile, expectedRate int) { + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: srcSampleRate, BitDepth: new(8)}) + ci := &ClientInfo{ + TranscodingProfiles: []Profile{ + {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP}, + }, + CodecProfiles: codecProfiles, + } + decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) + Expect(err).ToNot(HaveOccurred()) + Expect(decision.CanTranscode).To(BeTrue()) + Expect(decision.TargetFormat).To(Equal("flac")) + Expect(decision.TranscodeStream.SampleRate).To(Equal(expectedRate)) + Expect(decision.TargetSampleRate).To(Equal(expectedRate)) + Expect(decision.TranscodeStream.BitDepth).To(Equal(24)) + Expect(decision.TargetBitDepth).To(Equal(24)) + }, + Entry("caps DSD64 at 88.2kHz when the client declares no limit", 352800, nil, 88200), + Entry("caps DSD128 at 88.2kHz when the client declares no limit", 705600, nil, 88200), + Entry("uses a declared upper limit instead of the cap", 352800, + []CodecProfile{sampleRateLimit("flac", ComparisonLessThanEqual, "192000")}, 192000), + Entry("picks the closest rate from a declared list", 352800, + []CodecProfile{sampleRateLimit("flac", ComparisonEquals, "96000", "192000")}, 192000), + Entry("applies a declared limit below the cap", 352800, + []CodecProfile{sampleRateLimit("flac", ComparisonLessThanEqual, "48000")}, 48000), + Entry("keeps the cap when the declared rate limit is for another codec", 352800, + []CodecProfile{ + sampleRateLimit("mp3", ComparisonLessThanEqual, "192000"), + {Type: CodecProfileTypeAudio, Name: "flac", Limitations: []Limitation{ + {Name: LimitationAudioChannels, Comparison: ComparisonLessThanEqual, Values: []string{"2"}, Required: true}, + }}, + }, 88200), + ) + + It("normalizes DSD sample rate from tags when there is no probe data", func() { + DeferCleanup(configtest.SetupConfig()) + conf.Server.DevEnableMediaFileProbe = false + + mf := &model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)} ci := &ClientInfo{ TranscodingProfiles: []Profile{ {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP}, }, - CodecProfiles: []CodecProfile{ - { - Type: CodecProfileTypeAudio, - Name: "flac", - Limitations: []Limitation{ - {Name: LimitationAudioSamplerate, Comparison: ComparisonLessThanEqual, Values: []string{"48000"}, Required: true}, - }, - }, - }, } decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) - // DSD64 2822400 / 8 = 352800, capped by codec profile limit of 48000 - Expect(decision.TranscodeStream.SampleRate).To(Equal(48000)) - Expect(decision.TargetSampleRate).To(Equal(48000)) - // DSD 1-bit → 24-bit PCM - Expect(decision.TranscodeStream.BitDepth).To(Equal(24)) + // Tags store the 1-bit DSD64 rate, ffprobe reports 352800 + Expect(decision.SourceStream.SampleRate).To(Equal(352800)) + Expect(decision.TargetSampleRate).To(Equal(88200)) Expect(decision.TargetBitDepth).To(Equal(24)) }) It("applies audioBitdepth limitation to DSD-converted bit depth", func() { - mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)}) + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 352800, BitDepth: new(8)}) ci := &ClientInfo{ TranscodingProfiles: []Profile{ {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP}, @@ -803,7 +821,7 @@ var _ = Describe("Decider", func() { decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) - // DSD 1-bit → 24-bit PCM, then capped by codec profile limit to 16-bit + // DSD → 24-bit PCM, then capped by codec profile limit to 16-bit Expect(decision.TranscodeStream.BitDepth).To(Equal(16)) Expect(decision.TargetBitDepth).To(Equal(16)) }) @@ -1021,7 +1039,7 @@ var _ = Describe("Decider", func() { Context("AAC max sample rate", func() { It("caps sample rate at 96000 for AAC", func() { - mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)}) + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 352800, BitDepth: new(8)}) ci := &ClientInfo{ MaxTranscodingAudioBitrate: 320, TranscodingProfiles: []Profile{ @@ -1031,7 +1049,7 @@ var _ = Describe("Decider", func() { decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) - // DSD64 2822400 / 8 = 352800, capped by AAC max of 96000 + // DSD64 probes as 352800, capped by AAC max of 96000 Expect(decision.TranscodeStream.SampleRate).To(Equal(96000)) }) }) diff --git a/core/stream/limitations.go b/core/stream/limitations.go index ab70d6c07..77c56bb87 100644 --- a/core/stream/limitations.go +++ b/core/stream/limitations.go @@ -1,6 +1,8 @@ package stream import ( + "iter" + "slices" "strconv" "strings" ) @@ -48,6 +50,27 @@ func checkLimitations(src *Details, limitations []Limitation) string { return "" } +func audioCodecProfiles(clientInfo *ClientInfo, codec string) iter.Seq[CodecProfile] { + return func(yield func(CodecProfile) bool) { + for _, cp := range clientInfo.CodecProfiles { + if strings.EqualFold(cp.Type, CodecProfileTypeAudio) && matchesCodec(codec, []string{cp.Name}) { + if !yield(cp) { + return + } + } + } + } +} + +func hasCodecLimitation(clientInfo *ClientInfo, codec, name string) bool { + for cp := range audioCodecProfiles(clientInfo, codec) { + if slices.ContainsFunc(cp.Limitations, func(lim Limitation) bool { return strings.EqualFold(lim.Name, name) }) { + return true + } + } + return false +} + // applyLimitation adjusts a transcoded stream parameter to satisfy the limitation. // Returns the adjustment result. func applyLimitation(sourceBitrate int, lim *Limitation, ts *Details) adjustResult { diff --git a/server/subsonic/e2e/subsonic_transcode_test.go b/server/subsonic/e2e/subsonic_transcode_test.go index 313066938..3f994f4ae 100644 --- a/server/subsonic/e2e/subsonic_transcode_test.go +++ b/server/subsonic/e2e/subsonic_transcode_test.go @@ -340,8 +340,8 @@ var _ = Describe("Transcode Endpoints", Ordered, func() { Expect(resp.TranscodeDecision.CanTranscode).To(BeTrue()) Expect(resp.TranscodeDecision.TranscodeStream).ToNot(BeNil()) Expect(resp.TranscodeDecision.TranscodeStream.Codec).To(Equal("flac")) - // DSD sample rate normalized: 2822400 / 8 = 352800 - Expect(resp.TranscodeDecision.TranscodeStream.AudioSamplerate).To(Equal(int32(352800))) + // DSD sample rate normalized: 2822400 / 8 = 352800, capped at 88200 + Expect(resp.TranscodeDecision.TranscodeStream.AudioSamplerate).To(Equal(int32(88200))) // DSD 1-bit → 24-bit PCM Expect(resp.TranscodeDecision.TranscodeStream.AudioBitdepth).To(Equal(int32(24))) })