1use super::format::{ConvertError, Narrowing, PcmFormat, SampleFormat};
13use super::plan::{ConversionPlan, Step};
14use super::resample::Resampler;
15use super::samples::{self, Rng};
16
17pub const BLOCK_FRAMES: usize = 1024;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22pub struct Processed {
23 pub consumed: usize,
25 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 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 #[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 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 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 Copy {
231 frame_bytes: usize,
232 },
233 Integer(IntegerEngine),
234 Float(Box<FloatEngine>),
235}
236
237pub 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 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 pub fn source_frame_bytes(&self) -> usize {
356 self.source_frame
357 }
358
359 pub fn target_frame_bytes(&self) -> usize {
361 self.target_frame
362 }
363
364 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 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 pub fn clipped_samples(&self) -> u64 {
391 self.clipped
392 }
393
394 pub fn process(&mut self, input: &[u8], output: &mut [u8]) -> Result<Processed, ConvertError> {
397 if matches!(&self.engine, Engine::Float(engine) if engine.finishing) {
398 return Err(ConvertError::InvalidState(
399 "finish() was called: reset() before converting more".into(),
400 ));
401 }
402 let input_frames = input.len() / self.source_frame;
403 let output_frames = output.len() / self.target_frame;
404 let capacity = match &self.engine {
405 Engine::Float(engine) => engine
406 .resampler
407 .as_ref()
408 .map_or(output_frames, |r| r.max_input_for_output(output_frames)),
409 _ => output_frames,
410 };
411 let input = &input[..input_frames.min(capacity) * self.source_frame];
412 if let SampleFormat::Int { bits, slot_bytes } = self.plan.source().sample {
413 let padding = u32::from(slot_bytes) * 8 - u32::from(bits);
414 if padding > 0 {
415 let slot = usize::from(slot_bytes);
416 let whole = input.len() / self.source_frame * self.source_frame;
417 let mask = (1u32 << padding) - 1;
418 for sample in input[..whole].chunks_exact(slot) {
419 let mut word = 0u32;
420 for (i, byte) in sample.iter().enumerate() {
421 word |= u32::from(*byte) << (i * 8);
422 }
423 if word & mask != 0 {
424 return Err(ConvertError::InvalidArgument(
425 "source integer sample has nonzero declared padding bits".into(),
426 ));
427 }
428 }
429 }
430 }
431 let (consumed, produced) = match &mut self.engine {
432 Engine::Copy { frame_bytes } => {
433 let frames = (input.len() / *frame_bytes).min(output.len() / *frame_bytes);
434 let bytes = frames * *frame_bytes;
435 output[..bytes].copy_from_slice(&input[..bytes]);
436 (bytes, bytes)
437 }
438 Engine::Integer(engine) => engine.process(input, output, &mut self.clipped),
439 Engine::Float(engine) => {
440 if engine.finishing {
441 return Err(ConvertError::InvalidState(
442 "finish() was called: reset() before converting more".into(),
443 ));
444 }
445 engine.process(input, output, &mut self.clipped)
446 }
447 };
448 Ok(Processed { consumed, produced })
449 }
450
451 pub fn finish(&mut self, output: &mut [u8]) -> Result<usize, ConvertError> {
455 Ok(match &mut self.engine {
456 Engine::Float(engine) => engine.finish(output, &mut self.clipped),
457 _ => 0,
458 })
459 }
460
461 pub fn reset(&mut self) {
463 match &mut self.engine {
464 Engine::Float(engine) => {
465 engine.reset();
466 engine.rng = Rng::new(self.plan.options().dither_seed);
467 }
468 Engine::Integer(engine) => engine.rng = Rng::new(self.plan.options().dither_seed),
469 Engine::Copy { .. } => {}
470 }
471 self.clipped = 0;
472 }
473
474 pub fn output_len_for(&self, input_bytes: usize) -> usize {
478 let frames = input_bytes / self.source_frame;
479 let out_frames = match &self.engine {
480 Engine::Float(engine) => match &engine.resampler {
481 Some(resampler) => resampler.output_len_for(frames),
482 None => frames,
483 },
484 _ => frames,
485 };
486 out_frames * self.target_frame
487 }
488}
489
490#[cfg(test)]
491mod tests {
492 use super::*;
493 use crate::convert::format::{ConvertOptions, Quality};
494
495 fn converter(source: PcmFormat, target: PcmFormat, options: ConvertOptions) -> Converter {
496 Converter::new(&ConversionPlan::pcm(source, target, &options).unwrap()).unwrap()
497 }
498
499 fn fmt(rate: u32, channels: u16, sample: SampleFormat) -> PcmFormat {
500 PcmFormat::new(rate, channels, sample)
501 }
502
503 fn convert_all(c: &mut Converter, input: &[u8], chunk: usize, room: usize) -> Vec<u8> {
505 let mut result = Vec::new();
506 let mut buffer = vec![0u8; room];
507 let mut pending: &[u8] = &[];
508 let mut rest = input;
509 let chunk = (chunk / c.source_frame_bytes()).max(1) * c.source_frame_bytes();
510 loop {
511 if pending.is_empty() && !rest.is_empty() {
512 let take = chunk.min(rest.len());
513 pending = &rest[..take];
514 rest = &rest[take..];
515 }
516 if pending.is_empty() {
517 break;
518 }
519 let done = c.process(pending, &mut buffer).unwrap();
520 result.extend_from_slice(&buffer[..done.produced]);
521 pending = &pending[done.consumed..];
522 if done.consumed == 0 && done.produced == 0 {
523 assert!(
525 pending.len() < c.source_frame_bytes(),
526 "stuck with {} bytes",
527 pending.len()
528 );
529 break;
530 }
531 }
532 loop {
533 let n = c.finish(&mut buffer).unwrap();
534 if n == 0 {
535 break;
536 }
537 result.extend_from_slice(&buffer[..n]);
538 }
539 result
540 }
541
542 fn i16_bytes(values: &[i16]) -> Vec<u8> {
543 values.iter().flat_map(|v| v.to_le_bytes()).collect()
544 }
545
546 #[test]
547 fn padding_validation_only_scans_the_consumable_prefix() {
548 let padded = SampleFormat::Int {
549 bits: 20,
550 slot_bytes: 3,
551 };
552 for target in [padded, SampleFormat::I32] {
553 let mut c = converter(
554 fmt(48_000, 1, padded),
555 fmt(48_000, 1, target),
556 ConvertOptions::default(),
557 );
558 let input = [0x10, 0x12, 0x34, 0x11, 0x12, 0x34];
559 let mut output = [0x55; 8];
560 let width = c.target_frame_bytes();
561 let done = c.process(&input, &mut output[..width]).unwrap();
562 assert_eq!(done.consumed, 3);
563 let before = output;
564 assert!(matches!(
565 c.process(&input[3..], &mut output),
566 Err(ConvertError::InvalidArgument(_))
567 ));
568 assert_eq!(output, before);
569 assert_eq!(c.clipped_samples(), 0);
570 assert_eq!(c.process(&input[3..], &mut []).unwrap().consumed, 0);
571 }
572 }
573
574 #[test]
575 fn src_padding_boundaries_follow_current_phase_without_mutation_on_error() {
576 let padded = SampleFormat::Int {
577 bits: 20,
578 slot_bytes: 3,
579 };
580 for (source_rate, target_rate) in [(44_100, 48_000), (48_000, 44_100)] {
581 let mut actual = converter(
582 fmt(source_rate, 1, padded),
583 fmt(target_rate, 1, SampleFormat::I16),
584 ConvertOptions::default(),
585 );
586 let mut reference = converter(
587 fmt(source_rate, 1, padded),
588 fmt(target_rate, 1, SampleFormat::I16),
589 ConvertOptions::default(),
590 );
591 let prefix = vec![0u8; 3 * 103];
592 let mut a = vec![0u8; 512];
593 let mut b = vec![0u8; 512];
594 let first = actual.process(&prefix, &mut a).unwrap();
595 let ref_first = reference.process(&prefix, &mut b).unwrap();
596 assert_eq!(
597 (first.consumed, first.produced),
598 (ref_first.consumed, ref_first.produced)
599 );
600 assert_eq!(&a[..first.produced], &b[..ref_first.produced]);
601 let capacity = match &actual.engine {
602 Engine::Float(engine) => engine.resampler.as_ref().unwrap().max_input_for_output(7),
603 _ => panic!("expected resampling"),
604 };
605 assert!(capacity > 0);
606 let mut input = vec![0u8; (capacity + 1) * 3];
607 input[capacity * 3] = 1;
608 let mut small = [0u8; 14];
609 let done = actual.process(&input, &mut small).unwrap();
610 assert_eq!(done.consumed, capacity * 3);
611 let ref_done = reference
612 .process(&input[..capacity * 3], &mut b[..14])
613 .unwrap();
614 assert_eq!(&small[..done.produced], &b[..ref_done.produced]);
615 let mut invalid = vec![0u8; 3 * 100];
616 invalid[0] = 1;
617 let mut untouched = [0x55u8; 14];
618 assert!(matches!(
619 actual.process(&invalid, &mut untouched),
620 Err(ConvertError::InvalidArgument(_))
621 ));
622 assert_eq!(untouched, [0x55; 14]);
623 invalid[0] = 0;
624 let next = actual.process(&invalid, &mut untouched).unwrap();
625 let expected = reference.process(&invalid, &mut b[..14]).unwrap();
626 assert_eq!(
627 (next.consumed, next.produced),
628 (expected.consumed, expected.produced)
629 );
630 assert_eq!(&untouched[..next.produced], &b[..expected.produced]);
631 assert_eq!(actual.clipped_samples(), reference.clipped_samples());
632 }
633 }
634
635 #[test]
636 fn identical_formats_copy_the_bytes() {
637 let mut c = converter(
638 fmt(44_100, 2, SampleFormat::I16),
639 fmt(44_100, 2, SampleFormat::I16),
640 ConvertOptions::default(),
641 );
642 let input = i16_bytes(&[1, -2, 3, -4, 5, -6]);
643 assert_eq!(convert_all(&mut c, &input, 4, 64), input);
644 assert_eq!(c.delay_frames(), 0);
645 }
646
647 #[test]
648 fn widening_16_to_24_and_32_is_exact_with_zero_filled_low_bits() {
649 let input = i16_bytes(&[0x1234, -2, 0, i16::MAX, i16::MIN, 1]);
650 let mut to24 = converter(
651 fmt(44_100, 1, SampleFormat::I16),
652 fmt(44_100, 1, SampleFormat::I24),
653 ConvertOptions::default(),
654 );
655 let out = convert_all(&mut to24, &input, 100, 100);
656 assert_eq!(&out[..3], &[0x00, 0x34, 0x12]);
657 assert_eq!(&out[3..6], &[0x00, 0xfe, 0xff]);
658 assert_eq!(&out[9..12], &[0x00, 0xff, 0x7f]); assert_eq!(&out[12..15], &[0x00, 0x00, 0x80]); let mut to32 = converter(
662 fmt(44_100, 1, SampleFormat::I16),
663 fmt(44_100, 1, SampleFormat::I32),
664 ConvertOptions::default(),
665 );
666 let out = convert_all(&mut to32, &input, 100, 100);
667 assert_eq!(&out[..4], &[0x00, 0x00, 0x34, 0x12]);
668 let values: Vec<i32> = out
669 .chunks_exact(4)
670 .map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
671 .collect();
672 let expected: Vec<i32> = [0x1234i16, -2, 0, i16::MAX, i16::MIN, 1]
673 .iter()
674 .map(|v| i32::from(*v) << 16)
675 .collect();
676 assert_eq!(values, expected);
677 }
678
679 #[test]
680 fn packed_24_and_24_in_4_repack_bit_exactly_both_ways() {
681 let values: Vec<i32> = (0..50_000i64)
683 .map(|i| (((i * 99_991) % 16_777_216) - 8_388_608) as i32)
684 .collect();
685 let packed: Vec<u8> = values
686 .iter()
687 .flat_map(|v| {
688 [
689 (*v & 0xff) as u8,
690 ((*v >> 8) & 0xff) as u8,
691 ((*v >> 16) & 0xff) as u8,
692 ]
693 })
694 .collect();
695 let mut up = converter(
696 fmt(96_000, 1, SampleFormat::I24),
697 fmt(96_000, 1, SampleFormat::I24_IN_32),
698 ConvertOptions::default(),
699 );
700 let wide = convert_all(&mut up, &packed, 3000, 4000);
701 assert_eq!(wide.len(), values.len() * 4);
702 for (i, v) in values.iter().enumerate() {
703 let word = i32::from_le_bytes([
704 wide[i * 4],
705 wide[i * 4 + 1],
706 wide[i * 4 + 2],
707 wide[i * 4 + 3],
708 ]);
709 assert_eq!(word, v << 8, "sample {i}");
710 }
711 let mut down = converter(
712 fmt(96_000, 1, SampleFormat::I24_IN_32),
713 fmt(96_000, 1, SampleFormat::I24),
714 ConvertOptions::default(),
715 );
716 assert_eq!(convert_all(&mut down, &wide, 4000, 3000), packed);
717 }
718
719 #[test]
720 fn mono_to_stereo_duplicates_every_sample() {
721 let mut c = converter(
722 fmt(48_000, 1, SampleFormat::I16),
723 fmt(48_000, 2, SampleFormat::I16),
724 ConvertOptions::default(),
725 );
726 let out = convert_all(&mut c, &i16_bytes(&[10, -20, 30]), 6, 64);
727 assert_eq!(out, i16_bytes(&[10, 10, -20, -20, 30, 30]));
728 let mut widened = converter(
729 fmt(48_000, 1, SampleFormat::I16),
730 fmt(48_000, 2, SampleFormat::I24),
731 ConvertOptions::default(),
732 );
733 let out = convert_all(&mut widened, &i16_bytes(&[0x0102]), 2, 64);
734 assert_eq!(out, [0x00, 0x02, 0x01, 0x00, 0x02, 0x01]);
735 }
736
737 #[test]
738 fn narrowing_truncates_or_dithers_as_asked() {
739 let input: Vec<u8> = [0x1234_5678i32, -0x0000_ffff, 0x7fff_ffff]
740 .iter()
741 .flat_map(|v| v.to_le_bytes())
742 .collect();
743 let truncate = ConvertOptions {
744 narrowing: Narrowing::Truncate,
745 ..ConvertOptions::default()
746 };
747 let mut c = converter(
748 fmt(44_100, 1, SampleFormat::I32),
749 fmt(44_100, 1, SampleFormat::I16),
750 truncate,
751 );
752 let out = convert_all(&mut c, &input, 100, 100);
753 let values: Vec<i16> = out
754 .chunks_exact(2)
755 .map(|b| i16::from_le_bytes([b[0], b[1]]))
756 .collect();
757 assert_eq!(values, [0x1234, -1, 0x7fff]);
758
759 let mut dithered = converter(
760 fmt(44_100, 1, SampleFormat::I32),
761 fmt(44_100, 1, SampleFormat::I16),
762 ConvertOptions::default(),
763 );
764 let out = convert_all(&mut dithered, &input, 100, 100);
765 let values: Vec<i16> = out
766 .chunks_exact(2)
767 .map(|b| i16::from_le_bytes([b[0], b[1]]))
768 .collect();
769 assert!((i32::from(values[0]) - 0x1234).abs() <= 2);
770 assert!(i32::from(values[1]).abs() <= 2);
771 assert!(i32::from(values[2]) >= 0x7ffe, "{}", values[2]);
772 }
773
774 #[test]
775 fn integers_become_floats_exactly_and_floats_come_back_with_truncation() {
776 let ints: Vec<i16> = (-32768..=32767).step_by(7).map(|v| v as i16).collect();
777 let mut up = converter(
778 fmt(44_100, 1, SampleFormat::I16),
779 fmt(44_100, 1, SampleFormat::Float32),
780 ConvertOptions::default(),
781 );
782 let floats = convert_all(&mut up, &i16_bytes(&ints), 1000, 1000);
783 for (i, v) in ints.iter().enumerate() {
784 let x = f32::from_le_bytes([
785 floats[i * 4],
786 floats[i * 4 + 1],
787 floats[i * 4 + 2],
788 floats[i * 4 + 3],
789 ]);
790 assert_eq!(f64::from(x), f64::from(*v) / 32768.0, "sample {i}");
791 }
792 let truncate = ConvertOptions {
793 narrowing: Narrowing::Truncate,
794 ..ConvertOptions::default()
795 };
796 let mut down = converter(
797 fmt(44_100, 1, SampleFormat::Float32),
798 fmt(44_100, 1, SampleFormat::I16),
799 truncate,
800 );
801 assert_eq!(
802 convert_all(&mut down, &floats, 1000, 1000),
803 i16_bytes(&ints)
804 );
805 }
806
807 #[test]
808 fn a_24_bit_source_survives_a_float_round_trip() {
809 let values: Vec<i32> = (0..20_000i64)
810 .map(|i| (((i * 99_991) % 16_777_216) - 8_388_608) as i32)
811 .collect();
812 let packed: Vec<u8> = values
813 .iter()
814 .flat_map(|v| {
815 [
816 (*v & 0xff) as u8,
817 ((*v >> 8) & 0xff) as u8,
818 ((*v >> 16) & 0xff) as u8,
819 ]
820 })
821 .collect();
822 let truncate = ConvertOptions {
823 narrowing: Narrowing::Truncate,
824 ..ConvertOptions::default()
825 };
826 let mut up = converter(
827 fmt(96_000, 1, SampleFormat::I24),
828 fmt(96_000, 1, SampleFormat::Float32),
829 truncate,
830 );
831 let floats = convert_all(&mut up, &packed, 3000, 4000);
832 let mut down = converter(
833 fmt(96_000, 1, SampleFormat::Float32),
834 fmt(96_000, 1, SampleFormat::I24),
835 truncate,
836 );
837 assert_eq!(
838 convert_all(&mut down, &floats, 4000, 3000),
839 packed,
840 "a float holds 24 bits exactly"
841 );
842 }
843
844 #[test]
845 fn non_finite_floats_are_silence_and_full_scale_saturates_with_a_count() {
846 let input: Vec<u8> = [f32::NAN, f32::INFINITY, 2.0, -2.0, 0.5]
847 .iter()
848 .flat_map(|v| v.to_le_bytes())
849 .collect();
850 let mut c = converter(
851 fmt(44_100, 1, SampleFormat::Float32),
852 fmt(44_100, 1, SampleFormat::I16),
853 ConvertOptions::default(),
854 );
855 let out = convert_all(&mut c, &input, 100, 100);
856 let values: Vec<i16> = out
857 .chunks_exact(2)
858 .map(|b| i16::from_le_bytes([b[0], b[1]]))
859 .collect();
860 assert!(values[0].abs() <= 1 && values[1].abs() <= 1, "{values:?}");
861 assert!(values[2] >= 32766 && values[3] <= -32767, "{values:?}");
862 assert!((i32::from(values[4]) - 16384).abs() <= 1);
863 assert_eq!(c.clipped_samples(), 2);
864 c.reset();
865 assert_eq!(c.clipped_samples(), 0);
866 }
867
868 #[test]
869 fn chunking_and_a_tight_output_buffer_change_nothing() {
870 let input: Vec<u8> = (0..40_000i32)
871 .flat_map(|i| (((i * 37) % 60_000 - 30_000) as i16).to_le_bytes())
872 .collect();
873 for (source, target, mono) in [
874 (
875 fmt(44_100, 2, SampleFormat::I16),
876 fmt(48_000, 2, SampleFormat::I24),
877 false,
878 ),
879 (
880 fmt(44_100, 1, SampleFormat::I16),
881 fmt(48_000, 2, SampleFormat::I16),
882 true,
883 ),
884 (
885 fmt(44_100, 2, SampleFormat::I16),
886 fmt(44_100, 2, SampleFormat::I24_IN_32),
887 false,
888 ),
889 ] {
890 let channels = usize::from(source.channels);
891 let usable = input.len() / (2 * channels) * (2 * channels);
892 let whole = {
893 let mut c = converter(source, target, ConvertOptions::default());
894 convert_all(&mut c, &input[..usable], usable, 1 << 20)
895 };
896 for (chunk, room) in [
897 (2 * channels, 64),
898 (1000 * channels, 3),
899 (4096, 1000),
900 (7 * 2 * channels, 123),
901 ] {
902 let mut c = converter(source, target, ConvertOptions::default());
903 let room = room.max(c.min_output_bytes());
904 let got = convert_all(&mut c, &input[..usable], chunk, room);
905 assert_eq!(
906 got, whole,
907 "{source:?} -> {target:?}, chunk {chunk}, room {room}, mono {mono}"
908 );
909 }
910 }
911 }
912
913 #[test]
914 fn a_resampling_converter_produces_the_exact_length_and_reports_its_delay() {
915 let source = fmt(44_100, 2, SampleFormat::I16);
916 let target = fmt(48_000, 2, SampleFormat::I16);
917 let mut c = converter(source, target, ConvertOptions::default());
918 assert!(c.delay_frames() > 0);
919 assert_eq!(
920 c.delay_frames(),
921 80,
922 "158 taps round up to 160: 80 frames held back"
923 );
924 let frames = 10_000usize;
925 let input = vec![0u8; frames * 4];
926 let out = convert_all(&mut c, &input, 4 * 333, 4 * 500);
927 assert_eq!(out.len(), (frames * 160).div_ceil(147) * 4);
928 }
929
930 #[test]
931 fn processing_after_finish_needs_a_reset_and_a_reset_gives_the_same_stream_again() {
932 let source = fmt(48_000, 1, SampleFormat::I16);
933 let target = fmt(44_100, 1, SampleFormat::I16);
934 let input: Vec<u8> = (0..6_000i32)
935 .flat_map(|i| (((i * 91) % 20_000 - 10_000) as i16).to_le_bytes())
936 .collect();
937 let mut c = converter(source, target, ConvertOptions::default());
938 let first = convert_all(&mut c, &input, 1000, 4096);
939 let mut sink = vec![0u8; 64];
940 assert_eq!(
941 c.process(&input, &mut sink).unwrap_err().code(),
942 "invalid_state"
943 );
944 c.reset();
945 let second = convert_all(&mut c, &input, 777, 999);
946 assert_eq!(
947 first, second,
948 "reset restores the filter, the counters and the dither"
949 );
950 }
951
952 #[test]
953 fn output_len_for_matches_what_process_writes() {
954 let mut c = converter(
955 fmt(44_100, 2, SampleFormat::I16),
956 fmt(96_000, 2, SampleFormat::I24),
957 ConvertOptions::default(),
958 );
959 let input = vec![0u8; 4 * 1000];
960 let mut buffer = vec![0u8; 1 << 20];
961 for _ in 0..5 {
962 let predicted = c.output_len_for(input.len());
963 let done = c.process(&input, &mut buffer).unwrap();
964 assert_eq!(done.produced, predicted);
965 }
966 }
967
968 #[test]
969 fn a_resampled_sine_keeps_its_frequency_level_and_stays_clean() {
970 let frames = 44_100usize;
972 let input: Vec<u8> = (0..frames)
973 .flat_map(|n| {
974 let v = (0.5
975 * (2.0 * std::f64::consts::PI * 1000.0 * n as f64 / 44_100.0).sin()
976 * 32767.0)
977 .round() as i16;
978 v.to_le_bytes()
979 })
980 .collect();
981 let mut c = converter(
982 fmt(44_100, 1, SampleFormat::I16),
983 fmt(48_000, 1, SampleFormat::I24),
984 ConvertOptions {
985 headroom_db: 0.0,
986 ..ConvertOptions::default()
987 },
988 );
989 let out = convert_all(&mut c, &input, 4096, 8192);
990 let samples: Vec<f64> = out
991 .chunks_exact(3)
992 .map(|b| f64::from(i32::from_le_bytes([0, b[0], b[1], b[2]]) >> 8) / 8_388_608.0)
993 .collect();
994 assert_eq!(samples.len(), (frames * 160).div_ceil(147));
995 let len = (samples.len() - 4000) / 48 * 48;
997 let middle = &samples[2000..2000 + len];
998 let peak = middle.iter().fold(0.0f64, |m, v| m.max(v.abs()));
999 assert!((peak - 0.5).abs() < 0.001, "peak {peak}");
1000 let w = 2.0 * std::f64::consts::PI * 1000.0 / 48_000.0;
1002 let (mut a, mut b) = (0.0, 0.0);
1003 for (i, y) in middle.iter().enumerate() {
1004 a += y * (w * i as f64).sin();
1005 b += y * (w * i as f64).cos();
1006 }
1007 let n = middle.len() as f64;
1008 let (a, b) = (2.0 * a / n, 2.0 * b / n);
1009 let residual = middle
1010 .iter()
1011 .enumerate()
1012 .map(|(i, y)| y - (a * (w * i as f64).sin() + b * (w * i as f64).cos()))
1013 .map(|e| e * e)
1014 .sum::<f64>()
1015 / n;
1016 let noise_db = 10.0 * (residual / (0.5f64 * 0.5 / 2.0)).log10();
1017 assert!(noise_db < -90.0, "noise at {noise_db} dB");
1018 }
1019
1020 #[test]
1021 fn a_full_scale_square_wave_overshoots_and_saturates_without_wrapping_and_headroom_prevents_it()
1022 {
1023 let frames = 20_000usize;
1024 let input: Vec<u8> = (0..frames)
1025 .flat_map(|n| {
1026 let v: i16 = if (n / 22) % 2 == 0 {
1027 i16::MAX
1028 } else {
1029 i16::MIN
1030 };
1031 v.to_le_bytes()
1032 })
1033 .collect();
1034 let source = fmt(44_100, 1, SampleFormat::I16);
1035 let target = fmt(48_000, 1, SampleFormat::I16);
1036
1037 let mut plain = converter(
1038 source,
1039 target,
1040 ConvertOptions {
1041 headroom_db: 0.0,
1042 ..ConvertOptions::default()
1043 },
1044 );
1045 let out = convert_all(&mut plain, &input, 4096, 8192);
1046 let values: Vec<i16> = out
1047 .chunks_exact(2)
1048 .map(|b| i16::from_le_bytes([b[0], b[1]]))
1049 .collect();
1050 assert!(
1051 plain.clipped_samples() > 0,
1052 "the Gibbs overshoot of a full-scale square wave exceeds full scale"
1053 );
1054 let mut reference = converter(
1058 source,
1059 fmt(48_000, 1, SampleFormat::Float32),
1060 ConvertOptions {
1061 headroom_db: 0.0,
1062 ..ConvertOptions::default()
1063 },
1064 );
1065 let floats = convert_all(&mut reference, &input, 4096, 8192);
1066 assert_eq!(floats.len() / 4, values.len());
1067 let mut beyond = 0;
1068 for (i, (value, float)) in values.iter().zip(floats.chunks_exact(4)).enumerate() {
1069 let x = f64::from(f32::from_le_bytes([float[0], float[1], float[2], float[3]]));
1070 if x > 1.0 {
1071 beyond += 1;
1072 }
1073 let expected = (x * 32768.0).round().clamp(-32768.0, 32767.0);
1074 assert!(
1075 (f64::from(*value) - expected).abs() <= 2.0,
1076 "sample {i}: {value} for a float of {x}"
1077 );
1078 }
1079 assert!(beyond > 0, "the float conversion shows the overshoot");
1080
1081 let overshoot = floats
1082 .chunks_exact(4)
1083 .map(|b| f64::from(f32::from_le_bytes([b[0], b[1], b[2], b[3]])).abs())
1084 .fold(0.0f64, f64::max);
1085 println!(
1086 "full-scale square wave, 44.1 -> 48 kHz: peak {overshoot:.4} = {:+.2} dB",
1087 20.0 * overshoot.log10()
1088 );
1089 assert!(overshoot > 1.2 && overshoot < 1.6, "{overshoot}");
1090
1091 let mut default_guard = converter(source, target, ConvertOptions::default());
1092 convert_all(&mut default_guard, &input, 4096, 8192);
1093 assert_eq!(default_guard.clipped_samples(), 0);
1094 let headroom = ConvertOptions {
1095 headroom_db: -3.5,
1096 ..ConvertOptions::default()
1097 };
1098 let mut guarded = converter(source, target, headroom);
1099 convert_all(&mut guarded, &input, 4096, 8192);
1100 assert_eq!(
1101 guarded.clipped_samples(),
1102 0,
1103 "3.5 dB of headroom covers the overshoot"
1104 );
1105 }
1106
1107 #[test]
1108 fn phase_reversal_can_clip_with_default_headroom() {
1109 for quality in [super::super::Quality::High, super::super::Quality::Fast] {
1110 let input: Vec<u8> = (0..8192)
1111 .flat_map(|n| {
1112 let phase = 2.0 * std::f64::consts::PI * 19_000.0 * n as f64 / 44_100.0;
1113 let sign = if (n / 256) % 2 == 0 { 1.0 } else { -1.0 };
1114 ((phase.sin().signum() * sign * 32767.0) as i16).to_le_bytes()
1115 })
1116 .collect();
1117 let source = fmt(44_100, 1, SampleFormat::I16);
1118 let options = ConvertOptions {
1119 quality,
1120 narrowing: Narrowing::Truncate,
1121 ..ConvertOptions::default()
1122 };
1123 let mut floating = converter(source, fmt(48_000, 1, SampleFormat::Float32), options);
1124 let floats = convert_all(&mut floating, &input, 4096, 8192);
1125 let peak = floats
1126 .chunks_exact(4)
1127 .map(|b| f32::from_le_bytes(b.try_into().unwrap()).abs())
1128 .fold(0.0f32, f32::max);
1129 let mut integer = converter(source, fmt(48_000, 1, SampleFormat::I16), options);
1130 let ints = convert_all(&mut integer, &input, 4096, 8192);
1131 println!(
1132 "{quality:?} phase reversal peak {peak}, clips {}",
1133 integer.clipped_samples()
1134 );
1135 assert!(peak > 1.0 && integer.clipped_samples() > 0);
1136 for (f, i) in floats.chunks_exact(4).zip(ints.chunks_exact(2)) {
1137 let f = f32::from_le_bytes(f.try_into().unwrap());
1138 let i = i16::from_le_bytes(i.try_into().unwrap());
1139 if f > 1.0 {
1140 assert_eq!(i, i16::MAX);
1141 }
1142 if f < -1.0 {
1143 assert_eq!(i, i16::MIN);
1144 }
1145 }
1146 }
1147 }
1148
1149 #[test]
1150 fn a_full_scale_sine_is_not_clipped_with_a_float_or_a_truncating_16_bit_target() {
1151 for hz in [100.0, 1_000.0, 10_000.0, 19_000.0] {
1153 let tone = |scale: f64| -> Vec<f64> {
1155 (0..20_000)
1156 .map(|n| {
1157 let edge = n.min(19_999 - n).min(2_000) as f64 / 2_000.0;
1158 let fade = 0.5 - 0.5 * (std::f64::consts::PI * edge).cos();
1159 scale
1160 * fade
1161 * (2.0 * std::f64::consts::PI * hz * f64::from(n) / 44_100.0).sin()
1162 })
1163 .collect()
1164 };
1165 let input: Vec<u8> = tone(1.0)
1167 .iter()
1168 .flat_map(|v| (*v as f32).to_le_bytes())
1169 .collect();
1170 let mut c = converter(
1171 fmt(44_100, 1, SampleFormat::Float32),
1172 fmt(96_000, 1, SampleFormat::Float32),
1173 ConvertOptions {
1174 headroom_db: 0.0,
1175 ..ConvertOptions::default()
1176 },
1177 );
1178 let out = convert_all(&mut c, &input, 4096, 8192);
1179 let settled = &out[4 * 1000..out.len() - 4 * 1000];
1180 let peak = settled
1181 .chunks_exact(4)
1182 .map(|b| f64::from(f32::from_le_bytes([b[0], b[1], b[2], b[3]])).abs())
1183 .fold(0.0f64, f64::max);
1184 assert!(peak <= 1.00001, "{hz} Hz overshoots to {peak}");
1185 assert!(peak >= 0.9999, "{hz} Hz is down to {peak}");
1186
1187 let ints: Vec<u8> = tone(32767.0 / 32768.0)
1189 .iter()
1190 .flat_map(|v| ((v * 32768.0).round() as i16).to_le_bytes())
1191 .collect();
1192 let truncate = ConvertOptions {
1193 narrowing: Narrowing::Truncate,
1194 ..ConvertOptions {
1195 headroom_db: 0.0,
1196 ..ConvertOptions::default()
1197 }
1198 };
1199 let mut c = converter(
1200 fmt(44_100, 1, SampleFormat::I16),
1201 fmt(96_000, 1, SampleFormat::I16),
1202 truncate,
1203 );
1204 convert_all(&mut c, &ints, 4096, 8192);
1205 assert_eq!(c.clipped_samples(), 0, "{hz} Hz clipped");
1206 }
1207 }
1208
1209 #[test]
1210 fn the_fast_preset_is_cheaper() {
1211 let plan = |quality| {
1212 converter(
1213 fmt(48_000, 2, SampleFormat::I16),
1214 fmt(44_100, 2, SampleFormat::I16),
1215 ConvertOptions {
1216 quality,
1217 ..ConvertOptions::default()
1218 },
1219 )
1220 };
1221 assert!(plan(Quality::Fast).delay_frames() * 2 < plan(Quality::High).delay_frames());
1222 }
1223}