usbdac-core 0.1.20

Direct USB DAC playback for Rust audio applications on Android and Linux, with PCM, DoP, native DSD and bit-perfect reporting.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! Streaming native DSD to PCM. Input is chronological channel-interleaved
//! bytes with the oldest bit in bit 7, as accepted by `DacStream::write`.
//! This converter is always lossy; DoP carrier words are not accepted.
//!
//! A 704-tap Kaiser-windowed low-pass decimates the one-bit stream by 16,
//! followed by the library's high-quality rational PCM resampler. The first
//! stage is evaluated with byte lookup tables, so no processing allocation is
//! required. Input rates are DSD64, DSD128, DSD256 and DSD512 in the
//! 44.1 kHz and 48 kHz families.
use crate::convert::{
    ConversionPlan, ConvertError, ConvertOptions, Converter, PcmFormat, Processed, SampleFormat,
};

const TAPS: usize = 704;
const HISTORY: usize = TAPS / 8;
const DELAY: usize = TAPS / 32;
const DSD_PCM_BATCH_FRAMES: usize = 128;

pub struct DsdPcmConverter {
    channels: usize,
    table: Vec<[f64; 256]>,
    history: Vec<[u8; HISTORY]>,
    head: usize,
    first: Option<[u8; 8]>,
    skipped: usize,
    pending: Vec<u8>,
    pending_offset: usize,
    pcm: Converter,
    finishing: bool,
    tail_left: usize,
    final_partial: bool,
    input_frames: u64,
    output_frames: u64,
    input_rate: u32,
    output_rate: u32,
    output_frame_bytes: usize,
    tail_scratch: Vec<u8>,
    tail_read: usize,
    tail_valid: usize,
    first_stage_gain: f64,
}

