diff --git a/core/ffmpeg/ffmpeg.go b/core/ffmpeg/ffmpeg.go index aab41464d..c0277f871 100644 --- a/core/ffmpeg/ffmpeg.go +++ b/core/ffmpeg/ffmpeg.go @@ -490,7 +490,7 @@ func buildDynamicArgs(opts TranscodeOptions) []string { // buildTemplateArgs handles user-customized command templates, with dynamic injection // of sample rate, channels, and bit depth when requested by the transcode decision. // Values in opts have already been clamped to codec limits upstream (see -// core/stream/codec.go codecMax* helpers), so injecting them unconditionally is safe — +// core/stream/codec.go), so injecting them unconditionally is safe — // ffmpeg honors the last occurrence of a duplicate flag. func buildTemplateArgs(opts TranscodeOptions) []string { args := createFFmpegCommand(opts.Command, opts.FilePath, opts.BitRate, opts.Offset) diff --git a/core/stream/codec.go b/core/stream/codec.go index 86d1ef8d2..07d74e4a5 100644 --- a/core/stream/codec.go +++ b/core/stream/codec.go @@ -1,6 +1,9 @@ package stream -import "strings" +import ( + "slices" + "strings" +) // normalizeProbeCodec maps ffprobe codec_name values to the simplified internal // codec names used throughout Navidrome (matching inferCodecFromSuffix output). @@ -84,16 +87,52 @@ func codecFixedOutputSampleRate(codec string) int { return 0 } -// codecMaxSampleRate returns the hard maximum output sample rate for a codec. -// Returns 0 if the codec has no hard limit. -func codecMaxSampleRate(codec string) int { - switch strings.ToLower(codec) { - case "mp3": - return 48000 - case "aac": - return 96000 +// codecSampleRates lists, in ascending order, the only sample rates some +// encoders accept. ffmpeg's libmp3lame and aac encoders exit with an error for +// any other rate (e.g. 32728Hz from Nintendo 3DS rips). +var codecSampleRates = map[string][]int{ + "mp3": {8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000}, + "aac": {7350, 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000}, +} + +// codecSampleRate returns a sample rate the codec's encoder accepts: the +// lowest supported rate at or above sampleRate, or the codec's highest rate if +// sampleRate is above it. Codecs with no fixed set, and a zero (unknown) rate, +// are returned unchanged. +func codecSampleRate(codec string, sampleRate int) int { + rates := codecSampleRates[strings.ToLower(codec)] + if len(rates) == 0 || sampleRate <= 0 { + return sampleRate } - return 0 + for _, r := range rates { + if r >= sampleRate { + return r + } + } + return rates[len(rates)-1] +} + +// codecAcceptsSampleRate reports whether the codec's encoder accepts sampleRate. +// Codecs with no fixed set accept any rate. +func codecAcceptsSampleRate(codec string, sampleRate int) bool { + rates := codecSampleRates[strings.ToLower(codec)] + return len(rates) == 0 || slices.Contains(rates, sampleRate) +} + +// codecSampleRateAtOrBelow returns the highest rate the codec's encoder accepts +// that is not above sampleRate, and false if there is none. Codecs with no +// fixed set return sampleRate unchanged. +func codecSampleRateAtOrBelow(codec string, sampleRate int) (int, bool) { + rates := codecSampleRates[strings.ToLower(codec)] + if len(rates) == 0 { + return sampleRate, true + } + for _, r := range slices.Backward(rates) { + if r <= sampleRate { + return r, true + } + } + return 0, false } // codecMaxChannels returns the hard maximum number of audio channels a codec diff --git a/core/stream/codec_test.go b/core/stream/codec_test.go index 97e15bdb5..adc2f22fd 100644 --- a/core/stream/codec_test.go +++ b/core/stream/codec_test.go @@ -67,6 +67,22 @@ var _ = Describe("Codec", func() { }) }) + DescribeTable("codecSampleRate", + func(codec string, in, expected int) { + Expect(codecSampleRate(codec, in)).To(Equal(expected)) + }, + Entry("mp3 keeps a supported rate", "mp3", 44100, 44100), + Entry("mp3 moves 32728 up to 44100", "mp3", 32728, 44100), + Entry("mp3 moves 7000 up to 8000", "mp3", 7000, 8000), + Entry("mp3 caps 96000 at 48000", "mp3", 96000, 48000), + Entry("mp3 is case-insensitive", "MP3", 32728, 44100), + Entry("aac moves 32728 up to 44100", "aac", 32728, 44100), + Entry("aac moves 50000 up to 64000", "aac", 50000, 64000), + Entry("aac caps 352800 at 96000", "aac", 352800, 96000), + Entry("unknown rate stays 0", "mp3", 0, 0), + Entry("codec with no fixed set keeps the rate", "flac", 32728, 32728), + ) + Describe("codecMaxChannels", func() { It("returns 2 for mp3", func() { Expect(codecMaxChannels("mp3")).To(Equal(2)) diff --git a/core/stream/decider.go b/core/stream/decider.go index 6a231f638..a514dfef0 100644 --- a/core/stream/decider.go +++ b/core/stream/decider.go @@ -285,9 +285,7 @@ func (s *deciderService) computeTranscodedStream(ctx context.Context, src *Detai if fixedRate := codecFixedOutputSampleRate(ts.Codec); fixedRate > 0 { ts.SampleRate = fixedRate } - if maxRate := codecMaxSampleRate(ts.Codec); maxRate > 0 && ts.SampleRate > maxRate { - ts.SampleRate = maxRate - } + ts.SampleRate = codecSampleRate(ts.Codec, ts.SampleRate) if maxCh := codecMaxChannels(ts.Codec); maxCh > 0 && ts.Channels > maxCh { ts.Channels = maxCh } @@ -420,6 +418,19 @@ func (s *deciderService) applyCodecLimitations(ctx context.Context, sourceBitrat } } } + // A later limitation can lower a value below a bound an earlier one + // accepted, so check the final values against every limitation once more. + for codecProfile := range audioCodecProfiles(clientInfo, targetCodec) { + for _, lim := range codecProfile.Limitations { + check := *ts + if applyLimitation(sourceBitrate, &lim, &check) != adjustNone { + log.Trace(ctx, "Skipping transcoding profile: codec limitations conflict", + "targetFormat", targetFormat, "codec", targetCodec, "limitation", lim.Name, + "comparison", lim.Comparison, "values", lim.Values) + return false + } + } + } return true } diff --git a/core/stream/decider_test.go b/core/stream/decider_test.go index 204f5add0..e1747f6fc 100644 --- a/core/stream/decider_test.go +++ b/core/stream/decider_test.go @@ -1014,7 +1014,7 @@ var _ = Describe("Decider", func() { }) }) - Context("MP3 max sample rate", func() { + Context("Encoder-accepted sample rates", func() { It("caps sample rate at 48000 for MP3", func() { mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1500, Channels: 2, SampleRate: 96000, BitDepth: new(24)}) ci := &ClientInfo{ @@ -1042,9 +1042,77 @@ var _ = Describe("Decider", func() { Expect(decision.CanTranscode).To(BeTrue()) Expect(decision.TranscodeStream.SampleRate).To(Equal(44100)) }) - }) - Context("AAC max sample rate", func() { + It("moves a rate LAME does not accept up to a supported one", func() { + // Nintendo 3DS rips are 32728Hz, which libmp3lame rejects + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 800, Channels: 2, SampleRate: 32728, BitDepth: new(16)}) + ci := &ClientInfo{ + MaxTranscodingAudioBitrate: 192, + TranscodingProfiles: []Profile{ + {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP}, + }, + } + decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) + Expect(err).ToNot(HaveOccurred()) + Expect(decision.CanTranscode).To(BeTrue()) + Expect(decision.TranscodeStream.SampleRate).To(Equal(44100)) + Expect(decision.TargetSampleRate).To(Equal(44100)) + }) + + DescribeTable("keeps client sample rate limits within the rates LAME accepts", + func(comparison string, values []string, expectedRate int) { + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 800, Channels: 2, SampleRate: 32728, BitDepth: new(16)}) + ci := &ClientInfo{ + MaxTranscodingAudioBitrate: 192, + TranscodingProfiles: []Profile{ + {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP}, + }, + CodecProfiles: []CodecProfile{{ + Type: CodecProfileTypeAudio, + Name: "mp3", + Limitations: []Limitation{ + {Name: LimitationAudioSamplerate, Comparison: comparison, Values: values}, + }, + }}, + } + decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) + Expect(err).ToNot(HaveOccurred()) + if expectedRate == 0 { + Expect(decision.CanTranscode).To(BeFalse()) + return + } + Expect(decision.CanTranscode).To(BeTrue()) + Expect(decision.TargetSampleRate).To(Equal(expectedRate)) + }, + Entry("Equals skips a value LAME rejects", ComparisonEquals, []string{"32000", "40000"}, 32000), + Entry("LessThanEqual moves a bound LAME rejects down", ComparisonLessThanEqual, []string{"40000"}, 32000), + Entry("Equals with only rejected values drops the profile", ComparisonEquals, []string{"40000"}, 0), + Entry("LessThanEqual below every LAME rate drops the profile", ComparisonLessThanEqual, []string{"7000"}, 0), + Entry("a supported bound is kept", ComparisonLessThanEqual, []string{"32000"}, 32000), + ) + + It("drops the profile when a later limit lowers the rate below an earlier one", func() { + // <= 40000 lowers 44100 to 40000, then to 32000 for LAME, which breaks >= 33000 + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: new(16)}) + ci := &ClientInfo{ + MaxTranscodingAudioBitrate: 192, + TranscodingProfiles: []Profile{ + {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP}, + }, + CodecProfiles: []CodecProfile{{ + Type: CodecProfileTypeAudio, + Name: "mp3", + Limitations: []Limitation{ + {Name: LimitationAudioSamplerate, Comparison: ComparisonGreaterThanEqual, Values: []string{"33000"}}, + {Name: LimitationAudioSamplerate, Comparison: ComparisonLessThanEqual, Values: []string{"40000"}}, + }, + }}, + } + decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) + Expect(err).ToNot(HaveOccurred()) + Expect(decision.CanTranscode).To(BeFalse()) + }) + It("caps sample rate at 96000 for AAC", func() { mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 352800, BitDepth: new(8)}) ci := &ClientInfo{ diff --git a/core/stream/limitations.go b/core/stream/limitations.go index 32763e9f9..e4bfa49a3 100644 --- a/core/stream/limitations.go +++ b/core/stream/limitations.go @@ -104,7 +104,7 @@ func applyLimitation(sourceBitrate int, lim *Limitation, ts *Details) adjustResu } return applyIntLimitation(lim.Comparison, lim.Values, current, func(v int) { ts.Bitrate = v }) case LimitationAudioSamplerate: - return applyIntLimitation(lim.Comparison, lim.Values, ts.SampleRate, func(v int) { ts.SampleRate = v }) + return applySampleRateLimitation(lim, ts) case LimitationAudioBitdepth: if ts.BitDepth > 0 { return applyIntLimitation(lim.Comparison, lim.Values, ts.BitDepth, func(v int) { ts.BitDepth = v }) @@ -115,6 +115,33 @@ func applyLimitation(sourceBitrate int, lim *Limitation, ts *Details) adjustResu return adjustNone } +// applySampleRateLimitation applies a sample rate limitation and keeps the +// result to a rate the target encoder accepts. Equals values the encoder +// rejects are ignored, and a lowered rate moves down to the next accepted one. +// If no accepted rate satisfies the limitation, the profile cannot fit. +func applySampleRateLimitation(lim *Limitation, ts *Details) adjustResult { + values := lim.Values + if lim.Comparison == ComparisonEquals && len(values) > 0 { + values = slices.DeleteFunc(slices.Clone(values), func(v string) bool { + rate, ok := parseInt(v) + return ok && !codecAcceptsSampleRate(ts.Codec, rate) + }) + if len(values) == 0 { + return adjustCannotFit + } + } + result := applyIntLimitation(lim.Comparison, values, ts.SampleRate, func(v int) { ts.SampleRate = v }) + if result != adjustAdjusted { + return result + } + rate, ok := codecSampleRateAtOrBelow(ts.Codec, ts.SampleRate) + if !ok { + return adjustCannotFit + } + ts.SampleRate = rate + return adjustAdjusted +} + // applyIntLimitation applies a limitation comparison to a value. // If the value needs adjusting, calls the setter and returns the result. func applyIntLimitation(comparison string, values []string, current int, setter func(int)) adjustResult {