Skip to main content

usbdac_core/convert/
converter.rs

1//! The streaming executor of a [`ConversionPlan`].
2//!
3//! Two engines do the work. Plans that only move integers between layouts (widening, repacking,
4//! narrowing, mono to stereo) run on the integer engine: left-justified `i32` values, no floating
5//! point, so a bit-exact plan is exactly that. Plans that resample, or that involve floats, run on
6//! the float engine: samples decoded to `f64` (exact for every integer layout), resampled per
7//! channel, duplicated if mono to stereo, and encoded with the plan's narrowing mode.
8//!
9//! Both work on whole frames, in blocks of at most [`BLOCK_FRAMES`], with scratch buffers made when
10//! the converter is: `process`, `finish` and `reset` allocate nothing.
11
12use super::format::{ConvertError, Narrowing, PcmFormat, SampleFormat};
13use super::plan::{ConversionPlan, Step};
14use super::resample::Resampler;
15use super::samples::{self, Rng};
16
17/// The most frames one pass of the float engine handles.
18pub const BLOCK_FRAMES: usize = 1024;
19
20/// What one call to [`Converter::process`] did, in bytes.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22pub struct Processed {
23    /// Input bytes used: whole source frames.
24    pub consumed: usize,
25    /// Output bytes written: whole target frames.
26    pub produced: usize,
27}
28
29struct IntegerEngine {
30    source_bits: u8,
31    source_slot: usize,
32    target_bits: u8,
33    target_slot: usize,
34    channels: usize,
35    duplicate: bool,
36    mode: Narrowing,
37    narrow: bool,
38    rng: Rng,
39}
40
41impl IntegerEngine {
42    fn process(&mut self, input: &[u8], output: &mut [u8], clipped: &mut u64) -> (usize, usize) {
43        let source_frame = self.channels * self.source_slot;
44        let target_channels = if self.duplicate { 2 } else { self.channels };
45        let target_frame = target_channels * self.target_slot;
46        let frames = (input.len() / source_frame).min(output.len() / target_frame);
47        for frame in 0..frames {
48            let source = &input[frame * source_frame..(frame + 1) * source_frame];
49            let target = &mut output[frame * target_frame..(frame + 1) * target_frame];
50            for channel in 0..target_channels {
51                let from = if self.duplicate { 0 } else { channel };
52                let mut value = samples::read_int(
53                    &source[from * self.source_slot..],
54                    self.source_slot,
55                    self.source_bits,
56                );
57                if self.narrow {
58                    value =
59                        samples::narrow(value, self.target_bits, self.mode, &mut self.rng, clipped);
60                } else {
61                    value &= samples::keep_mask(self.target_bits.min(32));
62                }
63                samples::write_int(
64                    &mut target[channel * self.target_slot..],
65                    self.target_slot,
66                    value,
67                );
68            }
69        }
70        (frames * source_frame, frames * target_frame)
71    }
72}
73
74struct FloatEngine {
75    source: SampleFormat,
76    target: SampleFormat,
77    channels: usize,
78    duplicate: bool,
79    resampler: Option<Resampler>,
80    gain: f64,
81    mode: Narrowing,
82    rng: Rng,
83    planar_in: Vec<Vec<f64>>,
84    planar_out: Vec<Vec<f64>>,
85    /// Zeros still to feed to flush the resampler's tail.
86    pad_left: usize,
87    finishing: bool,
88}
89
90impl FloatEngine {
91    fn decode(&mut self, input: &[u8], frames: usize) {
92        let slot = self.source.bytes_per_sample();
93        let frame_bytes = slot * self.channels;
94        for frame in 0..frames {
95            for channel in 0..self.channels {
96                let bytes = &input[frame * frame_bytes + channel * slot..];
97                self.planar_in[channel][frame] = match self.source {
98                    SampleFormat::Float32 => samples::read_float(bytes),
99                    SampleFormat::Int { bits, slot_bytes } => {
100                        samples::int_to_f64(samples::read_int(bytes, usize::from(slot_bytes), bits))
101                    }
102                };
103            }
104        }
105    }
106
107    /// Encodes `frames` frames of `planar` (from `planar_in` or `planar_out`) into `output`.
108    // Keep explicit geometry and disjoint RNG/output/counter borrows on this
109    // allocation-free codec path rather than bundling them into shared state.
110    #[allow(clippy::too_many_arguments)]
111    fn encode(
112        planar: &[Vec<f64>],
113        frames: usize,
114        duplicate: bool,
115        gain: f64,
116        target: SampleFormat,
117        mode: Narrowing,
118        rng: &mut Rng,
119        output: &mut [u8],
120        clipped: &mut u64,
121    ) {
122        let slot = target.bytes_per_sample();
123        let target_channels = if duplicate { 2 } else { planar.len() };
124        let frame_bytes = slot * target_channels;
125        for frame in 0..frames {
126            for channel in 0..target_channels {
127                let x = planar[if duplicate { 0 } else { channel }][frame] * gain;
128                let bytes = &mut output[frame * frame_bytes + channel * slot..];
129                match target {
130                    SampleFormat::Float32 => bytes[..4].copy_from_slice(&(x as f32).to_le_bytes()),
131                    SampleFormat::Int { bits, slot_bytes } => {
132                        let value = samples::float_to_int(x, bits, mode, rng, clipped);
133                        samples::write_int(bytes, usize::from(slot_bytes), value);
134                    }
135                }
136            }
137        }
138    }
139
140    fn process(&mut self, input: &[u8], output: &mut [u8], clipped: &mut u64) -> (usize, usize) {
141        let source_frame = self.source.bytes_per_sample() * self.channels;
142        let target_channels = if self.duplicate { 2 } else { self.channels };
143        let target_frame = self.target.bytes_per_sample() * target_channels;
144        let in_frames = input.len() / source_frame;
145        let out_frames = output.len() / target_frame;
146        let (mut consumed, mut produced) = (0usize, 0usize);
147        while consumed < in_frames {
148            let room = out_frames - produced;
149            let mut n = (in_frames - consumed).min(BLOCK_FRAMES);
150            n = match &self.resampler {
151                Some(resampler) => n.min(resampler.max_input_for_output(room)),
152                None => n.min(room),
153            };
154            if n == 0 {
155                break;
156            }
157            self.decode(&input[consumed * source_frame..], n);
158            produced += self.encode_block(n, &mut output[produced * target_frame..], clipped);
159            consumed += n;
160        }
161        (consumed * source_frame, produced * target_frame)
162    }
163
164    /// Runs the `n` decoded frames of `planar_in` through the resampler (if any) and encodes the
165    /// result into `output`. Returns the frames written.
166    fn encode_block(&mut self, n: usize, output: &mut [u8], clipped: &mut u64) -> usize {
167        let frames = match &mut self.resampler {
168            Some(resampler) => resampler.process(&self.planar_in, n, &mut self.planar_out),
169            None => n,
170        };
171        let planar = if self.resampler.is_some() {
172            &self.planar_out
173        } else {
174            &self.planar_in
175        };
176        Self::encode(
177            planar,
178            frames,
179            self.duplicate,
180            self.gain,
181            self.target,
182            self.mode,
183            &mut self.rng,
184            output,
185            clipped,
186        );
187        frames
188    }
189
190    /// Feeds the zeros that flush the resampler's tail, as far as `output` has room.
191    fn finish(&mut self, output: &mut [u8], clipped: &mut u64) -> usize {
192        self.finishing = true;
193        if self.resampler.is_none() {
194            return 0;
195        }
196        let target_channels = if self.duplicate { 2 } else { self.channels };
197        let target_frame = self.target.bytes_per_sample() * target_channels;
198        let out_frames = output.len() / target_frame;
199        let mut produced = 0usize;
200        while self.pad_left > 0 {
201            let room = out_frames - produced;
202            let allowed = self
203                .resampler
204                .as_ref()
205                .map_or(0, |r| r.max_input_for_output(room));
206            let n = self.pad_left.min(BLOCK_FRAMES).min(allowed);
207            if n == 0 {
208                break;
209            }
210            for channel in &mut self.planar_in {
211                channel[..n].fill(0.0);
212            }
213            produced += self.encode_block(n, &mut output[produced * target_frame..], clipped);
214            self.pad_left -= n;
215        }
216        produced * target_frame
217    }
218
219    fn reset(&mut self) {
220        if let Some(resampler) = &mut self.resampler {
221            resampler.reset();
222            self.pad_left = resampler.pad_frames();
223        }
224        self.finishing = false;
225    }
226}
227
228enum Engine {
229    /// The formats are the same: the bytes are copied.
230    Copy {
231        frame_bytes: usize,
232    },
233    Integer(IntegerEngine),
234    Float(Box<FloatEngine>),
235}
236
237/// Turns audio in the plan's source format into the target format, a chunk at a time.
238///
239/// `process` takes whole frames from the front of the input and writes whole frames to the output,
240/// as many as fit in either; the caller keeps what was not consumed. After the last chunk call
241/// [`Converter::finish`] until it returns 0 to get the resampler's tail, then [`Converter::reset`]
242/// to start another stream (a seek is a reset too: the filter's history belongs to the old position).
243pub struct Converter {
244    plan: ConversionPlan,
245    engine: Engine,
246    source_frame: usize,
247    target_frame: usize,
248    clipped: u64,
249}
250
251impl Converter {
252    pub fn new(plan: &ConversionPlan) -> Result<Self, ConvertError> {
253        let source = plan.source();
254        let target = plan.target();
255        let options = plan.options();
256        let channels = usize::from(source.channels);
257        let duplicate = plan
258            .steps()
259            .iter()
260            .any(|step| matches!(step, Step::MonoToStereo));
261        let engine = if plan.steps().is_empty() {
262            Engine::Copy {
263                frame_bytes: source.bytes_per_frame(),
264            }
265        } else if !plan.resamples()
266            && matches!(source.sample, SampleFormat::Int { .. })
267            && matches!(target.sample, SampleFormat::Int { .. })
268        {
269            let (
270                SampleFormat::Int {
271                    bits: source_bits,
272                    slot_bytes: source_slot,
273                },
274                SampleFormat::Int {
275                    bits: target_bits,
276                    slot_bytes: target_slot,
277                },
278            ) = (source.sample, target.sample)
279            else {
280                unreachable!("both are integers")
281            };
282            Engine::Integer(IntegerEngine {
283                source_bits,
284                source_slot: usize::from(source_slot),
285                target_bits,
286                target_slot: usize::from(target_slot),
287                channels,
288                duplicate,
289                mode: options.narrowing,
290                narrow: target_bits < source_bits,
291                rng: Rng::new(options.dither_seed),
292            })
293        } else {
294            let resampler = if plan.resamples() {
295                Some(Resampler::new(
296                    source.sample_rate,
297                    target.sample_rate,
298                    channels,
299                    options.quality,
300                    BLOCK_FRAMES,
301                )?)
302            } else {
303                None
304            };
305            // A block of BLOCK_FRAMES produces at most ceil(BLOCK_FRAMES * L / M) frames.
306            let max_out = match &resampler {
307                Some(resampler) => {
308                    let info = resampler.info();
309                    (BLOCK_FRAMES * info.l).div_ceil(info.m) + 2
310                }
311                None => 0,
312            };
313            let pad_left = resampler.as_ref().map_or(0, Resampler::pad_frames);
314            Engine::Float(Box::new(FloatEngine {
315                source: source.sample,
316                target: target.sample,
317                channels,
318                duplicate,
319                resampler,
320                gain: if plan.resamples() {
321                    10f64.powf(options.headroom_db / 20.0)
322                } else {
323                    1.0
324                },
325                mode: options.narrowing,
326                rng: Rng::new(options.dither_seed),
327                planar_in: vec![vec![0.0; BLOCK_FRAMES]; channels],
328                planar_out: vec![vec![0.0; max_out]; channels],
329                pad_left,
330                finishing: false,
331            }))
332        };
333        Ok(Self {
334            plan: plan.clone(),
335            engine,
336            source_frame: source.bytes_per_frame(),
337            target_frame: target.bytes_per_frame(),
338            clipped: 0,
339        })
340    }
341
342    pub fn plan(&self) -> &ConversionPlan {
343        &self.plan
344    }
345
346    pub fn source(&self) -> PcmFormat {
347        self.plan.source()
348    }
349
350    pub fn target(&self) -> PcmFormat {
351        self.plan.target()
352    }
353
354    /// Bytes of one source frame: the unit `process` takes.
355    pub fn source_frame_bytes(&self) -> usize {
356        self.source_frame
357    }
358
359    /// Bytes of one target frame: the unit `process` writes.
360    pub fn target_frame_bytes(&self) -> usize {
361        self.target_frame
362    }
363
364    /// Source frames the converter holds back before the output reflects them: the resampler's
365    /// algorithmic latency (a few milliseconds), 0 for every other plan. Output frame `n` is
366    /// aligned with source time `n * source_rate / target_rate` exactly, so a position needs no
367    /// correction; only the delay between feeding audio and hearing it grows by this much.
368    pub fn delay_frames(&self) -> usize {
369        match &self.engine {
370            Engine::Float(engine) => engine.resampler.as_ref().map_or(0, Resampler::delay_frames),
371            _ => 0,
372        }
373    }
374
375    /// The smallest output buffer `process` and `finish` make progress with: room for the frames one
376    /// source frame can turn into (`ceil(target_rate / source_rate)` when resampling, 1 otherwise).
377    /// With less, `process` can consume nothing and `finish` can return 0 before the end.
378    pub fn min_output_bytes(&self) -> usize {
379        let frames = match &self.engine {
380            Engine::Float(engine) => engine.resampler.as_ref().map_or(1, |resampler| {
381                let info = resampler.info();
382                info.l.div_ceil(info.m).max(1)
383            }),
384            _ => 1,
385        };
386        frames * self.target_frame
387    }
388
389    /// Samples that exceeded full scale and were saturated, since the start or the last reset.
390    pub fn clipped_samples(&self) -> u64 {
391        self.clipped
392    }
393
394    /// Converts whole frames. Declared integer padding is checked before any output or state change.
395    /// Nonzero padding returns `InvalidArgument`; after `finish`, call `reset` first.
396    pub fn process(&mut self, input: &[u8], output: &mut [u8]) -> Result<Processed, ConvertError> {
397        if let SampleFormat::Int { bits, slot_bytes } = self.plan.source().sample {
398            let padding = u32::from(slot_bytes) * 8 - u32::from(bits);
399            if padding > 0 {
400                let slot = usize::from(slot_bytes);
401                let whole = input.len() / self.source_frame * self.source_frame;
402                let mask = (1u32 << padding) - 1;
403                for sample in input[..whole].chunks_exact(slot) {
404                    let mut word = 0u32;
405                    for (i, byte) in sample.iter().enumerate() {
406                        word |= u32::from(*byte) << (i * 8);
407                    }
408                    if word & mask != 0 {
409                        return Err(ConvertError::InvalidArgument(
410                            "source integer sample has nonzero declared padding bits".into(),
411                        ));
412                    }
413                }
414            }
415        }
416        let (consumed, produced) = match &mut self.engine {
417            Engine::Copy { frame_bytes } => {
418                let frames = (input.len() / *frame_bytes).min(output.len() / *frame_bytes);
419                let bytes = frames * *frame_bytes;
420                output[..bytes].copy_from_slice(&input[..bytes]);
421                (bytes, bytes)
422            }
423            Engine::Integer(engine) => engine.process(input, output, &mut self.clipped),
424            Engine::Float(engine) => {
425                if engine.finishing {
426                    return Err(ConvertError::InvalidState(
427                        "finish() was called: reset() before converting more".into(),
428                    ));
429                }
430                engine.process(input, output, &mut self.clipped)
431            }
432        };
433        Ok(Processed { consumed, produced })
434    }
435
436    /// Writes the end of the stream: the frames the resampler still holds, as far as `output` has
437    /// room. Call it until it returns 0. Nothing else follows a `finish`: [`Converter::process`]
438    /// fails until [`Converter::reset`].
439    pub fn finish(&mut self, output: &mut [u8]) -> Result<usize, ConvertError> {
440        Ok(match &mut self.engine {
441            Engine::Float(engine) => engine.finish(output, &mut self.clipped),
442            _ => 0,
443        })
444    }
445
446    /// Starts a new stream: the filter's history, the dither state and the counters are cleared.
447    pub fn reset(&mut self) {
448        match &mut self.engine {
449            Engine::Float(engine) => {
450                engine.reset();
451                engine.rng = Rng::new(self.plan.options().dither_seed);
452            }
453            Engine::Integer(engine) => engine.rng = Rng::new(self.plan.options().dither_seed),
454            Engine::Copy { .. } => {}
455        }
456        self.clipped = 0;
457    }
458
459    /// Output bytes `process` writes for `input_bytes` of input, if the output buffer is large
460    /// enough, rounded down to whole frames. Exact for every plan; for a resampling one it depends
461    /// on how much has been fed so far.
462    pub fn output_len_for(&self, input_bytes: usize) -> usize {
463        let frames = input_bytes / self.source_frame;
464        let out_frames = match &self.engine {
465            Engine::Float(engine) => match &engine.resampler {
466                Some(resampler) => resampler.output_len_for(frames),
467                None => frames,
468            },
469            _ => frames,
470        };
471        out_frames * self.target_frame
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478    use crate::convert::format::{ConvertOptions, Quality};
479
480    fn converter(source: PcmFormat, target: PcmFormat, options: ConvertOptions) -> Converter {
481        Converter::new(&ConversionPlan::pcm(source, target, &options).unwrap()).unwrap()
482    }
483
484    fn fmt(rate: u32, channels: u16, sample: SampleFormat) -> PcmFormat {
485        PcmFormat::new(rate, channels, sample)
486    }
487
488    /// Runs everything through in `chunk`-byte pieces with an output buffer of `room` bytes.
489    fn convert_all(c: &mut Converter, input: &[u8], chunk: usize, room: usize) -> Vec<u8> {
490        let mut result = Vec::new();
491        let mut buffer = vec![0u8; room];
492        let mut pending: &[u8] = &[];
493        let mut rest = input;
494        let chunk = (chunk / c.source_frame_bytes()).max(1) * c.source_frame_bytes();
495        loop {
496            if pending.is_empty() && !rest.is_empty() {
497                let take = chunk.min(rest.len());
498                pending = &rest[..take];
499                rest = &rest[take..];
500            }
501            if pending.is_empty() {
502                break;
503            }
504            let done = c.process(pending, &mut buffer).unwrap();
505            result.extend_from_slice(&buffer[..done.produced]);
506            pending = &pending[done.consumed..];
507            if done.consumed == 0 && done.produced == 0 {
508                // A partial frame at the end of the stream: nothing more to do.
509                assert!(
510                    pending.len() < c.source_frame_bytes(),
511                    "stuck with {} bytes",
512                    pending.len()
513                );
514                break;
515            }
516        }
517        loop {
518            let n = c.finish(&mut buffer).unwrap();
519            if n == 0 {
520                break;
521            }
522            result.extend_from_slice(&buffer[..n]);
523        }
524        result
525    }
526
527    fn i16_bytes(values: &[i16]) -> Vec<u8> {
528        values.iter().flat_map(|v| v.to_le_bytes()).collect()
529    }
530
531    #[test]
532    fn identical_formats_copy_the_bytes() {
533        let mut c = converter(
534            fmt(44_100, 2, SampleFormat::I16),
535            fmt(44_100, 2, SampleFormat::I16),
536            ConvertOptions::default(),
537        );
538        let input = i16_bytes(&[1, -2, 3, -4, 5, -6]);
539        assert_eq!(convert_all(&mut c, &input, 4, 64), input);
540        assert_eq!(c.delay_frames(), 0);
541    }
542
543    #[test]
544    fn widening_16_to_24_and_32_is_exact_with_zero_filled_low_bits() {
545        let input = i16_bytes(&[0x1234, -2, 0, i16::MAX, i16::MIN, 1]);
546        let mut to24 = converter(
547            fmt(44_100, 1, SampleFormat::I16),
548            fmt(44_100, 1, SampleFormat::I24),
549            ConvertOptions::default(),
550        );
551        let out = convert_all(&mut to24, &input, 100, 100);
552        assert_eq!(&out[..3], &[0x00, 0x34, 0x12]);
553        assert_eq!(&out[3..6], &[0x00, 0xfe, 0xff]);
554        assert_eq!(&out[9..12], &[0x00, 0xff, 0x7f]); // i16::MAX
555        assert_eq!(&out[12..15], &[0x00, 0x00, 0x80]); // i16::MIN
556
557        let mut to32 = converter(
558            fmt(44_100, 1, SampleFormat::I16),
559            fmt(44_100, 1, SampleFormat::I32),
560            ConvertOptions::default(),
561        );
562        let out = convert_all(&mut to32, &input, 100, 100);
563        assert_eq!(&out[..4], &[0x00, 0x00, 0x34, 0x12]);
564        let values: Vec<i32> = out
565            .chunks_exact(4)
566            .map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
567            .collect();
568        let expected: Vec<i32> = [0x1234i16, -2, 0, i16::MAX, i16::MIN, 1]
569            .iter()
570            .map(|v| i32::from(*v) << 16)
571            .collect();
572        assert_eq!(values, expected);
573    }
574
575    #[test]
576    fn packed_24_and_24_in_4_repack_bit_exactly_both_ways() {
577        // Every pattern of a 24-bit sample that matters: walk the 24-bit range in a prime stride.
578        let values: Vec<i32> = (0..50_000i64)
579            .map(|i| (((i * 99_991) % 16_777_216) - 8_388_608) as i32)
580            .collect();
581        let packed: Vec<u8> = values
582            .iter()
583            .flat_map(|v| {
584                [
585                    (*v & 0xff) as u8,
586                    ((*v >> 8) & 0xff) as u8,
587                    ((*v >> 16) & 0xff) as u8,
588                ]
589            })
590            .collect();
591        let mut up = converter(
592            fmt(96_000, 1, SampleFormat::I24),
593            fmt(96_000, 1, SampleFormat::I24_IN_32),
594            ConvertOptions::default(),
595        );
596        let wide = convert_all(&mut up, &packed, 3000, 4000);
597        assert_eq!(wide.len(), values.len() * 4);
598        for (i, v) in values.iter().enumerate() {
599            let word = i32::from_le_bytes([
600                wide[i * 4],
601                wide[i * 4 + 1],
602                wide[i * 4 + 2],
603                wide[i * 4 + 3],
604            ]);
605            assert_eq!(word, v << 8, "sample {i}");
606        }
607        let mut down = converter(
608            fmt(96_000, 1, SampleFormat::I24_IN_32),
609            fmt(96_000, 1, SampleFormat::I24),
610            ConvertOptions::default(),
611        );
612        assert_eq!(convert_all(&mut down, &wide, 4000, 3000), packed);
613    }
614
615    #[test]
616    fn mono_to_stereo_duplicates_every_sample() {
617        let mut c = converter(
618            fmt(48_000, 1, SampleFormat::I16),
619            fmt(48_000, 2, SampleFormat::I16),
620            ConvertOptions::default(),
621        );
622        let out = convert_all(&mut c, &i16_bytes(&[10, -20, 30]), 6, 64);
623        assert_eq!(out, i16_bytes(&[10, 10, -20, -20, 30, 30]));
624        let mut widened = converter(
625            fmt(48_000, 1, SampleFormat::I16),
626            fmt(48_000, 2, SampleFormat::I24),
627            ConvertOptions::default(),
628        );
629        let out = convert_all(&mut widened, &i16_bytes(&[0x0102]), 2, 64);
630        assert_eq!(out, [0x00, 0x02, 0x01, 0x00, 0x02, 0x01]);
631    }
632
633    #[test]
634    fn narrowing_truncates_or_dithers_as_asked() {
635        let input: Vec<u8> = [0x1234_5678i32, -0x0000_ffff, 0x7fff_ffff]
636            .iter()
637            .flat_map(|v| v.to_le_bytes())
638            .collect();
639        let truncate = ConvertOptions {
640            narrowing: Narrowing::Truncate,
641            ..ConvertOptions::default()
642        };
643        let mut c = converter(
644            fmt(44_100, 1, SampleFormat::I32),
645            fmt(44_100, 1, SampleFormat::I16),
646            truncate,
647        );
648        let out = convert_all(&mut c, &input, 100, 100);
649        let values: Vec<i16> = out
650            .chunks_exact(2)
651            .map(|b| i16::from_le_bytes([b[0], b[1]]))
652            .collect();
653        assert_eq!(values, [0x1234, -1, 0x7fff]);
654
655        let mut dithered = converter(
656            fmt(44_100, 1, SampleFormat::I32),
657            fmt(44_100, 1, SampleFormat::I16),
658            ConvertOptions::default(),
659        );
660        let out = convert_all(&mut dithered, &input, 100, 100);
661        let values: Vec<i16> = out
662            .chunks_exact(2)
663            .map(|b| i16::from_le_bytes([b[0], b[1]]))
664            .collect();
665        assert!((i32::from(values[0]) - 0x1234).abs() <= 2);
666        assert!(i32::from(values[1]).abs() <= 2);
667        assert!(i32::from(values[2]) >= 0x7ffe, "{}", values[2]);
668    }
669
670    #[test]
671    fn integers_become_floats_exactly_and_floats_come_back_with_truncation() {
672        let ints: Vec<i16> = (-32768..=32767).step_by(7).map(|v| v as i16).collect();
673        let mut up = converter(
674            fmt(44_100, 1, SampleFormat::I16),
675            fmt(44_100, 1, SampleFormat::Float32),
676            ConvertOptions::default(),
677        );
678        let floats = convert_all(&mut up, &i16_bytes(&ints), 1000, 1000);
679        for (i, v) in ints.iter().enumerate() {
680            let x = f32::from_le_bytes([
681                floats[i * 4],
682                floats[i * 4 + 1],
683                floats[i * 4 + 2],
684                floats[i * 4 + 3],
685            ]);
686            assert_eq!(f64::from(x), f64::from(*v) / 32768.0, "sample {i}");
687        }
688        let truncate = ConvertOptions {
689            narrowing: Narrowing::Truncate,
690            ..ConvertOptions::default()
691        };
692        let mut down = converter(
693            fmt(44_100, 1, SampleFormat::Float32),
694            fmt(44_100, 1, SampleFormat::I16),
695            truncate,
696        );
697        assert_eq!(
698            convert_all(&mut down, &floats, 1000, 1000),
699            i16_bytes(&ints)
700        );
701    }
702
703    #[test]
704    fn a_24_bit_source_survives_a_float_round_trip() {
705        let values: Vec<i32> = (0..20_000i64)
706            .map(|i| (((i * 99_991) % 16_777_216) - 8_388_608) as i32)
707            .collect();
708        let packed: Vec<u8> = values
709            .iter()
710            .flat_map(|v| {
711                [
712                    (*v & 0xff) as u8,
713                    ((*v >> 8) & 0xff) as u8,
714                    ((*v >> 16) & 0xff) as u8,
715                ]
716            })
717            .collect();
718        let truncate = ConvertOptions {
719            narrowing: Narrowing::Truncate,
720            ..ConvertOptions::default()
721        };
722        let mut up = converter(
723            fmt(96_000, 1, SampleFormat::I24),
724            fmt(96_000, 1, SampleFormat::Float32),
725            truncate,
726        );
727        let floats = convert_all(&mut up, &packed, 3000, 4000);
728        let mut down = converter(
729            fmt(96_000, 1, SampleFormat::Float32),
730            fmt(96_000, 1, SampleFormat::I24),
731            truncate,
732        );
733        assert_eq!(
734            convert_all(&mut down, &floats, 4000, 3000),
735            packed,
736            "a float holds 24 bits exactly"
737        );
738    }
739
740    #[test]
741    fn non_finite_floats_are_silence_and_full_scale_saturates_with_a_count() {
742        let input: Vec<u8> = [f32::NAN, f32::INFINITY, 2.0, -2.0, 0.5]
743            .iter()
744            .flat_map(|v| v.to_le_bytes())
745            .collect();
746        let mut c = converter(
747            fmt(44_100, 1, SampleFormat::Float32),
748            fmt(44_100, 1, SampleFormat::I16),
749            ConvertOptions::default(),
750        );
751        let out = convert_all(&mut c, &input, 100, 100);
752        let values: Vec<i16> = out
753            .chunks_exact(2)
754            .map(|b| i16::from_le_bytes([b[0], b[1]]))
755            .collect();
756        assert!(values[0].abs() <= 1 && values[1].abs() <= 1, "{values:?}");
757        assert!(values[2] >= 32766 && values[3] <= -32767, "{values:?}");
758        assert!((i32::from(values[4]) - 16384).abs() <= 1);
759        assert_eq!(c.clipped_samples(), 2);
760        c.reset();
761        assert_eq!(c.clipped_samples(), 0);
762    }
763
764    #[test]
765    fn chunking_and_a_tight_output_buffer_change_nothing() {
766        let input: Vec<u8> = (0..40_000i32)
767            .flat_map(|i| (((i * 37) % 60_000 - 30_000) as i16).to_le_bytes())
768            .collect();
769        for (source, target, mono) in [
770            (
771                fmt(44_100, 2, SampleFormat::I16),
772                fmt(48_000, 2, SampleFormat::I24),
773                false,
774            ),
775            (
776                fmt(44_100, 1, SampleFormat::I16),
777                fmt(48_000, 2, SampleFormat::I16),
778                true,
779            ),
780            (
781                fmt(44_100, 2, SampleFormat::I16),
782                fmt(44_100, 2, SampleFormat::I24_IN_32),
783                false,
784            ),
785        ] {
786            let channels = usize::from(source.channels);
787            let usable = input.len() / (2 * channels) * (2 * channels);
788            let whole = {
789                let mut c = converter(source, target, ConvertOptions::default());
790                convert_all(&mut c, &input[..usable], usable, 1 << 20)
791            };
792            for (chunk, room) in [
793                (2 * channels, 64),
794                (1000 * channels, 3),
795                (4096, 1000),
796                (7 * 2 * channels, 123),
797            ] {
798                let mut c = converter(source, target, ConvertOptions::default());
799                let room = room.max(c.min_output_bytes());
800                let got = convert_all(&mut c, &input[..usable], chunk, room);
801                assert_eq!(
802                    got, whole,
803                    "{source:?} -> {target:?}, chunk {chunk}, room {room}, mono {mono}"
804                );
805            }
806        }
807    }
808
809    #[test]
810    fn a_resampling_converter_produces_the_exact_length_and_reports_its_delay() {
811        let source = fmt(44_100, 2, SampleFormat::I16);
812        let target = fmt(48_000, 2, SampleFormat::I16);
813        let mut c = converter(source, target, ConvertOptions::default());
814        assert!(c.delay_frames() > 0);
815        assert_eq!(
816            c.delay_frames(),
817            80,
818            "158 taps round up to 160: 80 frames held back"
819        );
820        let frames = 10_000usize;
821        let input = vec![0u8; frames * 4];
822        let out = convert_all(&mut c, &input, 4 * 333, 4 * 500);
823        assert_eq!(out.len(), (frames * 160).div_ceil(147) * 4);
824    }
825
826    #[test]
827    fn processing_after_finish_needs_a_reset_and_a_reset_gives_the_same_stream_again() {
828        let source = fmt(48_000, 1, SampleFormat::I16);
829        let target = fmt(44_100, 1, SampleFormat::I16);
830        let input: Vec<u8> = (0..6_000i32)
831            .flat_map(|i| (((i * 91) % 20_000 - 10_000) as i16).to_le_bytes())
832            .collect();
833        let mut c = converter(source, target, ConvertOptions::default());
834        let first = convert_all(&mut c, &input, 1000, 4096);
835        let mut sink = vec![0u8; 64];
836        assert_eq!(
837            c.process(&input, &mut sink).unwrap_err().code(),
838            "invalid_state"
839        );
840        c.reset();
841        let second = convert_all(&mut c, &input, 777, 999);
842        assert_eq!(
843            first, second,
844            "reset restores the filter, the counters and the dither"
845        );
846    }
847
848    #[test]
849    fn output_len_for_matches_what_process_writes() {
850        let mut c = converter(
851            fmt(44_100, 2, SampleFormat::I16),
852            fmt(96_000, 2, SampleFormat::I24),
853            ConvertOptions::default(),
854        );
855        let input = vec![0u8; 4 * 1000];
856        let mut buffer = vec![0u8; 1 << 20];
857        for _ in 0..5 {
858            let predicted = c.output_len_for(input.len());
859            let done = c.process(&input, &mut buffer).unwrap();
860            assert_eq!(done.produced, predicted);
861        }
862    }
863
864    #[test]
865    fn a_resampled_sine_keeps_its_frequency_level_and_stays_clean() {
866        // 1 kHz at -6 dBFS from 44.1 kHz 16-bit to 48 kHz 24-bit.
867        let frames = 44_100usize;
868        let input: Vec<u8> = (0..frames)
869            .flat_map(|n| {
870                let v = (0.5
871                    * (2.0 * std::f64::consts::PI * 1000.0 * n as f64 / 44_100.0).sin()
872                    * 32767.0)
873                    .round() as i16;
874                v.to_le_bytes()
875            })
876            .collect();
877        let mut c = converter(
878            fmt(44_100, 1, SampleFormat::I16),
879            fmt(48_000, 1, SampleFormat::I24),
880            ConvertOptions {
881                headroom_db: 0.0,
882                ..ConvertOptions::default()
883            },
884        );
885        let out = convert_all(&mut c, &input, 4096, 8192);
886        let samples: Vec<f64> = out
887            .chunks_exact(3)
888            .map(|b| f64::from(i32::from_le_bytes([0, b[0], b[1], b[2]]) >> 8) / 8_388_608.0)
889            .collect();
890        assert_eq!(samples.len(), (frames * 160).div_ceil(147));
891        // A whole number of 48-sample periods, so the projections below are orthogonal.
892        let len = (samples.len() - 4000) / 48 * 48;
893        let middle = &samples[2000..2000 + len];
894        let peak = middle.iter().fold(0.0f64, |m, v| m.max(v.abs()));
895        assert!((peak - 0.5).abs() < 0.001, "peak {peak}");
896        // Everything except the sine is below -90 dB (the input's own 16-bit rounding is at about -98 dB).
897        let w = 2.0 * std::f64::consts::PI * 1000.0 / 48_000.0;
898        let (mut a, mut b) = (0.0, 0.0);
899        for (i, y) in middle.iter().enumerate() {
900            a += y * (w * i as f64).sin();
901            b += y * (w * i as f64).cos();
902        }
903        let n = middle.len() as f64;
904        let (a, b) = (2.0 * a / n, 2.0 * b / n);
905        let residual = middle
906            .iter()
907            .enumerate()
908            .map(|(i, y)| y - (a * (w * i as f64).sin() + b * (w * i as f64).cos()))
909            .map(|e| e * e)
910            .sum::<f64>()
911            / n;
912        let noise_db = 10.0 * (residual / (0.5f64 * 0.5 / 2.0)).log10();
913        assert!(noise_db < -90.0, "noise at {noise_db} dB");
914    }
915
916    #[test]
917    fn a_full_scale_square_wave_overshoots_and_saturates_without_wrapping_and_headroom_prevents_it()
918    {
919        let frames = 20_000usize;
920        let input: Vec<u8> = (0..frames)
921            .flat_map(|n| {
922                let v: i16 = if (n / 22) % 2 == 0 {
923                    i16::MAX
924                } else {
925                    i16::MIN
926                };
927                v.to_le_bytes()
928            })
929            .collect();
930        let source = fmt(44_100, 1, SampleFormat::I16);
931        let target = fmt(48_000, 1, SampleFormat::I16);
932
933        let mut plain = converter(
934            source,
935            target,
936            ConvertOptions {
937                headroom_db: 0.0,
938                ..ConvertOptions::default()
939            },
940        );
941        let out = convert_all(&mut plain, &input, 4096, 8192);
942        let values: Vec<i16> = out
943            .chunks_exact(2)
944            .map(|b| i16::from_le_bytes([b[0], b[1]]))
945            .collect();
946        assert!(
947            plain.clipped_samples() > 0,
948            "the Gibbs overshoot of a full-scale square wave exceeds full scale"
949        );
950        // The same signal as floats is never saturated, so it shows what the integers should be:
951        // the float value rounded, and held at the rails where it goes past them. A wrap would
952        // put a sample on the other side of zero.
953        let mut reference = converter(
954            source,
955            fmt(48_000, 1, SampleFormat::Float32),
956            ConvertOptions {
957                headroom_db: 0.0,
958                ..ConvertOptions::default()
959            },
960        );
961        let floats = convert_all(&mut reference, &input, 4096, 8192);
962        assert_eq!(floats.len() / 4, values.len());
963        let mut beyond = 0;
964        for (i, (value, float)) in values.iter().zip(floats.chunks_exact(4)).enumerate() {
965            let x = f64::from(f32::from_le_bytes([float[0], float[1], float[2], float[3]]));
966            if x > 1.0 {
967                beyond += 1;
968            }
969            let expected = (x * 32768.0).round().clamp(-32768.0, 32767.0);
970            assert!(
971                (f64::from(*value) - expected).abs() <= 2.0,
972                "sample {i}: {value} for a float of {x}"
973            );
974        }
975        assert!(beyond > 0, "the float conversion shows the overshoot");
976
977        let overshoot = floats
978            .chunks_exact(4)
979            .map(|b| f64::from(f32::from_le_bytes([b[0], b[1], b[2], b[3]])).abs())
980            .fold(0.0f64, f64::max);
981        println!(
982            "full-scale square wave, 44.1 -> 48 kHz: peak {overshoot:.4} = {:+.2} dB",
983            20.0 * overshoot.log10()
984        );
985        assert!(overshoot > 1.2 && overshoot < 1.6, "{overshoot}");
986
987        let mut default_guard = converter(source, target, ConvertOptions::default());
988        convert_all(&mut default_guard, &input, 4096, 8192);
989        assert_eq!(default_guard.clipped_samples(), 0);
990        let headroom = ConvertOptions {
991            headroom_db: -3.5,
992            ..ConvertOptions::default()
993        };
994        let mut guarded = converter(source, target, headroom);
995        convert_all(&mut guarded, &input, 4096, 8192);
996        assert_eq!(
997            guarded.clipped_samples(),
998            0,
999            "3.5 dB of headroom covers the overshoot"
1000        );
1001    }
1002
1003    #[test]
1004    fn a_full_scale_sine_is_not_clipped_with_a_float_or_a_truncating_16_bit_target() {
1005        // Within the passband the filter's ripple is about 3e-6, less than one 16-bit step at full scale.
1006        for hz in [100.0, 1_000.0, 10_000.0, 19_000.0] {
1007            // The tone fades in and out over 2000 frames: a tone cut off abruptly would ring at the cut.
1008            let tone = |scale: f64| -> Vec<f64> {
1009                (0..20_000)
1010                    .map(|n| {
1011                        let edge = n.min(19_999 - n).min(2_000) as f64 / 2_000.0;
1012                        let fade = 0.5 - 0.5 * (std::f64::consts::PI * edge).cos();
1013                        scale
1014                            * fade
1015                            * (2.0 * std::f64::consts::PI * hz * f64::from(n) / 44_100.0).sin()
1016                    })
1017                    .collect()
1018            };
1019            // A float target, at amplitude 1.0.
1020            let input: Vec<u8> = tone(1.0)
1021                .iter()
1022                .flat_map(|v| (*v as f32).to_le_bytes())
1023                .collect();
1024            let mut c = converter(
1025                fmt(44_100, 1, SampleFormat::Float32),
1026                fmt(96_000, 1, SampleFormat::Float32),
1027                ConvertOptions {
1028                    headroom_db: 0.0,
1029                    ..ConvertOptions::default()
1030                },
1031            );
1032            let out = convert_all(&mut c, &input, 4096, 8192);
1033            let settled = &out[4 * 1000..out.len() - 4 * 1000];
1034            let peak = settled
1035                .chunks_exact(4)
1036                .map(|b| f64::from(f32::from_le_bytes([b[0], b[1], b[2], b[3]])).abs())
1037                .fold(0.0f64, f64::max);
1038            assert!(peak <= 1.00001, "{hz} Hz overshoots to {peak}");
1039            assert!(peak >= 0.9999, "{hz} Hz is down to {peak}");
1040
1041            // A 16-bit source at its largest sine, 32767 / 32768, to a 16-bit target.
1042            let ints: Vec<u8> = tone(32767.0 / 32768.0)
1043                .iter()
1044                .flat_map(|v| ((v * 32768.0).round() as i16).to_le_bytes())
1045                .collect();
1046            let truncate = ConvertOptions {
1047                narrowing: Narrowing::Truncate,
1048                ..ConvertOptions {
1049                    headroom_db: 0.0,
1050                    ..ConvertOptions::default()
1051                }
1052            };
1053            let mut c = converter(
1054                fmt(44_100, 1, SampleFormat::I16),
1055                fmt(96_000, 1, SampleFormat::I16),
1056                truncate,
1057            );
1058            convert_all(&mut c, &ints, 4096, 8192);
1059            assert_eq!(c.clipped_samples(), 0, "{hz} Hz clipped");
1060        }
1061    }
1062
1063    #[test]
1064    fn the_fast_preset_is_cheaper() {
1065        let plan = |quality| {
1066            converter(
1067                fmt(48_000, 2, SampleFormat::I16),
1068                fmt(44_100, 2, SampleFormat::I16),
1069                ConvertOptions {
1070                    quality,
1071                    ..ConvertOptions::default()
1072                },
1073            )
1074        };
1075        assert!(plan(Quality::Fast).delay_frames() * 2 < plan(Quality::High).delay_frames());
1076    }
1077}