impl DsdPcmConverter {
    pub fn new(bit_rate: u32, channels: u16, target: PcmFormat) -> Result<Self, ConvertError> {
        Self::with_options(bit_rate, channels, target, &ConvertOptions::default())
    }
    pub fn with_options(
        bit_rate: u32,
        channels: u16,
        target: PcmFormat,
        options: &ConvertOptions,
    ) -> Result<Self, ConvertError> {
        if options.source_sample.is_some() {
            return Err(ConvertError::InvalidArgument(
                "PCM source layout is not valid for native DSD".into(),
            ));
        }
        if !matches!(
            bit_rate,
            2_822_400
                | 3_072_000
                | 5_644_800
                | 6_144_000
                | 11_289_600
                | 12_288_000
                | 22_579_200
                | 24_576_000
        ) || !(1..=8).contains(&channels)
        {
            return Err(ConvertError::Unsupported(
                "native DSD supports DSD64/128/256/512 in the 44.1 and 48 kHz families and 1 to 8 channels".into(),
            ));
        }
        let source = PcmFormat::new(bit_rate / 16, channels, SampleFormat::Float32);
        let plan = ConversionPlan::pcm(source, target, options)?;
        let first_stage_gain = if plan.resamples() {
            1.0
        } else {
            10f64.powf(options.headroom_db / 20.0)
        };
        let pcm = Converter::new(&plan)?;
        let tail_scratch = vec![0; pcm.min_output_bytes()];
        let mut coefficients = [0.0; TAPS];
        // Transition band is 0.020..0.03125 cycles/bit (the decimated Nyquist).
        let cutoff = (0.020 + 0.03125) / 2.0;
        let beta = crate::convert::resample::kaiser_beta(120.0);
        let denominator = crate::convert::resample::bessel_i0(beta);
        let mut sum = 0.0;
        for (i, c) in coefficients.iter_mut().enumerate() {
            let x = i as f64 - (TAPS as f64 - 1.0) / 2.0;
            let sinc = (2.0 * std::f64::consts::PI * cutoff * x).sin() / (std::f64::consts::PI * x);
            let position = 2.0 * i as f64 / (TAPS - 1) as f64 - 1.0;
            let window = crate::convert::resample::bessel_i0(
                beta * (1.0 - position * position).max(0.0).sqrt(),
            ) / denominator;
            *c = sinc * window;
            sum += *c;
        }
        for c in &mut coefficients {
            *c /= sum;
        }
        let mut table = vec![[0.0; 256]; HISTORY];
        for (group, entries) in table.iter_mut().enumerate() {
            for (byte, entry) in entries.iter_mut().enumerate() {
                *entry = (0..8)
                    .map(|bit| {
                        coefficients[group * 8 + bit]
                            * if byte & (1 << bit) != 0 { 1.0 } else { -1.0 }
                    })
                    .sum();
            }
        }
        Ok(Self {
            channels: channels as usize,
            table,
            history: vec![[0x69; HISTORY]; channels as usize],
            head: 0,
            first: None,
            skipped: 0,
            pending: Vec::with_capacity(channels as usize * 4 * DSD_PCM_BATCH_FRAMES),
            pending_offset: 0,
            pcm,
            finishing: false,
            tail_left: DELAY,
            final_partial: false,
            input_frames: 0,
            output_frames: 0,
            input_rate: bit_rate / 8,
            output_rate: target.sample_rate,
            output_frame_bytes: target.bytes_per_frame(),
            tail_scratch,
            tail_read: 0,
            tail_valid: 0,
            first_stage_gain,
        })
    }
    pub fn min_output_bytes(&self) -> usize {
        self.pcm.min_output_bytes()
    }
    pub fn kind(&self) -> crate::convert::ConversionKind {
        crate::convert::ConversionKind::Lossy
    }
    pub fn clipped_samples(&self) -> u64 {
        self.pcm.clipped_samples()
    }
    pub fn delay_byte_frames(&self) -> usize {
        2 * DELAY + self.pcm.delay_frames() * 2
    }
    fn push_frame(&mut self, frame: &[u8]) {
        self.head = (self.head + 1) % HISTORY;
        for (ch, byte) in frame.iter().enumerate().take(self.channels) {
            self.history[ch][self.head] = *byte;
        }
    }
    fn synthesize(&mut self) {
        if self.skipped < DELAY {
            self.skipped += 1;
            return;
        }
        for channel in &self.history {
            // Preserve the original newest-to-oldest summation order without
            // a modulo operation for each filter table lookup.
            let (older, newer) = channel.split_at(self.head + 1);
            let sample: f64 = older
                .iter()
                .rev()
                .chain(newer.iter().rev())
                .enumerate()
                .map(|(i, byte)| self.table[i][usize::from(*byte)])
                .sum();
            self.pending
                .extend_from_slice(&((sample * self.first_stage_gain) as f32).to_le_bytes());
        }
    }
    fn emit_pending(&mut self, output: &mut [u8]) -> Result<Processed, ConvertError> {
        if self.pending.is_empty() {
            return Ok(Processed {
                consumed: 0,
                produced: 0,
            });
        }
        let done = self
            .pcm
            .process(&self.pending[self.pending_offset..], output)?;
        self.pending_offset += done.consumed;
        if self.pending_offset == self.pending.len() {
            self.pending.clear();
            self.pending_offset = 0;
        }
        Ok(done)
    }
    pub fn process(&mut self, input: &[u8], output: &mut [u8]) -> Result<Processed, ConvertError> {
        if self.finishing {
            return Err(ConvertError::InvalidState(
                "finish called; reset before processing".into(),
            ));
        }
        let mut consumed = 0;
        let mut produced = 0;
        let batch_bytes = self.channels * 4 * DSD_PCM_BATCH_FRAMES;
        loop {
            let no_more_input = input.len() - consumed < self.channels;
            if !self.pending.is_empty()
                && (self.pending_offset > 0 || self.pending.len() >= batch_bytes || no_more_input)
            {
                let done = self.emit_pending(&mut output[produced..])?;
                produced += done.produced;
                if !self.pending.is_empty() {
                    break;
                }
                continue;
            }
            if no_more_input || output.len() - produced < self.min_output_bytes() {
                break;
            }
            let frame = &input[consumed..consumed + self.channels];
            self.push_frame(frame);
            consumed += self.channels;
            if self.first.take().is_some() {
                self.synthesize();
            } else {
                self.first = Some([0; 8]);
            }
        }
        self.input_frames = self
            .input_frames
            .saturating_add((consumed / self.channels) as u64);
        self.output_frames = self
            .output_frames
            .saturating_add((produced / self.output_frame_bytes) as u64);
        Ok(Processed { consumed, produced })
    }
    pub fn finish(&mut self, output: &mut [u8]) -> Result<usize, ConvertError> {
        self.finishing = true;
        let expected = (u128::from(self.input_frames) * u128::from(self.output_rate))
            .div_ceil(u128::from(self.input_rate));
        let remaining = expected.saturating_sub(u128::from(self.output_frames));
        let cap = (remaining
            .saturating_mul(self.output_frame_bytes as u128)
            .min(output.len() as u128) as usize
            / self.output_frame_bytes)
            * self.output_frame_bytes;
        if cap == 0 {
            return Ok(0);
        }
        let mut made = 0;
        while made < cap {
            if self.tail_read == self.tail_valid {
                self.tail_read = 0;
                self.tail_valid = 0;
                let mut scratch = std::mem::take(&mut self.tail_scratch);
                let result = self.finish_inner(&mut scratch);
                self.tail_scratch = scratch;
                let generated = result?;
                // Discard synthesis padding beyond the exact source duration.
                let legitimate = (remaining * self.output_frame_bytes as u128)
                    .saturating_sub(made as u128)
                    .min(usize::MAX as u128) as usize;
                self.tail_valid = generated.min(legitimate);
                if self.tail_valid == 0 {
                    break;
                }
            }
            let copied = (self.tail_valid - self.tail_read).min(cap - made);
            output[made..made + copied]
                .copy_from_slice(&self.tail_scratch[self.tail_read..self.tail_read + copied]);
            self.tail_read += copied;
            made += copied;
        }
        self.output_frames = self
            .output_frames
            .saturating_add((made / self.output_frame_bytes) as u64);
        Ok(made)
    }
    fn finish_inner(&mut self, output: &mut [u8]) -> Result<usize, ConvertError> {
        let mut produced = 0;
        loop {
            if !self.pending.is_empty() {
                let done = self.emit_pending(&mut output[produced..])?;
                produced += done.produced;
                if !self.pending.is_empty() {
                    return Ok(produced);
                }
            }
            if output.len() - produced < self.min_output_bytes() {
                return Ok(produced);
            }
            if self.first.take().is_some() && !self.final_partial {
                self.push_frame(&[0x69; 8][..self.channels]);
                self.synthesize();
                self.final_partial = true;
                continue;
            }
            if self.tail_left > 0 {
                self.push_frame(&[0x69; 8][..self.channels]);
                self.push_frame(&[0x69; 8][..self.channels]);
                self.synthesize();
                self.tail_left -= 1;
                continue;
            }
            produced += self.pcm.finish(&mut output[produced..])?;
            return Ok(produced);
        }
    }
    pub fn reset(&mut self) {
        for h in &mut self.history {
            h.fill(0x69);
        }
        self.head = 0;
        self.first = None;
        self.skipped = 0;
        self.pending.clear();
        self.pending_offset = 0;
        self.pcm.reset();
        self.finishing = false;
        self.tail_left = DELAY;
        self.final_partial = false;
        self.input_frames = 0;
        self.output_frames = 0;
        self.tail_read = 0;
        self.tail_valid = 0;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    fn converter() -> DsdPcmConverter {
        DsdPcmConverter::new(
            2_822_400,
            2,
            PcmFormat::new(44_100, 2, SampleFormat::Float32),
        )
        .unwrap()
    }
    // Reference for the original one-intermediate-frame-at-a-time pump.
    fn legacy_process(
        c: &mut DsdPcmConverter,
        input: &[u8],
        output: &mut [u8],
    ) -> Result<Processed, ConvertError> {
        let mut consumed = 0;
        let mut produced = 0;
        loop {
            if !c.pending.is_empty() {
                let done = c.emit_pending(&mut output[produced..])?;
                produced += done.produced;
                if !c.pending.is_empty() {
                    break;
                }
            }
            if input.len() - consumed < c.channels || output.len() - produced < c.min_output_bytes()
            {
                break;
            }
            c.push_frame(&input[consumed..consumed + c.channels]);
            consumed += c.channels;
            if c.first.take().is_some() {
                c.synthesize();
            } else {
                c.first = Some([0; 8]);
            }
        }
        c.input_frames += (consumed / c.channels) as u64;
        c.output_frames += (produced / c.output_frame_bytes) as u64;
        Ok(Processed { consumed, produced })
    }
    fn run_dsd512_pump(
        bit_rate: u32,
        input_frames: usize,
        chunk_frames: usize,
        output_frames: usize,
        legacy: bool,
    ) -> (Vec<u8>, u64) {
        let target = PcmFormat::new(48_000, 2, SampleFormat::I24);
        let mut converter = DsdPcmConverter::new(bit_rate, 2, target).unwrap();
        let input: Vec<u8> = (0..input_frames * 2)
            .map(|i| ((i.wrapping_mul(73) ^ (i >> 4) ^ 0x69) & 255) as u8)
            .collect();
        let mut output = vec![0; output_frames * target.bytes_per_frame()];
        assert!(output.len() >= converter.min_output_bytes());
        let mut decoded = Vec::new();
        let mut position = 0;
        while position < input.len() {
            let end = (position + chunk_frames * 2).min(input.len());
            let done = if legacy {
                legacy_process(&mut converter, &input[position..end], &mut output)
            } else {
                converter.process(&input[position..end], &mut output)
            }
            .unwrap();
            assert!(done.consumed > 0 || done.produced > 0);
            position += done.consumed;
            decoded.extend_from_slice(&output[..done.produced]);
        }
        loop {
            let count = converter.finish(&mut output).unwrap();
            if count == 0 {
                break;
            }
            decoded.extend_from_slice(&output[..count]);
        }
        let clipped = converter.clipped_samples();
        converter.reset();
        assert!(converter.process(&[0x69, 0x69], &mut output).is_ok());
        (decoded, clipped)
    }
    #[test]
    fn dsd512_batched_pump_matches_single_frame_reference_with_backpressure() {
        for bit_rate in [22_579_200, 24_576_000] {
            let reference = run_dsd512_pump(bit_rate, 24_000, 256, 256, true);
            assert_eq!(
                run_dsd512_pump(bit_rate, 24_000, 256, 256, false),
                reference
            );
            assert_eq!(run_dsd512_pump(bit_rate, 24_000, 37, 1, false), reference);
            let expected_frames = (24_000u64 * 48_000).div_ceil(u64::from(bit_rate / 8));
            assert_eq!(reference.0.len(), expected_frames as usize * 6);
        }
    }
    #[test]
    fn filter_rejects_decimation_aliases_and_preserves_passband() {
        let c = converter();
        let response = |f: f64| {
            let mut re = 0.0;
            let mut im = 0.0;
            for (j, table) in c.table.iter().enumerate() {
                for bit in 0..8 {
                    let coeff = (table[1 << bit] - table[0]) / 2.0;
                    let angle = 2.0 * std::f64::consts::PI * f * (j * 8 + bit) as f64;
                    re += coeff * angle.cos();
                    im -= coeff * angle.sin();
                }
            }
            re.hypot(im)
        };
        let mut ripple = 0.0f64;
        for i in 0..=512 {
            let f = 0.020 * i as f64 / 512.0;
            ripple = ripple.max((response(f) - 1.0).abs());
        }
        let mut stop = 0.0f64;
        for i in 0..=8192 {
            let f = 0.03125 + i as f64 * (0.5 - 0.03125) / 8192.0;
            stop = stop.max(response(f));
        }
        println!(
            "production taps: ripple {ripple:e}, stop {:.3} dB",
            20.0 * stop.log10()
        );
        assert!(ripple < 0.00001, "ripple {ripple}");
        assert!(stop < 0.000002, "stop {stop}");
    }
    fn run(chunks: usize) -> Vec<u8> {
        let mut c = converter();
        let input: Vec<u8> = (0..8192)
            .map(|i| if i % 2 == 0 { 0x69 } else { 0x96 })
            .collect();
        let mut result = Vec::new();
        let mut offset = 0;
        while offset < input.len() {
            let end = (offset + chunks).min(input.len());
            let mut out = [0u8; 512];
            let done = c.process(&input[offset..end], &mut out).unwrap();
            assert!(done.consumed > 0 || done.produced > 0);
            offset += done.consumed;
            result.extend_from_slice(&out[..done.produced]);
        }
        loop {
            let mut out = [0u8; 512];
            let n = c.finish(&mut out).unwrap();
            result.extend_from_slice(&out[..n]);
            if n == 0 {
                break;
            }
        }
        assert_eq!(c.kind(), crate::convert::ConversionKind::Lossy);
        result
    }
    #[test]
    fn streaming_chunks_and_eos_preserve_phase_and_length() {
        let a = run(8192);
        let b = run(18);
        assert_eq!(a, b);
        assert_eq!(a, run(3));
        assert_eq!(a.len(), 512 * 8); // 4096 input byte-frames, DSD64 -> 44.1 kHz
    }
    #[test]
    fn rejects_unsupported_rates_and_recovers_after_reset() {
        assert!(DsdPcmConverter::new(
            25_000_000,
            2,
            PcmFormat::new(44_100, 2, SampleFormat::Float32)
        )
        .is_err());
        let mut c = converter();
        let mut out = [0u8; 128];
        let _ = c.finish(&mut out).unwrap();
        assert!(c.process(&[0x69, 0x69], &mut out).is_err());
        c.reset();
        assert!(c.process(&[0x69, 0x69], &mut out).is_ok());
    }
    #[test]
    fn channel_histories_are_independent_and_msb_is_oldest() {
        let mut c = converter();
        for _ in 0..HISTORY {
            c.push_frame(&[0xff, 0x00]);
        }
        c.skipped = DELAY;
        c.synthesize();
        let left = f32::from_le_bytes(c.pending[0..4].try_into().unwrap());
        let right = f32::from_le_bytes(c.pending[4..8].try_into().unwrap());
        assert!((left - 1.0).abs() < 1e-6 && (right + 1.0).abs() < 1e-6);
        // Within each chronological byte, bit 0 is newest and multiplies tap 0.
        let weight_newest = (c.table[0][1] - c.table[0][0]) / 2.0;
        let weight_oldest = (c.table[0][128] - c.table[0][0]) / 2.0;
        assert!((weight_newest - weight_oldest).abs() > 1e-9);
    }
    #[test]
    fn odd_end_and_upsampling_return_exact_source_duration() {
        for target in [48_000u32, 192_000] {
            let mut c = DsdPcmConverter::new(
                2_822_400,
                1,
                PcmFormat::new(target, 1, SampleFormat::Float32),
            )
            .unwrap();
            let input = [0x69; 137];
            let mut out = [0u8; 4096];
            let done = c.process(&input, &mut out).unwrap();
            assert_eq!(done.consumed, input.len());
            let mut produced = done.produced;
            loop {
                let n = c.finish(&mut out).unwrap();
                produced += n;
                if n == 0 {
                    break;
                }
            }
            let expected = (137u64 * u64::from(target)).div_ceil(2_822_400 / 8) as usize;
            assert_eq!(produced, expected * 4, "target {target}");
        }
    }
    #[test]
    fn finish_preserves_tail_with_small_unaligned_buffers() {
        for rate in [192_000, 352_800] {
            for sample in [SampleFormat::Float32, SampleFormat::int(16, 2).unwrap()] {
                let frame = PcmFormat::new(rate, 1, sample).bytes_per_frame();
                let render = |capacity: usize| {
                    let mut c = DsdPcmConverter::new(2_822_400, 1, PcmFormat::new(rate, 1, sample))
                        .unwrap();
                    let mut result = Vec::new();
                    let input = [0x69; 137];
                    let mut out = vec![0; 8192];
                    let done = c.process(&input, &mut out).unwrap();
                    assert_eq!(done.consumed, input.len());
                    result.extend_from_slice(&out[..done.produced]);
                    assert_eq!(c.finish(&mut out[..frame - 1]).unwrap(), 0);
                    loop {
                        let n = c.finish(&mut out[..capacity]).unwrap();
                        assert_eq!(n % frame, 0);
                        result.extend_from_slice(&out[..n]);
                        if n == 0 {
                            break;
                        }
                    }
                    assert_eq!(c.finish(&mut out[..capacity]).unwrap(), 0);
                    assert_eq!(
                        result.len(),
                        (137u64 * rate as u64).div_ceil(352_800) as usize * frame
                    );
                    result
                };
                let reference = render(8192);
                assert_eq!(reference, render(frame));
                assert_eq!(reference, render(frame * 3 + 1));
            }
        }
    }
    #[test]
    fn full_chain_preserves_audio_tone_and_suppresses_out_of_band_tone() {
        fn level(freq: f64, measured_freq: f64) -> f64 {
            let mut bits = Vec::new();
            let mut acc = 0.0;
            let mut byte = 0u8;
            for n in 0..131_072 {
                let signal =
                    0.5 * (2.0 * std::f64::consts::PI * freq * n as f64 / 2_822_400.0).sin();
                acc += signal;
                let high = acc >= 0.0;
                acc -= if high { 1.0 } else { -1.0 };
                byte = (byte << 1) | u8::from(high);
                if n % 8 == 7 {
                    bits.push(byte);
                    byte = 0;
                }
            }
            let options = ConvertOptions {
                headroom_db: 0.0,
                ..ConvertOptions::default()
            };
            let mut c = DsdPcmConverter::with_options(
                2_822_400,
                1,
                PcmFormat::new(44_100, 1, SampleFormat::Float32),
                &options,
            )
            .unwrap();
            let mut audio = Vec::new();
            let mut i = 0;
            let mut out = [0u8; 4096];
            while i < bits.len() {
                let done = c.process(&bits[i..], &mut out).unwrap();
                assert!(done.consumed > 0 || done.produced > 0);
                i += done.consumed;
                audio.extend_from_slice(&out[..done.produced]);
            }
            loop {
                let n = c.finish(&mut out).unwrap();
                audio.extend_from_slice(&out[..n]);
                if n == 0 {
                    break;
                }
            }
            let samples: Vec<f64> = audio
                .chunks_exact(4)
                .map(|x| f32::from_le_bytes(x.try_into().unwrap()) as f64)
                .collect();
            let mut re = 0.0;
            let mut im = 0.0;
            let body = &samples[128..samples.len() - 128];
            for (n, value) in body.iter().enumerate() {
                let phase = 2.0 * std::f64::consts::PI * measured_freq * n as f64 / 44_100.0;
                re += value * phase.cos();
                im += value * phase.sin();
            }
            2.0 * re.hypot(im) / body.len() as f64
        }
        let in_band = level(1_378.125, 1_378.125);
        let alias = level(30_000.0, 14_100.0);
        assert!(
            (0.47..0.53).contains(&in_band),
            "in-band amplitude {in_band}"
        );
        assert!(alias < 0.002, "aliased amplitude {alias}");
    }
    #[test]
    fn production_chain_preserves_half_modulation_across_rates_and_qualities() {
        for source in [2_822_400, 5_644_800, 11_289_600] {
            for target in [44_100, source / 16, 768_000] {
                for quality in [crate::convert::Quality::High, crate::convert::Quality::Fast] {
                    let options = ConvertOptions {
                        quality,
                        headroom_db: 0.0,
                        ..ConvertOptions::default()
                    };
                    let mut c = DsdPcmConverter::with_options(
                        source,
                        1,
                        PcmFormat::new(target, 1, SampleFormat::Float32),
                        &options,
                    )
                    .unwrap();
                    let input = [0xee; 8192]; // 75% ones: +0.5 modulation
                    let mut out = vec![0u8; 512 * 1024];
                    let done = c.process(&input, &mut out).unwrap();
                    assert_eq!(done.consumed, input.len());
                    let mut n = done.produced;
                    loop {
                        let produced = c.finish(&mut out[n..]).unwrap();
                        n += produced;
                        if produced == 0 {
                            break;
                        }
                    }
                    assert_eq!(
                        n / 4,
                        (input.len() as u64 * target as u64).div_ceil(source as u64 / 8) as usize
                    );
                    let middle = (n / 4) / 2;
                    let value =
                        f32::from_le_bytes(out[middle * 4..middle * 4 + 4].try_into().unwrap());
                    assert!(
                        (value - 0.5).abs() < 0.0001,
                        "{source} {target} {quality:?}: {value}"
                    );
                }
            }
        }
    }

    #[test]
    fn headroom_is_applied_once_with_and_without_pcm_resampling() {
        fn amplitude(rate: u32, db: f64) -> f64 {
            let options = ConvertOptions {
                headroom_db: db,
                ..ConvertOptions::default()
            };
            let mut c = DsdPcmConverter::with_options(
                2_822_400,
                1,
                PcmFormat::new(rate, 1, SampleFormat::Float32),
                &options,
            )
            .unwrap();
            let input = [0xff; 8192];
            let mut out = vec![0; 128 * 1024];
            let done = c.process(&input, &mut out).unwrap();
            assert_eq!(done.consumed, input.len());
            let samples: Vec<f32> = out[..done.produced]
                .chunks_exact(4)
                .map(|b| f32::from_le_bytes(b.try_into().unwrap()))
                .collect();
            samples[samples.len() / 2] as f64
        }
        let gain = 10f64.powf(-6.0 / 20.0);
        for rate in [44_100, 176_400] {
            let unity = amplitude(rate, 0.0);
            let reduced = amplitude(rate, -6.0);
            assert!(
                (reduced / unity - gain).abs() < 0.001,
                "rate {rate}: {}",
                reduced / unity
            );
        }
        let options = ConvertOptions {
            source_sample: Some(SampleFormat::I16),
            ..ConvertOptions::default()
        };
        assert!(DsdPcmConverter::with_options(
            2_822_400,
            1,
            PcmFormat::new(44_100, 1, SampleFormat::Float32),
            &options
        )
        .is_err());
    }
}