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 = 1_536_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            || !matches!(target.encoding, Encoding::Pcm | Encoding::PcmFloat32)
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                if target.encoding == Encoding::PcmFloat32 {
203                    if target.valid_bits != 32 || target.subslot_bytes != 4 {
204                        return Err(ConvertError::InvalidArgument(
205                            "float PCM target must use 32-bit slots".into(),
206                        ));
207                    }
208                    SampleFormat::Float32
209                } else {
210                    SampleFormat::int(target.valid_bits, target.subslot_bytes)?
211                },
212            ),
213            options,
214        )
215    }
216
217    /// The plan between two PCM formats.
218    pub fn pcm(
219        source: PcmFormat,
220        target: PcmFormat,
221        options: &ConvertOptions,
222    ) -> Result<Self, ConvertError> {
223        for (name, format) in [("source", &source), ("target", &target)] {
224            if let SampleFormat::Int { bits, slot_bytes } = format.sample {
225                SampleFormat::int(bits, slot_bytes)?;
226            }
227            if !(MIN_RATE..=MAX_RATE).contains(&format.sample_rate) {
228                return Err(ConvertError::InvalidArgument(format!(
229                    "the {name} rate {} Hz is outside {MIN_RATE} to {MAX_RATE} Hz",
230                    format.sample_rate
231                )));
232            }
233            if format.channels == 0 || format.channels > 8 {
234                return Err(ConvertError::InvalidArgument(format!(
235                    "the {name} has {} channels (1 to 8)",
236                    format.channels
237                )));
238            }
239        }
240        if !(options.headroom_db.is_finite() && (-60.0..=0.0).contains(&options.headroom_db)) {
241            return Err(ConvertError::InvalidArgument(
242                "headroom_db must be between -60 and 0".into(),
243            ));
244        }
245        let dup = match (source.channels, target.channels) {
246            (a, b) if a == b => false,
247            (1, 2) => true,
248            (a, b) => {
249                return Err(ConvertError::Unsupported(format!(
250                    "{a} channels cannot be converted to {b}: only mono to stereo is supported"
251                )))
252            }
253        };
254
255        let mut steps = Vec::new();
256        let resample = source.sample_rate != target.sample_rate;
257        if resample {
258            steps.push(Step::Resample {
259                from_hz: source.sample_rate,
260                to_hz: target.sample_rate,
261                quality: options.quality,
262            });
263        }
264        match (source.sample, target.sample) {
265            (a, b) if a == b && !resample => {}
266            // After resampling the values are not integers any more; an integer target rounds them.
267            (_, SampleFormat::Float32) if resample => {}
268            (_, to @ SampleFormat::Int { .. }) if resample => steps.push(Step::Quantise {
269                to,
270                mode: options.narrowing,
271            }),
272            (SampleFormat::Float32, SampleFormat::Float32) => {}
273            (from @ SampleFormat::Int { .. }, SampleFormat::Float32) => {
274                steps.push(Step::IntToFloat { from })
275            }
276            (SampleFormat::Float32, to @ SampleFormat::Int { .. }) => steps.push(Step::Quantise {
277                to,
278                mode: options.narrowing,
279            }),
280            (
281                from @ SampleFormat::Int {
282                    bits: from_bits, ..
283                },
284                to @ SampleFormat::Int { bits: to_bits, .. },
285            ) => steps.push(if to_bits > from_bits {
286                Step::Widen { from, to }
287            } else if to_bits == from_bits {
288                Step::Repack { from, to }
289            } else {
290                Step::Narrow {
291                    from,
292                    to,
293                    mode: options.narrowing,
294                }
295            }),
296        }
297        if dup {
298            steps.push(Step::MonoToStereo);
299        }
300
301        let kind = steps
302            .iter()
303            .map(Step::kind)
304            .max()
305            .unwrap_or(ConversionKind::None);
306        let mut description = describe(kind, &steps, options.headroom_db);
307        if let SampleFormat::Int { bits, slot_bytes } = source.sample {
308            if u16::from(bits) < u16::from(slot_bytes) * 8 {
309                description.push_str(" Declared zero padding is validated on every input buffer.");
310            }
311        }
312        Ok(Self {
313            source,
314            target,
315            options: *options,
316            steps,
317            kind,
318            description,
319        })
320    }
321
322    pub fn source(&self) -> PcmFormat {
323        self.source
324    }
325
326    pub fn target(&self) -> PcmFormat {
327        self.target
328    }
329
330    pub fn options(&self) -> &ConvertOptions {
331        &self.options
332    }
333
334    pub fn steps(&self) -> &[Step] {
335        &self.steps
336    }
337
338    /// The worst of the steps: [`ConversionKind::None`] if there are none.
339    pub fn kind(&self) -> ConversionKind {
340        self.kind
341    }
342
343    /// A sentence that says what is done and how much it costs, for a status line or a log.
344    pub fn description(&self) -> &str {
345        &self.description
346    }
347
348    /// Whether the sample rate changes.
349    pub fn resamples(&self) -> bool {
350        self.steps
351            .iter()
352            .any(|step| matches!(step, Step::Resample { .. }))
353    }
354
355    /// Whether a bit-perfect target stream is still bit-perfect with respect to the source.
356    pub fn preserves_bit_perfect(&self) -> bool {
357        self.kind.preserves_bit_perfect()
358    }
359}
360
361fn describe(kind: ConversionKind, steps: &[Step], headroom_db: f64) -> String {
362    let lead = match kind {
363        ConversionKind::None => {
364            return "No conversion: the samples pass through unchanged.".to_string()
365        }
366        ConversionKind::BitExact => "Bit-exact conversion",
367        ConversionKind::Lossless => "Lossless conversion, but the audio is not identical",
368        ConversionKind::Lossy => "Lossy conversion, not bit-perfect",
369    };
370    let mut text = format!(
371        "{lead}: {}",
372        steps
373            .iter()
374            .map(Step::describe)
375            .collect::<Vec<_>>()
376            .join("; ")
377    );
378    if headroom_db != 0.0
379        && steps
380            .iter()
381            .any(|step| matches!(step, Step::Resample { .. }))
382    {
383        text.push_str(&format!(
384            "; {:.1} dB of headroom after resampling",
385            headroom_db
386        ));
387    }
388    text.push('.');
389    text
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395    use crate::capabilities::{LinkSpeed, Pacing, SyncKind};
396
397    fn fmt(rate: u32, channels: u16, sample: SampleFormat) -> PcmFormat {
398        PcmFormat::new(rate, channels, sample)
399    }
400
401    fn plan(source: PcmFormat, target: PcmFormat) -> ConversionPlan {
402        ConversionPlan::pcm(source, target, &ConvertOptions::default()).unwrap()
403    }
404
405    fn stream_format(
406        rate: u32,
407        channels: u16,
408        valid_bits: u8,
409        subslot_bytes: u8,
410        encoding: Encoding,
411    ) -> StreamFormat {
412        StreamFormat {
413            request: StreamRequest::pcm(rate, channels, valid_bits),
414            encoding,
415            sample_rate: rate,
416            channels,
417            valid_bits,
418            subslot_bytes,
419            interface_number: 1,
420            alt_setting: 1,
421            endpoint_address: 1,
422            sync_type: SyncKind::Asynchronous,
423            explicit_feedback: true,
424            link_speed: LinkSpeed::High,
425            service_interval_us: 125,
426            pacing: Pacing::ExplicitFeedback { endpoint: 0x81 },
427            clock: None,
428            native_dsd_signature: None,
429            channel_map: crate::capture::ChannelMap::uac2(channels, 0).unwrap(),
430        }
431    }
432
433    #[test]
434    fn float_stream_request_uses_float_layout_and_rejects_integer_override() {
435        let source = StreamRequest::pcm_float32(44_100, 2);
436        let target = stream_format(44_100, 2, 16, 2, Encoding::Pcm);
437        let plan = ConversionPlan::between(&source, &target, &ConvertOptions::default()).unwrap();
438        assert_eq!(plan.source().sample, SampleFormat::Float32);
439        assert_eq!(plan.kind(), ConversionKind::Lossy);
440        let options = ConvertOptions {
441            source_sample: Some(SampleFormat::I32),
442            ..ConvertOptions::default()
443        };
444        assert!(ConversionPlan::between(&source, &target, &options).is_err());
445    }
446
447    #[test]
448    fn identical_formats_need_no_conversion() {
449        let p = plan(
450            fmt(44_100, 2, SampleFormat::I16),
451            fmt(44_100, 2, SampleFormat::I16),
452        );
453        assert_eq!(p.kind(), ConversionKind::None);
454        assert!(p.steps().is_empty());
455        assert_eq!(
456            p.description(),
457            "No conversion: the samples pass through unchanged."
458        );
459        assert!(p.preserves_bit_perfect());
460    }
461
462    #[test]
463    fn widening_and_repacking_are_bit_exact() {
464        let widen = plan(
465            fmt(44_100, 2, SampleFormat::I16),
466            fmt(44_100, 2, SampleFormat::I24),
467        );
468        assert_eq!(widen.kind(), ConversionKind::BitExact);
469        assert_eq!(widen.steps().len(), 1);
470        assert!(matches!(widen.steps()[0], Step::Widen { .. }));
471        assert!(widen
472            .description()
473            .starts_with("Bit-exact conversion: 16-bit widened to 24-bit packed"));
474        assert!(widen.preserves_bit_perfect());
475
476        let to32 = plan(
477            fmt(48_000, 2, SampleFormat::I16),
478            fmt(48_000, 2, SampleFormat::I32),
479        );
480        assert_eq!(to32.kind(), ConversionKind::BitExact);
481
482        let repack = plan(
483            fmt(96_000, 2, SampleFormat::I24),
484            fmt(96_000, 2, SampleFormat::I24_IN_32),
485        );
486        assert_eq!(repack.kind(), ConversionKind::BitExact);
487        assert!(matches!(repack.steps()[0], Step::Repack { .. }));
488        let back = plan(
489            fmt(96_000, 2, SampleFormat::I24_IN_32),
490            fmt(96_000, 2, SampleFormat::I24),
491        );
492        assert_eq!(back.kind(), ConversionKind::BitExact);
493
494        // 16-bit in a 3-byte slot: the sample shifted left by 8.
495        let slot = plan(
496            fmt(44_100, 2, SampleFormat::I16),
497            SampleFormat::int(16, 3).map(|s| fmt(44_100, 2, s)).unwrap(),
498        );
499        assert_eq!(slot.kind(), ConversionKind::BitExact);
500    }
501
502    #[test]
503    fn narrowing_is_lossy_with_the_chosen_mode() {
504        let p = plan(
505            fmt(44_100, 2, SampleFormat::I24),
506            fmt(44_100, 2, SampleFormat::I16),
507        );
508        assert_eq!(p.kind(), ConversionKind::Lossy);
509        assert!(
510            p.description()
511                .contains("narrowed to 16-bit with TPDF dither"),
512            "{}",
513            p.description()
514        );
515        let truncate = ConversionPlan::pcm(
516            fmt(44_100, 2, SampleFormat::I32),
517            fmt(44_100, 2, SampleFormat::I16),
518            &ConvertOptions {
519                narrowing: Narrowing::Truncate,
520                ..ConvertOptions::default()
521            },
522        )
523        .unwrap();
524        assert!(
525            truncate.description().contains("by truncation"),
526            "{}",
527            truncate.description()
528        );
529        assert!(!truncate.preserves_bit_perfect());
530    }
531
532    #[test]
533    fn mono_to_stereo_is_lossless_but_not_identical() {
534        let p = plan(
535            fmt(44_100, 1, SampleFormat::I16),
536            fmt(44_100, 2, SampleFormat::I16),
537        );
538        assert_eq!(p.kind(), ConversionKind::Lossless);
539        assert_eq!(p.steps(), &[Step::MonoToStereo]);
540        assert!(p
541            .description()
542            .starts_with("Lossless conversion, but the audio is not identical"));
543        assert!(!p.preserves_bit_perfect());
544    }
545
546    #[test]
547    fn other_channel_changes_are_unsupported() {
548        for (from, to) in [(2, 1), (6, 2), (2, 6), (1, 4)] {
549            let error = ConversionPlan::pcm(
550                fmt(44_100, from, SampleFormat::I16),
551                fmt(44_100, to, SampleFormat::I16),
552                &ConvertOptions::default(),
553            )
554            .unwrap_err();
555            assert_eq!(error.code(), "unsupported", "{from} -> {to}");
556            assert!(error.message().contains("only mono to stereo"));
557        }
558    }
559
560    #[test]
561    fn integer_to_float_is_lossless_up_to_24_bits_and_lossy_beyond() {
562        for sample in [
563            SampleFormat::I16,
564            SampleFormat::I24,
565            SampleFormat::I24_IN_32,
566        ] {
567            let p = plan(
568                fmt(48_000, 2, sample),
569                fmt(48_000, 2, SampleFormat::Float32),
570            );
571            assert_eq!(p.kind(), ConversionKind::Lossless, "{sample:?}");
572            assert!(p.description().contains("(exact)"));
573        }
574        let p = plan(
575            fmt(48_000, 2, SampleFormat::I32),
576            fmt(48_000, 2, SampleFormat::Float32),
577        );
578        assert_eq!(p.kind(), ConversionKind::Lossy);
579        assert!(p.description().contains("rounded to 24 significant bits"));
580    }
581
582    #[test]
583    fn float_to_integer_is_lossy() {
584        let p = plan(
585            fmt(48_000, 2, SampleFormat::Float32),
586            fmt(48_000, 2, SampleFormat::I24),
587        );
588        assert_eq!(p.kind(), ConversionKind::Lossy);
589        assert!(matches!(p.steps()[0], Step::Quantise { .. }));
590        let same = plan(
591            fmt(48_000, 2, SampleFormat::Float32),
592            fmt(48_000, 2, SampleFormat::Float32),
593        );
594        assert_eq!(same.kind(), ConversionKind::None);
595    }
596
597    #[test]
598    fn a_rate_change_is_lossy_and_an_integer_target_quantises_the_result() {
599        let p = plan(
600            fmt(44_100, 2, SampleFormat::I16),
601            fmt(48_000, 2, SampleFormat::I16),
602        );
603        assert_eq!(p.kind(), ConversionKind::Lossy);
604        assert!(p.resamples());
605        assert!(matches!(
606            p.steps()[0],
607            Step::Resample {
608                from_hz: 44_100,
609                to_hz: 48_000,
610                quality: Quality::High
611            }
612        ));
613        assert!(matches!(p.steps()[1], Step::Quantise { .. }));
614        assert_eq!(p.steps().len(), 2);
615        assert!(p
616            .description()
617            .starts_with("Lossy conversion, not bit-perfect: resampled from 44100 Hz to 48000 Hz"));
618        assert!(p
619            .description()
620            .contains("quantised to 16-bit with TPDF dither"));
621        // A float target needs no quantising.
622        let float = plan(
623            fmt(44_100, 2, SampleFormat::I16),
624            fmt(48_000, 2, SampleFormat::Float32),
625        );
626        assert_eq!(float.steps().len(), 1);
627    }
628
629    #[test]
630    fn the_steps_of_a_mixed_conversion_are_listed_in_execution_order() {
631        let p = plan(
632            fmt(44_100, 1, SampleFormat::I16),
633            fmt(96_000, 2, SampleFormat::I24),
634        );
635        let codes: Vec<_> = p.steps().iter().map(Step::code).collect();
636        assert_eq!(codes, ["resample", "quantise", "mono_to_stereo"]);
637        assert_eq!(p.kind(), ConversionKind::Lossy);
638    }
639
640    #[test]
641    fn headroom_is_mentioned_when_it_applies() {
642        let options = ConvertOptions {
643            headroom_db: -1.0,
644            ..ConvertOptions::default()
645        };
646        let resampled = ConversionPlan::pcm(
647            fmt(44_100, 2, SampleFormat::I16),
648            fmt(48_000, 2, SampleFormat::I16),
649            &options,
650        )
651        .unwrap();
652        assert!(resampled
653            .description()
654            .contains("-1.0 dB of headroom after resampling"));
655        let not_resampled = ConversionPlan::pcm(
656            fmt(44_100, 2, SampleFormat::I16),
657            fmt(44_100, 2, SampleFormat::I24),
658            &options,
659        )
660        .unwrap();
661        assert!(!not_resampled.description().contains("headroom"));
662    }
663
664    #[test]
665    fn bad_formats_and_options_are_invalid_arguments() {
666        let ok = fmt(44_100, 2, SampleFormat::I16);
667        for bad in [
668            fmt(7_999, 2, SampleFormat::I16),
669            fmt(MAX_RATE + 1, 2, SampleFormat::I16),
670            fmt(44_100, 0, SampleFormat::I16),
671            fmt(44_100, 9, SampleFormat::I16),
672        ] {
673            assert_eq!(
674                ConversionPlan::pcm(bad, ok, &ConvertOptions::default())
675                    .unwrap_err()
676                    .code(),
677                "invalid_argument"
678            );
679            assert_eq!(
680                ConversionPlan::pcm(ok, bad, &ConvertOptions::default())
681                    .unwrap_err()
682                    .code(),
683                "invalid_argument"
684            );
685        }
686        for headroom in [1.0, f64::NAN, -61.0] {
687            let options = ConvertOptions {
688                headroom_db: headroom,
689                ..ConvertOptions::default()
690            };
691            assert_eq!(
692                ConversionPlan::pcm(ok, ok, &options).unwrap_err().code(),
693                "invalid_argument"
694            );
695        }
696        assert!(SampleFormat::int(24, 2).is_err());
697        assert!(SampleFormat::int(33, 4).is_err());
698        assert!(SampleFormat::int(16, 5).is_err());
699        assert!(SampleFormat::int(4, 1).is_err());
700    }
701
702    #[test]
703    fn between_reads_a_request_and_a_negotiated_format() {
704        // The host has 44.1 kHz 16-bit; the DAC runs 48 kHz 24-bit in a 4-byte slot (NearestSupported).
705        let request = StreamRequest::pcm(44_100, 2, 16);
706        let format = stream_format(48_000, 2, 24, 4, Encoding::Pcm);
707        let p = ConversionPlan::between(&request, &format, &ConvertOptions::default()).unwrap();
708        assert_eq!(p.source(), fmt(44_100, 2, SampleFormat::I16));
709        assert_eq!(p.target(), fmt(48_000, 2, SampleFormat::I24_IN_32));
710        assert_eq!(p.kind(), ConversionKind::Lossy);
711
712        // Same rate, the DAC only has 32-bit slots: widening, bit-exact.
713        let same = stream_format(44_100, 2, 32, 4, Encoding::Pcm);
714        let p = ConversionPlan::between(&request, &same, &ConvertOptions::default()).unwrap();
715        assert_eq!(p.kind(), ConversionKind::BitExact);
716    }
717
718    #[test]
719    fn between_honours_a_float_source() {
720        let request = StreamRequest::pcm(48_000, 2, 32);
721        let format = stream_format(48_000, 2, 24, 3, Encoding::Pcm);
722        let options = ConvertOptions {
723            source_sample: Some(SampleFormat::Float32),
724            ..ConvertOptions::default()
725        };
726        let p = ConversionPlan::between(&request, &format, &options).unwrap();
727        assert_eq!(p.source().sample, SampleFormat::Float32);
728        assert!(matches!(p.steps()[0], Step::Quantise { .. }));
729    }
730
731    #[test]
732    fn dsd_is_never_converted() {
733        let format = stream_format(44_100, 2, 16, 2, Encoding::Pcm);
734        let dop = StreamRequest::dop(2_822_400, 2);
735        let native = StreamRequest::dsd_native(2_822_400, 2);
736        for request in [dop, native] {
737            let error =
738                ConversionPlan::between(&request, &format, &ConvertOptions::default()).unwrap_err();
739            assert_eq!(error.code(), "unsupported");
740            assert!(error.message().contains("DoP and native DSD"));
741        }
742        let wire = stream_format(176_400, 2, 24, 3, Encoding::DoP);
743        let error = ConversionPlan::between(
744            &StreamRequest::pcm(176_400, 2, 24),
745            &wire,
746            &ConvertOptions::default(),
747        )
748        .unwrap_err();
749        assert_eq!(error.code(), "unsupported");
750    }
751
752    #[test]
753    fn a_source_depth_that_is_not_pcm_is_invalid() {
754        let format = stream_format(44_100, 2, 16, 2, Encoding::Pcm);
755        let error = ConversionPlan::between(
756            &StreamRequest::pcm(44_100, 2, 20),
757            &format,
758            &ConvertOptions::default(),
759        )
760        .unwrap_err();
761        assert_eq!(error.code(), "invalid_argument");
762    }
763}