Skip to main content

usbdac_core/convert/
plan.rs

1//! Planning: the smallest chain of steps that turns one PCM format into another, how much damage
2//! that chain does, and a sentence that says so.
3
4use super::format::{
5    ConversionKind, ConvertError, ConvertOptions, Narrowing, PcmFormat, Quality, SampleFormat,
6};
7use crate::format::{Encoding, StreamFormat, StreamRequest};
8
9/// The lowest and highest sample rate a plan accepts.
10pub const MIN_RATE: u32 = 8_000;
11pub const MAX_RATE: u32 = 768_000;
12
13/// One thing a conversion does.
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub enum Step {
16    /// The sample rate changes: a polyphase windowed-sinc resampler. Lossy.
17    Resample {
18        from_hz: u32,
19        to_hz: u32,
20        quality: Quality,
21    },
22    /// An integer sample gains bits: the old bits keep their place and the new low ones are zero.
23    /// A move to a bigger slot size comes with it. Bit-exact.
24    Widen {
25        from: SampleFormat,
26        to: SampleFormat,
27    },
28    /// An integer sample keeps its bits and changes slot size, as 24-bit packed in 3 bytes into 24-bit in 4. Bit-exact.
29    Repack {
30        from: SampleFormat,
31        to: SampleFormat,
32    },
33    /// An integer sample loses bits. Lossy.
34    Narrow {
35        from: SampleFormat,
36        to: SampleFormat,
37        mode: Narrowing,
38    },
39    /// An integer sample becomes a float. Lossless up to 24 significant bits (a float holds them
40    /// exactly), lossy beyond.
41    IntToFloat { from: SampleFormat },
42    /// A float sample is rounded to integers (after resampling, the rounding of the resampled values). Lossy.
43    Quantise { to: SampleFormat, mode: Narrowing },
44    /// One channel becomes two identical ones. Lossless, not identical.
45    MonoToStereo,
46}
47
48impl Step {
49    pub fn kind(&self) -> ConversionKind {
50        match self {
51            Self::Resample { .. } | Self::Narrow { .. } | Self::Quantise { .. } => {
52                ConversionKind::Lossy
53            }
54            Self::Widen { .. } | Self::Repack { .. } => ConversionKind::BitExact,
55            Self::MonoToStereo => ConversionKind::Lossless,
56            Self::IntToFloat { from } => {
57                if from.valid_bits() <= 24 {
58                    ConversionKind::Lossless
59                } else {
60                    ConversionKind::Lossy
61                }
62            }
63        }
64    }
65
66    /// A stable identifier.
67    pub fn code(&self) -> &'static str {
68        match self {
69            Self::Resample { .. } => "resample",
70            Self::Widen { .. } => "widen",
71            Self::Repack { .. } => "repack",
72            Self::Narrow { .. } => "narrow",
73            Self::IntToFloat { .. } => "int_to_float",
74            Self::Quantise { .. } => "quantise",
75            Self::MonoToStereo => "mono_to_stereo",
76        }
77    }
78
79    /// A phrase for the plan's description.
80    pub fn describe(&self) -> String {
81        fn mode(mode: Narrowing) -> &'static str {
82            match mode {
83                Narrowing::Truncate => "by truncation",
84                Narrowing::TpdfDither => "with TPDF dither",
85            }
86        }
87        match self {
88            Self::Resample {
89                from_hz,
90                to_hz,
91                quality,
92            } => {
93                let name = match quality {
94                    Quality::High => "high quality, stopband about 110 dB",
95                    Quality::Fast => "fast quality, stopband about 84 dB",
96                };
97                format!(
98                    "resampled from {from_hz} Hz to {to_hz} Hz (windowed-sinc polyphase, {name})"
99                )
100            }
101            Self::Widen { from, to } => format!(
102                "{} widened to {} (the new low bits are zero, every value is unchanged)",
103                from.describe(),
104                to.describe()
105            ),
106            Self::Repack { from, to } => format!(
107                "{} repacked as {} (every value is unchanged)",
108                from.describe(),
109                to.describe()
110            ),
111            Self::Narrow {
112                from,
113                to,
114                mode: narrowing,
115            } => format!(
116                "{} narrowed to {} {}",
117                from.describe(),
118                to.describe(),
119                mode(*narrowing)
120            ),
121            Self::IntToFloat { from } => {
122                if from.valid_bits() <= 24 {
123                    format!("{} converted to 32-bit float (exact)", from.describe())
124                } else {
125                    format!(
126                        "{} converted to 32-bit float (rounded to 24 significant bits)",
127                        from.describe()
128                    )
129                }
130            }
131            Self::Quantise {
132                to,
133                mode: narrowing,
134            } => {
135                format!(
136                    "quantised to {} {} (full scale saturates)",
137                    to.describe(),
138                    mode(*narrowing)
139                )
140            }
141            Self::MonoToStereo => "mono duplicated to stereo".to_string(),
142        }
143    }
144}
145
146/// How to turn `source` into `target`: the steps, what they cost, and a sentence for a status line.
147#[derive(Debug, Clone, PartialEq)]
148pub struct ConversionPlan {
149    source: PcmFormat,
150    target: PcmFormat,
151    options: ConvertOptions,
152    steps: Vec<Step>,
153    kind: ConversionKind,
154    description: String,
155}
156
157impl ConversionPlan {
158    /// The plan for what the host wants to play (`source`, a PCM request) and what the DAC runs
159    /// (`target`, the negotiated format). The source samples are in the layout the request's bit
160    /// depth implies (16-bit, packed 24-bit, 32-bit) unless [`ConvertOptions::source_sample`] says
161    /// otherwise. DoP and native DSD are refused: converting them would destroy them.
162    pub fn between(
163        source: &StreamRequest,
164        target: &StreamFormat,
165        options: &ConvertOptions,
166    ) -> Result<Self, ConvertError> {
167        if !matches!(source.encoding, Encoding::Pcm | Encoding::PcmFloat32)
168            || target.encoding != Encoding::Pcm
169        {
170            return Err(ConvertError::Unsupported(
171                "DoP and native DSD are never converted: a sample-rate or bit-depth change would destroy them".into(),
172            ));
173        }
174        if source.encoding == Encoding::PcmFloat32
175            && options
176                .source_sample
177                .is_some_and(|sample| sample != SampleFormat::Float32)
178        {
179            return Err(ConvertError::InvalidArgument(
180                "float PCM source requires Float32 layout".into(),
181            ));
182        }
183        let source_sample = match (source.encoding, options.source_sample) {
184            (Encoding::PcmFloat32, _) => SampleFormat::Float32,
185            (_, Some(sample)) => sample,
186            (_, None) => match source.bit_depth {
187                16 => SampleFormat::I16,
188                24 => SampleFormat::I24,
189                32 => SampleFormat::I32,
190                other => {
191                    return Err(ConvertError::InvalidArgument(format!(
192                        "a source of {other} bits is not 16, 24 or 32"
193                    )))
194                }
195            },
196        };
197        Self::pcm(
198            PcmFormat::new(source.sample_rate, source.channels, source_sample),
199            PcmFormat::new(
200                target.sample_rate,
201                target.channels,
202                SampleFormat::int(target.valid_bits, target.subslot_bytes)?,
203            ),
204            options,
205        )
206    }
207
208    /// The plan between two PCM formats.
209    pub fn pcm(
210        source: PcmFormat,
211        target: PcmFormat,
212        options: &ConvertOptions,
213    ) -> Result<Self, ConvertError> {
214        for (name, format) in [("source", &source), ("target", &target)] {
215            if let SampleFormat::Int { bits, slot_bytes } = format.sample {
216                SampleFormat::int(bits, slot_bytes)?;
217            }
218            if !(MIN_RATE..=MAX_RATE).contains(&format.sample_rate) {
219                return Err(ConvertError::InvalidArgument(format!(
220                    "the {name} rate {} Hz is outside {MIN_RATE} to {MAX_RATE} Hz",
221                    format.sample_rate
222                )));
223            }
224            if format.channels == 0 || format.channels > 8 {
225                return Err(ConvertError::InvalidArgument(format!(
226                    "the {name} has {} channels (1 to 8)",
227                    format.channels
228                )));
229            }
230        }
231        if !(options.headroom_db.is_finite() && (-60.0..=0.0).contains(&options.headroom_db)) {
232            return Err(ConvertError::InvalidArgument(
233                "headroom_db must be between -60 and 0".into(),
234            ));
235        }
236        let dup = match (source.channels, target.channels) {
237            (a, b) if a == b => false,
238            (1, 2) => true,
239            (a, b) => {
240                return Err(ConvertError::Unsupported(format!(
241                    "{a} channels cannot be converted to {b}: only mono to stereo is supported"
242                )))
243            }
244        };
245
246        let mut steps = Vec::new();
247        let resample = source.sample_rate != target.sample_rate;
248        if resample {
249            steps.push(Step::Resample {
250                from_hz: source.sample_rate,
251                to_hz: target.sample_rate,
252                quality: options.quality,
253            });
254        }
255        match (source.sample, target.sample) {
256            (a, b) if a == b && !resample => {}
257            // After resampling the values are not integers any more; an integer target rounds them.
258            (_, SampleFormat::Float32) if resample => {}
259            (_, to @ SampleFormat::Int { .. }) if resample => steps.push(Step::Quantise {
260                to,
261                mode: options.narrowing,
262            }),
263            (SampleFormat::Float32, SampleFormat::Float32) => {}
264            (from @ SampleFormat::Int { .. }, SampleFormat::Float32) => {
265                steps.push(Step::IntToFloat { from })
266            }
267            (SampleFormat::Float32, to @ SampleFormat::Int { .. }) => steps.push(Step::Quantise {
268                to,
269                mode: options.narrowing,
270            }),
271            (
272                from @ SampleFormat::Int {
273                    bits: from_bits, ..
274                },
275                to @ SampleFormat::Int { bits: to_bits, .. },
276            ) => steps.push(if to_bits > from_bits {
277                Step::Widen { from, to }
278            } else if to_bits == from_bits {
279                Step::Repack { from, to }
280            } else {
281                Step::Narrow {
282                    from,
283                    to,
284                    mode: options.narrowing,
285                }
286            }),
287        }
288        if dup {
289            steps.push(Step::MonoToStereo);
290        }
291
292        let kind = steps
293            .iter()
294            .map(Step::kind)
295            .max()
296            .unwrap_or(ConversionKind::None);
297        let mut description = describe(kind, &steps, options.headroom_db);
298        if let SampleFormat::Int { bits, slot_bytes } = source.sample {
299            if u16::from(bits) < u16::from(slot_bytes) * 8 {
300                description.push_str(" Declared zero padding is validated on every input buffer.");
301            }
302        }
303        Ok(Self {
304            source,
305            target,
306            options: *options,
307            steps,
308            kind,
309            description,
310        })
311    }
312
313    pub fn source(&self) -> PcmFormat {
314        self.source
315    }
316
317    pub fn target(&self) -> PcmFormat {
318        self.target
319    }
320
321    pub fn options(&self) -> &ConvertOptions {
322        &self.options
323    }
324
325    pub fn steps(&self) -> &[Step] {
326        &self.steps
327    }
328
329    /// The worst of the steps: [`ConversionKind::None`] if there are none.
330    pub fn kind(&self) -> ConversionKind {
331        self.kind
332    }
333
334    /// A sentence that says what is done and how much it costs, for a status line or a log.
335    pub fn description(&self) -> &str {
336        &self.description
337    }
338
339    /// Whether the sample rate changes.
340    pub fn resamples(&self) -> bool {
341        self.steps
342            .iter()
343            .any(|step| matches!(step, Step::Resample { .. }))
344    }
345
346    /// Whether a bit-perfect target stream is still bit-perfect with respect to the source.
347    pub fn preserves_bit_perfect(&self) -> bool {
348        self.kind.preserves_bit_perfect()
349    }
350}
351
352fn describe(kind: ConversionKind, steps: &[Step], headroom_db: f64) -> String {
353    let lead = match kind {
354        ConversionKind::None => {
355            return "No conversion: the samples pass through unchanged.".to_string()
356        }
357        ConversionKind::BitExact => "Bit-exact conversion",
358        ConversionKind::Lossless => "Lossless conversion, but the audio is not identical",
359        ConversionKind::Lossy => "Lossy conversion, not bit-perfect",
360    };
361    let mut text = format!(
362        "{lead}: {}",
363        steps
364            .iter()
365            .map(Step::describe)
366            .collect::<Vec<_>>()
367            .join("; ")
368    );
369    if headroom_db != 0.0
370        && steps
371            .iter()
372            .any(|step| matches!(step, Step::Resample { .. }))
373    {
374        text.push_str(&format!(
375            "; {:.1} dB of headroom after resampling",
376            headroom_db
377        ));
378    }
379    text.push('.');
380    text
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use crate::capabilities::{LinkSpeed, Pacing, SyncKind};
387
388    fn fmt(rate: u32, channels: u16, sample: SampleFormat) -> PcmFormat {
389        PcmFormat::new(rate, channels, sample)
390    }
391
392    fn plan(source: PcmFormat, target: PcmFormat) -> ConversionPlan {
393        ConversionPlan::pcm(source, target, &ConvertOptions::default()).unwrap()
394    }
395
396    fn stream_format(
397        rate: u32,
398        channels: u16,
399        valid_bits: u8,
400        subslot_bytes: u8,
401        encoding: Encoding,
402    ) -> StreamFormat {
403        StreamFormat {
404            request: StreamRequest::pcm(rate, channels, valid_bits),
405            encoding,
406            sample_rate: rate,
407            channels,
408            valid_bits,
409            subslot_bytes,
410            interface_number: 1,
411            alt_setting: 1,
412            endpoint_address: 1,
413            sync_type: SyncKind::Asynchronous,
414            explicit_feedback: true,
415            link_speed: LinkSpeed::High,
416            service_interval_us: 125,
417            pacing: Pacing::ExplicitFeedback { endpoint: 0x81 },
418            clock: None,
419            native_dsd_signature: None,
420            channel_map: crate::capture::ChannelMap::uac2(channels, 0).unwrap(),
421        }
422    }
423
424    #[test]
425    fn float_stream_request_uses_float_layout_and_rejects_integer_override() {
426        let source = StreamRequest::pcm_float32(44_100, 2);
427        let target = stream_format(44_100, 2, 16, 2, Encoding::Pcm);
428        let plan = ConversionPlan::between(&source, &target, &ConvertOptions::default()).unwrap();
429        assert_eq!(plan.source().sample, SampleFormat::Float32);
430        assert_eq!(plan.kind(), ConversionKind::Lossy);
431        let options = ConvertOptions {
432            source_sample: Some(SampleFormat::I32),
433            ..ConvertOptions::default()
434        };
435        assert!(ConversionPlan::between(&source, &target, &options).is_err());
436    }
437
438    #[test]
439    fn identical_formats_need_no_conversion() {
440        let p = plan(
441            fmt(44_100, 2, SampleFormat::I16),
442            fmt(44_100, 2, SampleFormat::I16),
443        );
444        assert_eq!(p.kind(), ConversionKind::None);
445        assert!(p.steps().is_empty());
446        assert_eq!(
447            p.description(),
448            "No conversion: the samples pass through unchanged."
449        );
450        assert!(p.preserves_bit_perfect());
451    }
452
453    #[test]
454    fn widening_and_repacking_are_bit_exact() {
455        let widen = plan(
456            fmt(44_100, 2, SampleFormat::I16),
457            fmt(44_100, 2, SampleFormat::I24),
458        );
459        assert_eq!(widen.kind(), ConversionKind::BitExact);
460        assert_eq!(widen.steps().len(), 1);
461        assert!(matches!(widen.steps()[0], Step::Widen { .. }));
462        assert!(widen
463            .description()
464            .starts_with("Bit-exact conversion: 16-bit widened to 24-bit packed"));
465        assert!(widen.preserves_bit_perfect());
466
467        let to32 = plan(
468            fmt(48_000, 2, SampleFormat::I16),
469            fmt(48_000, 2, SampleFormat::I32),
470        );
471        assert_eq!(to32.kind(), ConversionKind::BitExact);
472
473        let repack = plan(
474            fmt(96_000, 2, SampleFormat::I24),
475            fmt(96_000, 2, SampleFormat::I24_IN_32),
476        );
477        assert_eq!(repack.kind(), ConversionKind::BitExact);
478        assert!(matches!(repack.steps()[0], Step::Repack { .. }));
479        let back = plan(
480            fmt(96_000, 2, SampleFormat::I24_IN_32),
481            fmt(96_000, 2, SampleFormat::I24),
482        );
483        assert_eq!(back.kind(), ConversionKind::BitExact);
484
485        // 16-bit in a 3-byte slot: the sample shifted left by 8.
486        let slot = plan(
487            fmt(44_100, 2, SampleFormat::I16),
488            SampleFormat::int(16, 3).map(|s| fmt(44_100, 2, s)).unwrap(),
489        );
490        assert_eq!(slot.kind(), ConversionKind::BitExact);
491    }
492
493    #[test]
494    fn narrowing_is_lossy_with_the_chosen_mode() {
495        let p = plan(
496            fmt(44_100, 2, SampleFormat::I24),
497            fmt(44_100, 2, SampleFormat::I16),
498        );
499        assert_eq!(p.kind(), ConversionKind::Lossy);
500        assert!(
501            p.description()
502                .contains("narrowed to 16-bit with TPDF dither"),
503            "{}",
504            p.description()
505        );
506        let truncate = ConversionPlan::pcm(
507            fmt(44_100, 2, SampleFormat::I32),
508            fmt(44_100, 2, SampleFormat::I16),
509            &ConvertOptions {
510                narrowing: Narrowing::Truncate,
511                ..ConvertOptions::default()
512            },
513        )
514        .unwrap();
515        assert!(
516            truncate.description().contains("by truncation"),
517            "{}",
518            truncate.description()
519        );
520        assert!(!truncate.preserves_bit_perfect());
521    }
522
523    #[test]
524    fn mono_to_stereo_is_lossless_but_not_identical() {
525        let p = plan(
526            fmt(44_100, 1, SampleFormat::I16),
527            fmt(44_100, 2, SampleFormat::I16),
528        );
529        assert_eq!(p.kind(), ConversionKind::Lossless);
530        assert_eq!(p.steps(), &[Step::MonoToStereo]);
531        assert!(p
532            .description()
533            .starts_with("Lossless conversion, but the audio is not identical"));
534        assert!(!p.preserves_bit_perfect());
535    }
536
537    #[test]
538    fn other_channel_changes_are_unsupported() {
539        for (from, to) in [(2, 1), (6, 2), (2, 6), (1, 4)] {
540            let error = ConversionPlan::pcm(
541                fmt(44_100, from, SampleFormat::I16),
542                fmt(44_100, to, SampleFormat::I16),
543                &ConvertOptions::default(),
544            )
545            .unwrap_err();
546            assert_eq!(error.code(), "unsupported", "{from} -> {to}");
547            assert!(error.message().contains("only mono to stereo"));
548        }
549    }
550
551    #[test]
552    fn integer_to_float_is_lossless_up_to_24_bits_and_lossy_beyond() {
553        for sample in [
554            SampleFormat::I16,
555            SampleFormat::I24,
556            SampleFormat::I24_IN_32,
557        ] {
558            let p = plan(
559                fmt(48_000, 2, sample),
560                fmt(48_000, 2, SampleFormat::Float32),
561            );
562            assert_eq!(p.kind(), ConversionKind::Lossless, "{sample:?}");
563            assert!(p.description().contains("(exact)"));
564        }
565        let p = plan(
566            fmt(48_000, 2, SampleFormat::I32),
567            fmt(48_000, 2, SampleFormat::Float32),
568        );
569        assert_eq!(p.kind(), ConversionKind::Lossy);
570        assert!(p.description().contains("rounded to 24 significant bits"));
571    }
572
573    #[test]
574    fn float_to_integer_is_lossy() {
575        let p = plan(
576            fmt(48_000, 2, SampleFormat::Float32),
577            fmt(48_000, 2, SampleFormat::I24),
578        );
579        assert_eq!(p.kind(), ConversionKind::Lossy);
580        assert!(matches!(p.steps()[0], Step::Quantise { .. }));
581        let same = plan(
582            fmt(48_000, 2, SampleFormat::Float32),
583            fmt(48_000, 2, SampleFormat::Float32),
584        );
585        assert_eq!(same.kind(), ConversionKind::None);
586    }
587
588    #[test]
589    fn a_rate_change_is_lossy_and_an_integer_target_quantises_the_result() {
590        let p = plan(
591            fmt(44_100, 2, SampleFormat::I16),
592            fmt(48_000, 2, SampleFormat::I16),
593        );
594        assert_eq!(p.kind(), ConversionKind::Lossy);
595        assert!(p.resamples());
596        assert!(matches!(
597            p.steps()[0],
598            Step::Resample {
599                from_hz: 44_100,
600                to_hz: 48_000,
601                quality: Quality::High
602            }
603        ));
604        assert!(matches!(p.steps()[1], Step::Quantise { .. }));
605        assert_eq!(p.steps().len(), 2);
606        assert!(p
607            .description()
608            .starts_with("Lossy conversion, not bit-perfect: resampled from 44100 Hz to 48000 Hz"));
609        assert!(p
610            .description()
611            .contains("quantised to 16-bit with TPDF dither"));
612        // A float target needs no quantising.
613        let float = plan(
614            fmt(44_100, 2, SampleFormat::I16),
615            fmt(48_000, 2, SampleFormat::Float32),
616        );
617        assert_eq!(float.steps().len(), 1);
618    }
619
620    #[test]
621    fn the_steps_of_a_mixed_conversion_are_listed_in_execution_order() {
622        let p = plan(
623            fmt(44_100, 1, SampleFormat::I16),
624            fmt(96_000, 2, SampleFormat::I24),
625        );
626        let codes: Vec<_> = p.steps().iter().map(Step::code).collect();
627        assert_eq!(codes, ["resample", "quantise", "mono_to_stereo"]);
628        assert_eq!(p.kind(), ConversionKind::Lossy);
629    }
630
631    #[test]
632    fn headroom_is_mentioned_when_it_applies() {
633        let options = ConvertOptions {
634            headroom_db: -1.0,
635            ..ConvertOptions::default()
636        };
637        let resampled = ConversionPlan::pcm(
638            fmt(44_100, 2, SampleFormat::I16),
639            fmt(48_000, 2, SampleFormat::I16),
640            &options,
641        )
642        .unwrap();
643        assert!(resampled
644            .description()
645            .contains("-1.0 dB of headroom after resampling"));
646        let not_resampled = ConversionPlan::pcm(
647            fmt(44_100, 2, SampleFormat::I16),
648            fmt(44_100, 2, SampleFormat::I24),
649            &options,
650        )
651        .unwrap();
652        assert!(!not_resampled.description().contains("headroom"));
653    }
654
655    #[test]
656    fn bad_formats_and_options_are_invalid_arguments() {
657        let ok = fmt(44_100, 2, SampleFormat::I16);
658        for bad in [
659            fmt(7_999, 2, SampleFormat::I16),
660            fmt(768_001, 2, SampleFormat::I16),
661            fmt(44_100, 0, SampleFormat::I16),
662            fmt(44_100, 9, SampleFormat::I16),
663        ] {
664            assert_eq!(
665                ConversionPlan::pcm(bad, ok, &ConvertOptions::default())
666                    .unwrap_err()
667                    .code(),
668                "invalid_argument"
669            );
670            assert_eq!(
671                ConversionPlan::pcm(ok, bad, &ConvertOptions::default())
672                    .unwrap_err()
673                    .code(),
674                "invalid_argument"
675            );
676        }
677        for headroom in [1.0, f64::NAN, -61.0] {
678            let options = ConvertOptions {
679                headroom_db: headroom,
680                ..ConvertOptions::default()
681            };
682            assert_eq!(
683                ConversionPlan::pcm(ok, ok, &options).unwrap_err().code(),
684                "invalid_argument"
685            );
686        }
687        assert!(SampleFormat::int(24, 2).is_err());
688        assert!(SampleFormat::int(33, 4).is_err());
689        assert!(SampleFormat::int(16, 5).is_err());
690        assert!(SampleFormat::int(4, 1).is_err());
691    }
692
693    #[test]
694    fn between_reads_a_request_and_a_negotiated_format() {
695        // The host has 44.1 kHz 16-bit; the DAC runs 48 kHz 24-bit in a 4-byte slot (NearestSupported).
696        let request = StreamRequest::pcm(44_100, 2, 16);
697        let format = stream_format(48_000, 2, 24, 4, Encoding::Pcm);
698        let p = ConversionPlan::between(&request, &format, &ConvertOptions::default()).unwrap();
699        assert_eq!(p.source(), fmt(44_100, 2, SampleFormat::I16));
700        assert_eq!(p.target(), fmt(48_000, 2, SampleFormat::I24_IN_32));
701        assert_eq!(p.kind(), ConversionKind::Lossy);
702
703        // Same rate, the DAC only has 32-bit slots: widening, bit-exact.
704        let same = stream_format(44_100, 2, 32, 4, Encoding::Pcm);
705        let p = ConversionPlan::between(&request, &same, &ConvertOptions::default()).unwrap();
706        assert_eq!(p.kind(), ConversionKind::BitExact);
707    }
708
709    #[test]
710    fn between_honours_a_float_source() {
711        let request = StreamRequest::pcm(48_000, 2, 32);
712        let format = stream_format(48_000, 2, 24, 3, Encoding::Pcm);
713        let options = ConvertOptions {
714            source_sample: Some(SampleFormat::Float32),
715            ..ConvertOptions::default()
716        };
717        let p = ConversionPlan::between(&request, &format, &options).unwrap();
718        assert_eq!(p.source().sample, SampleFormat::Float32);
719        assert!(matches!(p.steps()[0], Step::Quantise { .. }));
720    }
721
722    #[test]
723    fn dsd_is_never_converted() {
724        let format = stream_format(44_100, 2, 16, 2, Encoding::Pcm);
725        let dop = StreamRequest::dop(2_822_400, 2);
726        let native = StreamRequest::dsd_native(2_822_400, 2);
727        for request in [dop, native] {
728            let error =
729                ConversionPlan::between(&request, &format, &ConvertOptions::default()).unwrap_err();
730            assert_eq!(error.code(), "unsupported");
731            assert!(error.message().contains("DoP and native DSD"));
732        }
733        let wire = stream_format(176_400, 2, 24, 3, Encoding::DoP);
734        let error = ConversionPlan::between(
735            &StreamRequest::pcm(176_400, 2, 24),
736            &wire,
737            &ConvertOptions::default(),
738        )
739        .unwrap_err();
740        assert_eq!(error.code(), "unsupported");
741    }
742
743    #[test]
744    fn a_source_depth_that_is_not_pcm_is_invalid() {
745        let format = stream_format(44_100, 2, 16, 2, Encoding::Pcm);
746        let error = ConversionPlan::between(
747            &StreamRequest::pcm(44_100, 2, 20),
748            &format,
749            &ConvertOptions::default(),
750        )
751        .unwrap_err();
752        assert_eq!(error.code(), "invalid_argument");
753    }
754}