decibri_decode/sample.rs
1//! Linear PCM sample formats, and the conversions between them and the `f32`
2//! this crate works in.
3//!
4//! This is the least interesting code in the crate and the foundation of all of
5//! it: mu-law decodes to linear PCM, WAV dispatches to it, and every decoded
6//! sample in every format passes through one of the functions here.
7//!
8//! # The numerical conventions, and where they come from
9//!
10//! These three were read out of decibri rather than chosen. A convention that
11//! differs from decibri's does not fail a test here. It produces a silent
12//! disagreement between this crate's output and decibri's on the same input,
13//! which is the expensive kind of difference.
14//!
15//! **Scale.** An integer sample of `n` bits is divided by `2^(n-1)`, not by
16//! `2^(n-1) - 1`. For `i16` that is `32768.0`, from
17//! `crates/decibri/src/sample.rs:42` and `:62` in decibri, and from the same
18//! divisor on decibri's numpy path in `bindings/python/src/lib.rs:874`. So
19//! [`i16::MIN`] maps to exactly `-1.0` and [`i16::MAX`] to `32767/32768`,
20//! slightly short of `+1.0`. The asymmetry is the price of the round trip being
21//! exact, which is what [`f32_to_i16`] and [`i16_to_f32`] give in return.
22//!
23//! **Rounding and clamping.** Float to integer clamps the float into
24//! `-1.0..=1.0`, scales, truncates toward zero, then clamps again in integer
25//! space, `crates/decibri/src/sample.rs:8-14`. A value exactly halfway between
26//! two integers goes toward zero, because truncation is what decibri's cast
27//! does. Both clamps stay: decoded and processed audio does exceed full scale
28//! in practice: decibri measured 1.41 out of its echo canceller against a
29//! capture peaking at 0.81, and a conversion that wrapped it would turn a loud
30//! passage into a loud passage of the opposite sign. decibri guards that with a
31//! regression test at `crates/decibri/src/sample.rs:188`; this crate guards it
32//! in `a_float_beyond_full_scale_clamps_and_never_wraps`.
33//!
34//! Float *output* formats are not clamped, matching
35//! `f32_to_f32_le_bytes` at `crates/decibri/src/sample.rs:23-29`: an `f32`
36//! consumer is delivered what the chain produced, overshoot included.
37//!
38//! **Downmix.** The arithmetic mean of a frame's channels, summed in `f32` in
39//! channel order, `crates/decibri/src/sample.rs:94-103`, which is what
40//! decibri's `File::open` reaches through `build_capture_stage`'s `Downmix`
41//! stage at `crates/decibri/src/stage.rs:104`. Not a sum, not a weighted
42//! fold. See [`downmix_to_mono`].
43//!
44//! # Determinism, and the two things it is not
45//!
46//! Every conversion here is bit-exact and byte-identical across targets. Two
47//! properties are deliberately *not* claimed alongside it.
48//!
49//! **Losslessness.** A round trip through `f32` is exact for every format at or
50//! below 24 significant bits (`u8`, `i8`, `i16`, the packed 24-bit formats and
51//! `f32` itself), and not for `i32` or `f64`, whose 31 and 53 significant
52//! bits do not fit in a 24-bit significand. Those land on the nearest
53//! representable `f32`, deterministically, with the error bounded by half an ulp
54//! at that magnitude. Nothing wraps and no sign flips. It is inherent to an
55//! `f32` internal representation, and the right trade for a crate feeding
56//! decibri's `f32` chain, but it is not losslessness and is not described as it.
57//!
58//! **A NaN's identity.** A NaN converted to an integer becomes silence, and a
59//! NaN narrowed from `f64` to `f32` becomes silence as well. The second was the
60//! one place in this crate where the output bits were architecture-dependent,
61//! because IEEE 754 does not specify the payload a NaN keeps through it, so
62//! normalising it removes the exception rather than documenting it.
63//!
64//! # No dither
65//!
66//! Float to integer clamps and rounds, deterministically, with nothing added.
67//! Dither trades correlated distortion for uncorrelated noise when reducing bit
68//! depth for a listener, and it is the wrong tool twice over here: this crate
69//! claims bit-exact cross-platform byte-identical output, and a random source
70//! would either break that claim or make a generator seed part of the public
71//! contract. There is no listener on a decode front end feeding a speech
72//! pipeline. If dither is ever wanted it belongs in an output stage.
73
74/// The widest sample any [`SampleFormat`] occupies, in bytes.
75///
76/// `f64` sets it. A decoder holding a partial sample needs a buffer this big
77/// and never bigger, which is why [`PcmDecoder`](crate::PcmDecoder) can hold
78/// its straddling bytes in a fixed array rather than a `Vec`.
79pub const MAX_BYTES_PER_SAMPLE: usize = 8;
80
81/// The most negative value a packed 24-bit sample can hold.
82pub const I24_MIN: i32 = -8_388_608;
83
84/// The most positive value a packed 24-bit sample can hold.
85pub const I24_MAX: i32 = 8_388_607;
86
87/// A linear PCM sample format: a width, a signedness and, above one byte, a
88/// byte order.
89///
90/// Little-endian covers WAV, big-endian covers AIFF, and both are needed.
91///
92/// **Eight-bit signedness is the container's, not a convention.** WAV's 8-bit
93/// PCM is unsigned, offset by 128; AIFF's is signed two's complement. Those
94/// are what the two specifications say, and they are exact inverses of each
95/// other, which is why [`U8`](Self::U8) and [`I8`](Self::I8) are two variants
96/// rather than one variant and a flag somebody forgets to set. A converter
97/// that reads either one as the other produces audio offset by half full
98/// scale, which sounds like severe distortion rather than like a subtle bug;
99/// see [`u8_to_f32`] and [`i8_to_f32`].
100///
101/// This enum is `#[non_exhaustive]`: a consumer matching on it needs a `_`
102/// arm, so a later container's format can be added without breaking source.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104#[non_exhaustive]
105pub enum SampleFormat {
106 /// Unsigned 8-bit, offset by 128, as WAV carries. One byte, so no byte
107 /// order.
108 U8,
109 /// Signed 8-bit two's complement, as AIFF carries. One byte, so no byte
110 /// order.
111 I8,
112 /// Signed 16-bit, little-endian.
113 I16Le,
114 /// Signed 16-bit, big-endian.
115 I16Be,
116 /// Signed 24-bit packed into three bytes, little-endian.
117 I24Le,
118 /// Signed 24-bit packed into three bytes, big-endian.
119 I24Be,
120 /// Signed 32-bit, little-endian.
121 I32Le,
122 /// Signed 32-bit, big-endian.
123 I32Be,
124 /// IEEE 754 binary32, little-endian.
125 F32Le,
126 /// IEEE 754 binary32, big-endian.
127 F32Be,
128 /// IEEE 754 binary64, little-endian.
129 F64Le,
130 /// IEEE 754 binary64, big-endian.
131 F64Be,
132}
133
134impl SampleFormat {
135 /// How many bytes one sample occupies.
136 ///
137 /// Three for the 24-bit formats: they are packed, not padded into four.
138 pub const fn bytes_per_sample(self) -> usize {
139 match self {
140 Self::U8 | Self::I8 => 1,
141 Self::I16Le | Self::I16Be => 2,
142 Self::I24Le | Self::I24Be => 3,
143 Self::I32Le | Self::I32Be | Self::F32Le | Self::F32Be => 4,
144 Self::F64Le | Self::F64Be => 8,
145 }
146 }
147
148 /// How many bits of resolution one sample carries.
149 ///
150 /// The form a container declares, and the form
151 /// [`DecodeError::UnsupportedSampleFormat`](crate::DecodeError::UnsupportedSampleFormat)
152 /// reports.
153 pub const fn bits_per_sample(self) -> u16 {
154 (self.bytes_per_sample() * 8) as u16
155 }
156
157 /// `true` for the IEEE 754 formats.
158 ///
159 /// The distinction is not cosmetic: the float formats pass values through
160 /// unclamped, and the integer formats clamp.
161 pub const fn is_float(self) -> bool {
162 matches!(self, Self::F32Le | Self::F32Be | Self::F64Le | Self::F64Be)
163 }
164
165 /// Appends every whole sample in `bytes` to `output` as `f32`, and returns
166 /// how many it appended.
167 ///
168 /// `output` is appended to, never cleared, the same convention as
169 /// [`Decoder::decode`](crate::Decoder::decode), so a decoder's output vector
170 /// feeds a resampler with no copy in between. A trailing partial sample is
171 /// ignored rather than rejected; the caller owns the decision about whether
172 /// running out of bytes mid-sample is an error, because on an open stream it
173 /// is not. [`PcmDecoder`](crate::PcmDecoder) makes that decision.
174 ///
175 /// ```
176 /// use decibri_decode::SampleFormat;
177 ///
178 /// let mut samples = Vec::new();
179 /// // 0x8000 is i16::MIN little-endian: exactly -1.0.
180 /// let appended = SampleFormat::I16Le.decode(&[0x00, 0x80, 0x00, 0x40], &mut samples);
181 /// assert_eq!(appended, 2);
182 /// assert_eq!(samples, [-1.0, 0.5]);
183 /// ```
184 pub fn decode(self, bytes: &[u8], output: &mut Vec<f32>) -> usize {
185 let width = self.bytes_per_sample();
186 let whole = bytes.len() / width;
187 output.reserve(whole);
188 for sample in bytes.chunks_exact(width) {
189 output.push(self.decode_sample(sample));
190 }
191 whole
192 }
193
194 /// Appends `samples` to `output` in this format, and returns how many bytes
195 /// it appended.
196 ///
197 /// Integer formats clamp; float formats pass the value through as it is.
198 ///
199 /// ```
200 /// use decibri_decode::SampleFormat;
201 ///
202 /// let mut bytes = Vec::new();
203 /// // Beyond full scale clamps to the extreme rather than wrapping.
204 /// let appended = SampleFormat::I16Be.encode(&[1.5], &mut bytes);
205 /// assert_eq!(appended, 2);
206 /// assert_eq!(bytes, [0x7f, 0xff]);
207 /// ```
208 pub fn encode(self, samples: &[f32], output: &mut Vec<u8>) -> usize {
209 let written = samples.len() * self.bytes_per_sample();
210 output.reserve(written);
211 for &sample in samples {
212 self.encode_sample(sample, output);
213 }
214 written
215 }
216
217 /// One sample's worth of bytes to `f32`. `bytes` is exactly
218 /// [`bytes_per_sample`](Self::bytes_per_sample) long.
219 fn decode_sample(self, bytes: &[u8]) -> f32 {
220 debug_assert_eq!(bytes.len(), self.bytes_per_sample());
221 match self {
222 Self::U8 => u8_to_f32(bytes[0]),
223 Self::I8 => i8_to_f32(bytes[0] as i8),
224 Self::I16Le => i16_to_f32(i16::from_le_bytes([bytes[0], bytes[1]])),
225 Self::I16Be => i16_to_f32(i16::from_be_bytes([bytes[0], bytes[1]])),
226 // Sign extension from 24 bits to 32 is the classic bug in this
227 // format. Landing the three bytes in the *top* of an i32 and
228 // shifting right arithmetically does it without a branch and
229 // without a mask that has to be got right twice.
230 Self::I24Le => i24_to_f32(i32::from_le_bytes([0, bytes[0], bytes[1], bytes[2]]) >> 8),
231 Self::I24Be => i24_to_f32(i32::from_be_bytes([bytes[0], bytes[1], bytes[2], 0]) >> 8),
232 Self::I32Le => i32_to_f32(i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])),
233 Self::I32Be => i32_to_f32(i32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])),
234 Self::F32Le => f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
235 Self::F32Be => f32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
236 Self::F64Le => narrow(f64::from_le_bytes([
237 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
238 ])),
239 Self::F64Be => narrow(f64::from_be_bytes([
240 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
241 ])),
242 }
243 }
244
245 /// One `f32` to this format's bytes, appended to `output`.
246 fn encode_sample(self, sample: f32, output: &mut Vec<u8>) {
247 match self {
248 Self::U8 => output.push(f32_to_u8(sample)),
249 Self::I8 => output.push(f32_to_i8(sample) as u8),
250 Self::I16Le => output.extend_from_slice(&f32_to_i16(sample).to_le_bytes()),
251 Self::I16Be => output.extend_from_slice(&f32_to_i16(sample).to_be_bytes()),
252 // The fourth byte of the i32 is sign extension, which is exactly
253 // what a packed 24-bit sample leaves out: drop the high byte on the
254 // little-endian side and the low byte on the big-endian one.
255 Self::I24Le => output.extend_from_slice(&f32_to_i24(sample).to_le_bytes()[..3]),
256 Self::I24Be => output.extend_from_slice(&f32_to_i24(sample).to_be_bytes()[1..]),
257 Self::I32Le => output.extend_from_slice(&f32_to_i32(sample).to_le_bytes()),
258 Self::I32Be => output.extend_from_slice(&f32_to_i32(sample).to_be_bytes()),
259 Self::F32Le => output.extend_from_slice(&sample.to_le_bytes()),
260 Self::F32Be => output.extend_from_slice(&sample.to_be_bytes()),
261 Self::F64Le => output.extend_from_slice(&f64::from(sample).to_le_bytes()),
262 Self::F64Be => output.extend_from_slice(&f64::from(sample).to_be_bytes()),
263 }
264 }
265}
266
267/// `f64` to `f32`, with NaN normalised to silence.
268///
269/// The narrowing itself is round to nearest, ties to even, which IEEE 754
270/// specifies exactly, for every value except NaN. The bit pattern a NaN keeps
271/// through a narrowing conversion is *not* specified, so a decoded `f64` NaN was
272/// the one value in this crate whose `f32` representation could legitimately
273/// differ between architectures.
274///
275/// Sending it to `0.0` removes that exception rather than documenting it, and it
276/// is the answer the integer path already gives: `quantize` maps NaN to
277/// silence too, because silence is the only value a NaN can safely become. The
278/// determinism claim on this crate then stands without a carve-out, which is
279/// worth more than an accurate footnote: a contract with one exception invites
280/// the question of what else has one.
281///
282/// The 32-bit float formats are untouched by this: they involve no narrowing, so
283/// a NaN in the input arrives in the output as exactly the bit pattern the file
284/// carried, on every target.
285fn narrow(sample: f64) -> f32 {
286 if sample.is_nan() {
287 0.0
288 } else {
289 sample as f32
290 }
291}
292
293/// The float-to-integer rule, in one place because every width shares it.
294///
295/// Clamp the float, scale, truncate toward zero, clamp in integer space. The
296/// second clamp is not redundant: `1.0 * 32768.0` is `32768`, one past
297/// [`i16::MAX`]. The order matters: a cast before the clamp is the wrap this
298/// exists to prevent, and is the regression decibri records at
299/// `crates/decibri/src/sample.rs:186`.
300///
301/// A NaN sample clamps to NaN, and NaN cast to an integer is `0` in Rust,
302/// silence. That is the same answer decibri's path gives, and it is a
303/// deliberate one: silence is the only value a NaN can safely become.
304pub(crate) fn quantize(sample: f32, scale: f32, min: i64, max: i64) -> i64 {
305 let clamped = sample.clamp(-1.0, 1.0);
306 ((clamped * scale) as i64).clamp(min, max)
307}
308
309/// Unsigned 8-bit PCM to `f32`, offset by 128.
310///
311/// `0` is `-1.0`, `128` is `0.0`, `255` is `127/128`. The offset is what makes
312/// 8-bit WAV different from every wider format, and reading it as signed shifts
313/// the whole signal by half full scale.
314pub fn u8_to_f32(sample: u8) -> f32 {
315 (i16::from(sample) - 128) as f32 / 128.0
316}
317
318/// `f32` to unsigned 8-bit PCM, offset by 128.
319pub fn f32_to_u8(sample: f32) -> u8 {
320 (quantize(sample, 128.0, -128, 127) + 128) as u8
321}
322
323/// Signed 8-bit PCM to `f32`, divided by `128`.
324///
325/// The 8-bit format AIFF carries, and the exact inverse of WAV's unsigned
326/// convention: `-128` is `-1.0`, `0` is `0.0`, `127` is `127/128`. The same
327/// byte read through [`u8_to_f32`] instead lands half full scale away, so
328/// which of the two a container uses is the container's most audible single
329/// bit of documentation.
330pub fn i8_to_f32(sample: i8) -> f32 {
331 f32::from(sample) / 128.0
332}
333
334/// `f32` to signed 8-bit PCM, scaled by `128` and clamped.
335pub fn f32_to_i8(sample: f32) -> i8 {
336 quantize(sample, 128.0, -128, 127) as i8
337}
338
339/// Signed 16-bit PCM to `f32`, divided by `32768`.
340///
341/// [`i16::MIN`] is exactly `-1.0`; [`i16::MAX`] is `32767/32768`.
342pub fn i16_to_f32(sample: i16) -> f32 {
343 f32::from(sample) / 32768.0
344}
345
346/// `f32` to signed 16-bit PCM, scaled by `32768` and clamped.
347///
348/// The exact inverse of [`i16_to_f32`] across the whole 16-bit domain: every
349/// one of the 65,536 values survives the round trip bit-identically.
350pub fn f32_to_i16(sample: f32) -> i16 {
351 quantize(sample, 32768.0, i16::MIN as i64, i16::MAX as i64) as i16
352}
353
354/// Sign-extended 24-bit PCM to `f32`, divided by `8388608`.
355///
356/// `sample` is the sign-extended value, in `I24_MIN..=I24_MAX`; a value outside
357/// that range converts to a magnitude past `1.0` rather than being clamped,
358/// because a 24-bit sample cannot be out of range and a caller passing one that
359/// is has a bug upstream worth seeing.
360pub fn i24_to_f32(sample: i32) -> f32 {
361 sample as f32 / 8_388_608.0
362}
363
364/// `f32` to a sign-extended 24-bit value in `I24_MIN..=I24_MAX`.
365pub fn f32_to_i24(sample: f32) -> i32 {
366 quantize(sample, 8_388_608.0, I24_MIN as i64, I24_MAX as i64) as i32
367}
368
369/// Signed 32-bit PCM to `f32`, divided by `2147483648`.
370///
371/// `f32` carries 24 bits of significand, so this is lossy above `2^24`: the
372/// value lands on the nearest representable `f32`, which is what the format
373/// costs and not something this crate can avoid while its internal
374/// representation is `f32`. Every 32-bit sample the ear can tell apart survives;
375/// the bits that do not are 48 dB below the noise floor of any real recording.
376pub fn i32_to_f32(sample: i32) -> f32 {
377 sample as f32 / 2_147_483_648.0
378}
379
380/// `f32` to signed 32-bit PCM, scaled by `2147483648` and clamped.
381pub fn f32_to_i32(sample: f32) -> i32 {
382 quantize(sample, 2_147_483_648.0, i32::MIN as i64, i32::MAX as i64) as i32
383}
384
385/// Collapses interleaved multichannel audio to mono by averaging each frame's
386/// channels, appends the result to `output` and returns how many samples it
387/// appended.
388///
389/// The formula is decibri's, read from `crates/decibri/src/sample.rs:94-103`
390/// and reproduced rather than reinvented: the arithmetic mean, summed in `f32`
391/// in channel order, divided by the channel count. Not a sum, and not weighted.
392/// If this crate averaged differently, the same stereo file would give two
393/// different mono results depending on which path read it.
394///
395/// `channels <= 1` copies the input through unchanged. A trailing partial frame
396/// is dropped, as decibri drops it.
397///
398/// ```
399/// use decibri_decode::downmix_to_mono;
400///
401/// let mut mono = Vec::new();
402/// // L R L R -> two frames, each the mean of its two channels.
403/// downmix_to_mono(&[0.5, 0.3, 0.4, 0.6], 2, &mut mono);
404/// assert_eq!(mono.len(), 2);
405/// ```
406pub fn downmix_to_mono(samples: &[f32], channels: u16, output: &mut Vec<f32>) -> usize {
407 if channels <= 1 {
408 output.extend_from_slice(samples);
409 return samples.len();
410 }
411 let channels = usize::from(channels);
412 let frames = samples.len() / channels;
413 output.reserve(frames);
414 for frame in samples.chunks_exact(channels) {
415 // decibri's exact expression. `Iterator::sum` folds left to right from
416 // 0.0, and f32 addition does not associate, so the fold order is part
417 // of the answer and not an implementation detail.
418 output.push(frame.iter().sum::<f32>() / channels as f32);
419 }
420 frames
421}
422
423/// Splits interleaved samples into one plane per channel.
424///
425/// A trailing partial frame is dropped, so every returned plane has the same
426/// length. `channels == 0` yields no planes.
427///
428/// ```
429/// use decibri_decode::deinterleave;
430///
431/// let planes = deinterleave(&[1.0, -1.0, 2.0, -2.0], 2);
432/// assert_eq!(planes, vec![vec![1.0, 2.0], vec![-1.0, -2.0]]);
433/// ```
434pub fn deinterleave(samples: &[f32], channels: u16) -> Vec<Vec<f32>> {
435 let channels = usize::from(channels);
436 if channels == 0 {
437 return Vec::new();
438 }
439 let frames = samples.len() / channels;
440 let mut planes = vec![Vec::with_capacity(frames); channels];
441 for frame in samples.chunks_exact(channels) {
442 for (plane, &sample) in planes.iter_mut().zip(frame) {
443 plane.push(sample);
444 }
445 }
446 planes
447}
448
449/// Interleaves per-channel planes into `output`, and returns how many samples
450/// it appended.
451///
452/// The frame count is the shortest plane's length, so planes of unequal length
453/// interleave to the part they all cover rather than to a ragged buffer or a
454/// panic. No planes appends nothing.
455///
456/// ```
457/// use decibri_decode::interleave;
458///
459/// let mut out = Vec::new();
460/// interleave(&[vec![1.0, 2.0], vec![-1.0, -2.0]], &mut out);
461/// assert_eq!(out, [1.0, -1.0, 2.0, -2.0]);
462/// ```
463pub fn interleave<P: AsRef<[f32]>>(planes: &[P], output: &mut Vec<f32>) -> usize {
464 let frames = planes
465 .iter()
466 .map(|plane| plane.as_ref().len())
467 .min()
468 .unwrap_or(0);
469 let appended = frames * planes.len();
470 output.reserve(appended);
471 for frame in 0..frames {
472 for plane in planes {
473 output.push(plane.as_ref()[frame]);
474 }
475 }
476 appended
477}
478
479#[cfg(test)]
480mod tests {
481 use super::*;
482
483 /// Every format, for the tests that have to cover all of them rather than
484 /// the one that was being thought about.
485 const ALL: [SampleFormat; 12] = [
486 SampleFormat::U8,
487 SampleFormat::I8,
488 SampleFormat::I16Le,
489 SampleFormat::I16Be,
490 SampleFormat::I24Le,
491 SampleFormat::I24Be,
492 SampleFormat::I32Le,
493 SampleFormat::I32Be,
494 SampleFormat::F32Le,
495 SampleFormat::F32Be,
496 SampleFormat::F64Le,
497 SampleFormat::F64Be,
498 ];
499
500 /// The multi-byte formats, paired little-endian with big-endian.
501 const ENDIAN_PAIRS: [(SampleFormat, SampleFormat); 5] = [
502 (SampleFormat::I16Le, SampleFormat::I16Be),
503 (SampleFormat::I24Le, SampleFormat::I24Be),
504 (SampleFormat::I32Le, SampleFormat::I32Be),
505 (SampleFormat::F32Le, SampleFormat::F32Be),
506 (SampleFormat::F64Le, SampleFormat::F64Be),
507 ];
508
509 fn decode_one(format: SampleFormat, bytes: &[u8]) -> f32 {
510 let mut out = Vec::new();
511 assert_eq!(format.decode(bytes, &mut out), 1);
512 out[0]
513 }
514
515 fn encode_one(format: SampleFormat, sample: f32) -> Vec<u8> {
516 let mut out = Vec::new();
517 format.encode(&[sample], &mut out);
518 out
519 }
520
521 // -- Gate 5: exhaustive i16 round trip --------------------------------
522
523 /// All 65,536 `i16` values to `f32` and back, bit-identical. The complete
524 /// input domain, not a sample of it.
525 #[test]
526 fn every_i16_value_round_trips_bit_identically() {
527 for raw in i16::MIN..=i16::MAX {
528 let as_float = i16_to_f32(raw);
529 assert_eq!(
530 f32_to_i16(as_float),
531 raw,
532 "{raw} did not survive the round trip (became {as_float})"
533 );
534 }
535 }
536
537 /// The scale factor, stated as the two values that distinguish `/32768`
538 /// from `/32767`. This is the assertion that would fail if somebody
539 /// "corrected" the asymmetry.
540 #[test]
541 fn i16_is_scaled_by_32768_not_32767() {
542 assert_eq!(i16_to_f32(i16::MIN), -1.0);
543 assert_eq!(i16_to_f32(i16::MAX), 32767.0 / 32768.0);
544 assert!(i16_to_f32(i16::MAX) < 1.0);
545 assert_eq!(i16_to_f32(0), 0.0);
546 assert_eq!(i16_to_f32(16_384), 0.5);
547 // decibri's own worked example: 0.5 * 32768 = 16384.
548 assert_eq!(f32_to_i16(0.5), 16_384);
549 }
550
551 // -- Gate 6: exhaustive u8 round trip ---------------------------------
552
553 /// All 256 `u8` values.
554 #[test]
555 fn every_u8_value_round_trips_bit_identically() {
556 for raw in u8::MIN..=u8::MAX {
557 let as_float = u8_to_f32(raw);
558 assert_eq!(
559 f32_to_u8(as_float),
560 raw,
561 "{raw} did not survive the round trip (became {as_float})"
562 );
563 }
564 }
565
566 /// The 128 offset, at the three points where getting it wrong is loudest.
567 #[test]
568 fn u8_is_unsigned_and_offset_by_128() {
569 assert_eq!(u8_to_f32(0), -1.0);
570 assert_eq!(u8_to_f32(128), 0.0);
571 assert_eq!(u8_to_f32(255), 127.0 / 128.0);
572 // Silence in 8-bit WAV is 0x80, not 0x00. Reading it as signed puts
573 // silence at -1.0: a DC offset of half full scale.
574 assert_eq!(decode_one(SampleFormat::U8, &[0x80]), 0.0);
575 assert_eq!(encode_one(SampleFormat::U8, 0.0), [0x80]);
576 }
577
578 /// All 256 `i8` values: the exhaustive gate for the format AIFF carries.
579 #[test]
580 fn every_i8_value_round_trips_bit_identically() {
581 for raw in i8::MIN..=i8::MAX {
582 let as_float = i8_to_f32(raw);
583 assert_eq!(
584 f32_to_i8(as_float),
585 raw,
586 "{raw} did not survive the round trip (became {as_float})"
587 );
588 }
589 }
590
591 /// The signed convention, anchored at the bytes where confusing it with
592 /// the unsigned one is loudest. `0x00` is silence in AIFF and `-1.0` in
593 /// WAV; `0x80` is the reverse. A shared implementation that read both
594 /// containers' 8-bit through one function would fail one of these two
595 /// blocks whichever convention it picked.
596 #[test]
597 fn i8_is_signed_and_the_exact_inverse_of_u8() {
598 assert_eq!(i8_to_f32(0), 0.0);
599 assert_eq!(i8_to_f32(i8::MIN), -1.0);
600 assert_eq!(i8_to_f32(i8::MAX), 127.0 / 128.0);
601 assert_eq!(i8_to_f32(64), 0.5);
602
603 // Silence in AIFF's 8-bit is 0x00, not 0x80.
604 assert_eq!(decode_one(SampleFormat::I8, &[0x00]), 0.0);
605 assert_eq!(encode_one(SampleFormat::I8, 0.0), [0x00]);
606 // 0x80 is the most negative value, not the midpoint.
607 assert_eq!(decode_one(SampleFormat::I8, &[0x80]), -1.0);
608 // And every byte decodes exactly half full scale away from the same
609 // byte read as WAV's unsigned 8-bit, wrapped into range: the two
610 // conventions differ by the sign bit and nothing else.
611 for byte in 0..=u8::MAX {
612 assert_eq!(
613 decode_one(SampleFormat::I8, &[byte]),
614 decode_one(SampleFormat::U8, &[byte ^ 0x80]),
615 "byte {byte:#04x}: I8 and U8 are not sign-bit twins"
616 );
617 }
618 }
619
620 // -- Gate 7: i24 and i32 round trips ----------------------------------
621
622 /// Every one of the 16,777,216 packed 24-bit values. Exhaustive is
623 /// affordable here, so the strided sweep the plan allowed is not needed:
624 /// `f32` holds 24 significand bits, so the whole domain is representable
625 /// and the round trip is exact across all of it.
626 #[test]
627 fn every_i24_value_round_trips_bit_identically() {
628 for raw in I24_MIN..=I24_MAX {
629 assert_eq!(f32_to_i24(i24_to_f32(raw)), raw, "{raw} did not round trip");
630 }
631 }
632
633 /// `i32` cannot round trip exhaustively through `f32` and this states the
634 /// exact boundary of what does. Below `2^24` every value is exact; above
635 /// it, the value lands on the nearest `f32` and the error is bounded by half
636 /// an ulp at that magnitude, never wrapped, never sign-flipped.
637 #[test]
638 fn i32_round_trips_exactly_within_the_f32_significand_and_lands_near_outside_it() {
639 // Exact below 2^24: the whole range an f32 represents integrally.
640 for raw in [0, 1, -1, 1 << 20, -(1 << 20), (1 << 24) - 1, -(1 << 24)] {
641 assert_eq!(f32_to_i32(i32_to_f32(raw)), raw, "{raw} must be exact");
642 }
643 // Boundaries: the two values where a wrap would show up first.
644 assert_eq!(i32_to_f32(i32::MIN), -1.0);
645 assert_eq!(f32_to_i32(-1.0), i32::MIN);
646 // i32::MAX is not representable in f32; it rounds to 2^31, which the
647 // clamp brings back to i32::MAX. Exact by way of the clamp.
648 assert_eq!(i32_to_f32(i32::MAX), 1.0);
649 assert_eq!(f32_to_i32(1.0), i32::MAX);
650
651 // A strided sweep over the whole domain. The stride is 65,537, an odd
652 // number coprime with every power of two, so successive samples land on
653 // every bit position of the low half rather than repeating one residue
654 // class the way a power-of-two stride would. 65,536 iterations covers
655 // the range in a test that runs in milliseconds; exhaustive would be
656 // 4.29 billion.
657 const STRIDE: i64 = 65_537;
658 let mut raw = i32::MIN as i64;
659 while raw <= i32::MAX as i64 {
660 let value = raw as i32;
661 let recovered = f32_to_i32(i32_to_f32(value));
662 // Half an ulp of f32 at this magnitude, and never more.
663 let ulp = (value.unsigned_abs().max(1 << 24) >> 23) as i64;
664 let error = (recovered as i64 - raw).abs();
665 assert!(
666 error <= ulp,
667 "{value} recovered as {recovered}, off by {error} (ulp {ulp})"
668 );
669 // Whatever the precision loss, the sign never flips.
670 assert!(
671 recovered.signum() == value.signum() || value.unsigned_abs() <= 1,
672 "{value} changed sign to {recovered}"
673 );
674 raw += STRIDE;
675 }
676 }
677
678 /// The packed 24-bit boundaries, including the sign-extension edge that is
679 /// this format's classic bug: `0x800000` is the most negative value, not
680 /// the largest positive one.
681 #[test]
682 fn i24_sign_extension_is_correct_at_the_boundaries() {
683 assert_eq!(i24_to_f32(I24_MIN), -1.0);
684 assert_eq!(i24_to_f32(I24_MAX), 8_388_607.0 / 8_388_608.0);
685 assert_eq!(i24_to_f32(0), 0.0);
686 // 0x800000 little-endian is I24_MIN. Zero-extending instead of
687 // sign-extending would read it as +8388608, i.e. +1.0.
688 assert_eq!(decode_one(SampleFormat::I24Le, &[0x00, 0x00, 0x80]), -1.0);
689 assert_eq!(decode_one(SampleFormat::I24Be, &[0x80, 0x00, 0x00]), -1.0);
690 // 0xFFFFFF is -1 in 24-bit two's complement, not +16777215.
691 assert_eq!(
692 decode_one(SampleFormat::I24Le, &[0xff, 0xff, 0xff]),
693 -1.0 / 8_388_608.0
694 );
695 assert_eq!(
696 decode_one(SampleFormat::I24Be, &[0xff, 0xff, 0xff]),
697 -1.0 / 8_388_608.0
698 );
699 // And the largest positive, which must not read as negative.
700 assert_eq!(
701 decode_one(SampleFormat::I24Le, &[0xff, 0xff, 0x7f]),
702 8_388_607.0 / 8_388_608.0
703 );
704 }
705
706 // -- Gate 8: clamping -------------------------------------------------
707
708 /// A float past full scale converts to the integer extreme and never
709 /// wraps. A wrap turns a loud passage into a loud passage of the opposite
710 /// sign, which is the worst failure mode available here; decibri guards the
711 /// same property at `crates/decibri/src/sample.rs:188` because its echo
712 /// canceller really does emit 1.41 against a capture peaking at 0.81.
713 #[test]
714 fn a_float_beyond_full_scale_clamps_and_never_wraps() {
715 for over in [1.000_01_f32, 1.41, 2.0, 8.5, 1e9, f32::MAX, f32::INFINITY] {
716 assert_eq!(f32_to_u8(over), u8::MAX, "{over} must clamp in u8");
717 assert_eq!(f32_to_u8(-over), u8::MIN, "-{over} must clamp in u8");
718 assert_eq!(f32_to_i8(over), i8::MAX, "{over} must clamp in i8");
719 assert_eq!(f32_to_i8(-over), i8::MIN, "-{over} must clamp in i8");
720 assert_eq!(f32_to_i16(over), i16::MAX, "{over} must clamp in i16");
721 assert_eq!(f32_to_i16(-over), i16::MIN, "-{over} must clamp in i16");
722 assert_eq!(f32_to_i24(over), I24_MAX, "{over} must clamp in i24");
723 assert_eq!(f32_to_i24(-over), I24_MIN, "-{over} must clamp in i24");
724 assert_eq!(f32_to_i32(over), i32::MAX, "{over} must clamp in i32");
725 assert_eq!(f32_to_i32(-over), i32::MIN, "-{over} must clamp in i32");
726
727 // Through the byte-level API, which is what a caller actually hits.
728 assert_eq!(encode_one(SampleFormat::I16Le, over), [0xff, 0x7f]);
729 assert_eq!(encode_one(SampleFormat::I16Le, -over), [0x00, 0x80]);
730 assert_eq!(encode_one(SampleFormat::I24Be, over), [0x7f, 0xff, 0xff]);
731 assert_eq!(encode_one(SampleFormat::I24Be, -over), [0x80, 0x00, 0x00]);
732 }
733 }
734
735 /// The float formats do not clamp. An `f32` consumer is delivered what the
736 /// chain produced, overshoot included, and decibri's `f32_to_f32_le_bytes`
737 /// documents the same thing at `crates/decibri/src/sample.rs:23`, and the
738 /// overshoot is a statement about the canceller's residual rather than a
739 /// defect to hide.
740 #[test]
741 fn the_float_formats_pass_values_through_unclamped() {
742 for over in [1.41_f32, -2.0, 100.0] {
743 for format in [SampleFormat::F32Le, SampleFormat::F32Be] {
744 let bytes = encode_one(format, over);
745 assert_eq!(decode_one(format, &bytes), over);
746 }
747 for format in [SampleFormat::F64Le, SampleFormat::F64Be] {
748 let bytes = encode_one(format, over);
749 assert_eq!(decode_one(format, &bytes), over);
750 }
751 }
752 }
753
754 /// NaN becomes silence, not a wrapped extreme. Rust's float-to-integer cast
755 /// saturates and sends NaN to zero; this pins that as intended behaviour
756 /// rather than as something that happens to hold.
757 #[test]
758 fn nan_quantizes_to_silence() {
759 assert_eq!(f32_to_i16(f32::NAN), 0);
760 assert_eq!(f32_to_i32(f32::NAN), 0);
761 assert_eq!(f32_to_i24(f32::NAN), 0);
762 assert_eq!(f32_to_i8(f32::NAN), 0);
763 // Silence in unsigned 8-bit is the 128 midpoint.
764 assert_eq!(f32_to_u8(f32::NAN), 128);
765 }
766
767 /// A NaN arriving in an `f64` stream becomes silence at the point of
768 /// narrowing, rather than becoming whichever NaN the target's conversion
769 /// instruction happens to produce.
770 ///
771 /// IEEE 754 specifies the narrowing exactly for every value except NaN,
772 /// whose payload through a conversion is left to the implementation. That
773 /// made a decoded `f64` NaN the one output in this crate that could
774 /// legitimately differ between architectures; normalising it to silence
775 /// removes the exception, and matches what the integer path has always done.
776 #[test]
777 fn an_f64_nan_narrows_to_silence_rather_than_to_an_unspecified_nan() {
778 for format in [SampleFormat::F64Le, SampleFormat::F64Be] {
779 for nan in [f64::NAN, -f64::NAN, f64::from_bits(0x7ff8_0000_dead_beef)] {
780 let bytes = match format {
781 SampleFormat::F64Le => nan.to_le_bytes(),
782 _ => nan.to_be_bytes(),
783 };
784 let decoded = decode_one(format, &bytes);
785 assert!(!decoded.is_nan(), "{format:?} passed a NaN through");
786 assert_eq!(decoded.to_bits(), 0.0_f32.to_bits(), "{format:?}");
787 }
788 }
789 // A signalling NaN too: the quiet-bit handling on a narrowing is the
790 // part that differs most between architectures.
791 let signalling = f64::from_bits(0x7ff0_0000_0000_0001);
792 assert!(signalling.is_nan());
793 assert_eq!(
794 decode_one(SampleFormat::F64Le, &signalling.to_le_bytes()),
795 0.0
796 );
797
798 // Infinity is specified and is not touched: it is a real value that a
799 // decoder must not quietly turn into silence.
800 assert_eq!(
801 decode_one(SampleFormat::F64Le, &f64::INFINITY.to_le_bytes()),
802 f32::INFINITY
803 );
804
805 // The 32-bit float formats involve no narrowing, so a NaN there is
806 // exactly the bit pattern the file carried, on every target.
807 let bits = 0x7fc0_dead_u32;
808 assert_eq!(
809 decode_one(SampleFormat::F32Le, &bits.to_le_bytes()).to_bits(),
810 bits
811 );
812 }
813
814 /// Halfway between two integers goes toward zero, because truncation is
815 /// what decibri's cast does (`crates/decibri/src/sample.rs:12`). Stated as
816 /// a test so a later "improvement" to round-half-up has to argue with
817 /// decibri rather than with a comment.
818 #[test]
819 fn a_halfway_value_truncates_toward_zero() {
820 // 1.5 / 32768 scales to exactly 1.5.
821 assert_eq!(f32_to_i16(1.5 / 32768.0), 1);
822 assert_eq!(f32_to_i16(-1.5 / 32768.0), -1);
823 // And just under a whole number rounds down, not to nearest.
824 assert_eq!(f32_to_i16(0.999_999 * 2.0 / 32768.0), 1);
825 }
826
827 // -- Gate 9: endianness, against hand-written bytes -------------------
828
829 /// Byte sequences written by hand from the format definitions, not
830 /// produced by this crate's own encoder. An encoder and a decoder that
831 /// share a byte-order mistake agree with each other perfectly.
832 #[test]
833 fn endianness_is_proven_against_hand_written_bytes() {
834 // 0x1234 = 4660. As f32: 4660 / 32768.
835 assert_eq!(
836 decode_one(SampleFormat::I16Le, &[0x34, 0x12]),
837 4660.0 / 32768.0
838 );
839 assert_eq!(
840 decode_one(SampleFormat::I16Be, &[0x12, 0x34]),
841 4660.0 / 32768.0
842 );
843
844 // 0x123456 = 1193046. As f32: 1193046 / 8388608.
845 assert_eq!(
846 decode_one(SampleFormat::I24Le, &[0x56, 0x34, 0x12]),
847 1_193_046.0 / 8_388_608.0
848 );
849 assert_eq!(
850 decode_one(SampleFormat::I24Be, &[0x12, 0x34, 0x56]),
851 1_193_046.0 / 8_388_608.0
852 );
853
854 // 0x12345678 = 305419896. As f32 this rounds; compare against the same
855 // rounding applied to the integer, which is the documented behaviour.
856 assert_eq!(
857 decode_one(SampleFormat::I32Le, &[0x78, 0x56, 0x34, 0x12]),
858 305_419_896_f32 / 2_147_483_648.0
859 );
860 assert_eq!(
861 decode_one(SampleFormat::I32Be, &[0x12, 0x34, 0x56, 0x78]),
862 305_419_896_f32 / 2_147_483_648.0
863 );
864
865 // IEEE 754 binary32 for 1.0 is 0x3F800000.
866 assert_eq!(
867 decode_one(SampleFormat::F32Le, &[0x00, 0x00, 0x80, 0x3f]),
868 1.0
869 );
870 assert_eq!(
871 decode_one(SampleFormat::F32Be, &[0x3f, 0x80, 0x00, 0x00]),
872 1.0
873 );
874 // -0.5 is 0xBF000000.
875 assert_eq!(
876 decode_one(SampleFormat::F32Le, &[0x00, 0x00, 0x00, 0xbf]),
877 -0.5
878 );
879 assert_eq!(
880 decode_one(SampleFormat::F32Be, &[0xbf, 0x00, 0x00, 0x00]),
881 -0.5
882 );
883
884 // IEEE 754 binary64 for 1.0 is 0x3FF0000000000000.
885 assert_eq!(
886 decode_one(
887 SampleFormat::F64Le,
888 &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f]
889 ),
890 1.0
891 );
892 assert_eq!(
893 decode_one(
894 SampleFormat::F64Be,
895 &[0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
896 ),
897 1.0
898 );
899 // -0.25 is 0xBFD0000000000000.
900 assert_eq!(
901 decode_one(
902 SampleFormat::F64Be,
903 &[0xbf, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
904 ),
905 -0.25
906 );
907 }
908
909 /// `f64` narrows to `f32` on the way in, round to nearest, ties to even.
910 /// The crate works in `f32`, so a 64-bit source loses the bits `f32` has no
911 /// room for, deterministically, and at the point of decode rather than
912 /// somewhere downstream.
913 #[test]
914 fn f64_narrows_to_the_nearest_f32() {
915 // 0.1 is representable in neither, and the two nearest values differ.
916 let mut bytes = Vec::new();
917 SampleFormat::F64Le.encode(&[0.1], &mut bytes);
918 assert_eq!(decode_one(SampleFormat::F64Le, &bytes), 0.1_f32);
919 // A value with more precision than f32 can hold lands on the nearest.
920 let precise = 1.0_f64 / 3.0;
921 assert_eq!(
922 decode_one(SampleFormat::F64Be, &precise.to_be_bytes()),
923 precise as f32
924 );
925 // And one too large for f32 becomes infinity rather than wrapping.
926 assert_eq!(
927 decode_one(SampleFormat::F64Le, &1.0e300_f64.to_le_bytes()),
928 f32::INFINITY
929 );
930 }
931
932 /// The two byte orders are byte-reversals of each other, for every
933 /// multi-byte format and a spread of values. Catches a format whose two
934 /// variants were implemented independently and diverged.
935 #[test]
936 fn the_two_byte_orders_are_reversals_of_each_other() {
937 for (little, big) in ENDIAN_PAIRS {
938 for sample in [0.0_f32, 0.5, -0.5, 1.0, -1.0, 0.123_456_79, -0.987_654_3] {
939 let mut le = encode_one(little, sample);
940 let be = encode_one(big, sample);
941 le.reverse();
942 assert_eq!(le, be, "{little:?} and {big:?} disagree on {sample}");
943 }
944 }
945 }
946
947 // -- Round trips through the byte-level API ---------------------------
948
949 /// Every format survives f32 -> bytes -> f32 for values it can represent.
950 /// The 8-bit format is coarse enough to need its own tolerance; the rest
951 /// are exact at these values.
952 #[test]
953 fn every_format_round_trips_through_bytes() {
954 for format in ALL {
955 let samples = [0.0_f32, 0.5, -0.5, 0.25, -0.75];
956 let mut bytes = Vec::new();
957 let written = format.encode(&samples, &mut bytes);
958 assert_eq!(written, samples.len() * format.bytes_per_sample());
959 assert_eq!(bytes.len(), written);
960
961 let mut back = Vec::new();
962 assert_eq!(format.decode(&bytes, &mut back), samples.len());
963 for (original, recovered) in samples.iter().zip(&back) {
964 let tolerance = 1.0 / 128.0;
965 assert!(
966 (original - recovered).abs() <= tolerance,
967 "{format:?}: {original} came back as {recovered}"
968 );
969 }
970 // Everything but the 8-bit format is exact at these values.
971 if format != SampleFormat::U8 {
972 assert_eq!(back, samples, "{format:?} was not exact");
973 }
974 }
975 }
976
977 /// A trailing partial sample is ignored by the slice API rather than
978 /// rejected or read past. The decision about whether it is an error belongs
979 /// to the caller, because on an open stream it is not one.
980 #[test]
981 fn a_trailing_partial_sample_is_ignored_by_the_slice_api() {
982 let mut out = Vec::new();
983 // Five bytes of a three-byte format: one whole sample, two bytes over.
984 assert_eq!(
985 SampleFormat::I24Le.decode(&[0, 0, 0, 0xff, 0xff], &mut out),
986 1
987 );
988 assert_eq!(out, [0.0]);
989
990 out.clear();
991 assert_eq!(SampleFormat::F64Be.decode(&[0; 7], &mut out), 0);
992 assert!(out.is_empty());
993 assert_eq!(SampleFormat::U8.decode(&[], &mut out), 0);
994 }
995
996 /// `decode` and `encode` append rather than replace, which is what lets a
997 /// decoder's output vector feed a resampler without a copy.
998 #[test]
999 fn decode_and_encode_append_rather_than_clear() {
1000 let mut samples = vec![99.0_f32];
1001 SampleFormat::I16Le.decode(&[0x00, 0x40], &mut samples);
1002 assert_eq!(samples, [99.0, 0.5]);
1003
1004 let mut bytes = vec![0xaa];
1005 SampleFormat::U8.encode(&[0.0], &mut bytes);
1006 assert_eq!(bytes, [0xaa, 0x80]);
1007 }
1008
1009 // -- Format metadata --------------------------------------------------
1010
1011 #[test]
1012 fn format_widths_are_what_the_wire_carries() {
1013 assert_eq!(SampleFormat::U8.bytes_per_sample(), 1);
1014 assert_eq!(SampleFormat::I16Be.bytes_per_sample(), 2);
1015 // Packed, not padded into four.
1016 assert_eq!(SampleFormat::I24Le.bytes_per_sample(), 3);
1017 assert_eq!(SampleFormat::I24Le.bits_per_sample(), 24);
1018 assert_eq!(SampleFormat::I32Le.bytes_per_sample(), 4);
1019 assert_eq!(SampleFormat::F64Le.bytes_per_sample(), 8);
1020
1021 for format in ALL {
1022 assert!(
1023 format.bytes_per_sample() <= MAX_BYTES_PER_SAMPLE,
1024 "{format:?} does not fit the partial-sample buffer"
1025 );
1026 assert_eq!(
1027 format.is_float(),
1028 matches!(
1029 format,
1030 SampleFormat::F32Le
1031 | SampleFormat::F32Be
1032 | SampleFormat::F64Le
1033 | SampleFormat::F64Be
1034 ),
1035 "{format:?} is on the wrong side of is_float"
1036 );
1037 }
1038 }
1039
1040 // -- Q3: downmix, matched to decibri ----------------------------------
1041
1042 /// decibri's own downmix test vectors, from
1043 /// `crates/decibri/src/sample.rs:313-356`, run against this
1044 /// implementation. If the two ever diverge, the same file decoded through
1045 /// each path gives two different mono results, and this is where that shows
1046 /// up.
1047 #[test]
1048 fn the_downmix_matches_decibris_vectors_exactly() {
1049 let mut mono = Vec::new();
1050 // test_downmix_stereo_averages_and_halves
1051 assert_eq!(downmix_to_mono(&[0.5, 0.3, 0.4, 0.6], 2, &mut mono), 2);
1052 assert!((mono[0] - 0.4).abs() < 1e-6);
1053 assert!((mono[1] - 0.5).abs() < 1e-6);
1054
1055 // test_downmix_six_channel: a 5.1 frame summing to zero.
1056 mono.clear();
1057 downmix_to_mono(&[0.0, 0.6, 0.3, -0.3, 1.2, -1.8], 6, &mut mono);
1058 assert_eq!(mono.len(), 1);
1059 assert!((mono[0] - 0.0).abs() < 1e-6);
1060
1061 // test_downmix_preserves_sign_and_magnitude
1062 mono.clear();
1063 downmix_to_mono(&[1.0, -1.0], 2, &mut mono);
1064 assert_eq!(mono, [0.0]);
1065 mono.clear();
1066 downmix_to_mono(&[-0.5, -0.5], 2, &mut mono);
1067 assert_eq!(mono, [-0.5]);
1068
1069 // test_downmix_drops_trailing_partial_frame: 5 samples, 2 channels.
1070 mono.clear();
1071 assert_eq!(downmix_to_mono(&[0.2, 0.4, 0.6, 0.8, 0.9], 2, &mut mono), 2);
1072 assert!((mono[0] - 0.3).abs() < 1e-6);
1073 assert!((mono[1] - 0.7).abs() < 1e-6);
1074
1075 // test_downmix_mono_passthrough, including the degenerate zero.
1076 mono.clear();
1077 downmix_to_mono(&[0.1, -0.2, 0.3], 1, &mut mono);
1078 assert_eq!(mono, [0.1, -0.2, 0.3]);
1079 mono.clear();
1080 downmix_to_mono(&[0.1, -0.2, 0.3], 0, &mut mono);
1081 assert_eq!(mono, [0.1, -0.2, 0.3]);
1082
1083 // test_downmix_empty
1084 mono.clear();
1085 assert_eq!(downmix_to_mono(&[], 2, &mut mono), 0);
1086 assert!(mono.is_empty());
1087 }
1088
1089 /// The formula is the mean and not the sum. Two identical channels
1090 /// reproduce the mono signal at its original level rather than at twice it,
1091 /// which is the property decibri's `open_reads_header_and_downmixes` test
1092 /// asserts on the file path (`crates/decibri/src/file.rs:1095`).
1093 #[test]
1094 fn the_downmix_is_a_mean_and_not_a_sum() {
1095 let mut mono = Vec::new();
1096 downmix_to_mono(&[0.7, 0.7, -0.3, -0.3], 2, &mut mono);
1097 assert_eq!(mono, [0.7, -0.3]);
1098 }
1099
1100 /// The fold order is part of the answer. `f32` addition does not associate,
1101 /// so a downmix summing in a different order, or in `f64` and narrowed,
1102 /// would differ from decibri's in the last bit on some inputs. This pins
1103 /// the left-to-right `f32` fold.
1104 #[test]
1105 fn the_downmix_sums_left_to_right_in_f32() {
1106 // Chosen so that (a + b) + c and a + (b + c) differ in f32.
1107 let a = 1.0_f32;
1108 let b = 1e-8_f32;
1109 let c = -1.0_f32;
1110 let left_to_right = ((a + b) + c) / 3.0;
1111 let mut mono = Vec::new();
1112 downmix_to_mono(&[a, b, c], 3, &mut mono);
1113 assert_eq!(mono[0].to_bits(), left_to_right.to_bits());
1114 }
1115
1116 // -- Interleaving -----------------------------------------------------
1117
1118 #[test]
1119 fn interleaving_round_trips_through_planes() {
1120 let interleaved = [1.0_f32, -1.0, 2.0, -2.0, 3.0, -3.0];
1121 let planes = deinterleave(&interleaved, 2);
1122 assert_eq!(planes, vec![vec![1.0, 2.0, 3.0], vec![-1.0, -2.0, -3.0]]);
1123
1124 let mut back = Vec::new();
1125 assert_eq!(interleave(&planes, &mut back), interleaved.len());
1126 assert_eq!(back, interleaved);
1127 }
1128
1129 #[test]
1130 fn deinterleaving_drops_a_trailing_partial_frame_and_handles_the_edges() {
1131 // Seven samples at three channels: two whole frames, one sample over.
1132 let planes = deinterleave(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], 3);
1133 assert_eq!(planes, vec![vec![1.0, 4.0], vec![2.0, 5.0], vec![3.0, 6.0]]);
1134 // Mono is one plane, unchanged.
1135 assert_eq!(deinterleave(&[1.0, 2.0], 1), vec![vec![1.0, 2.0]]);
1136 // No channels is no planes, not a division by zero.
1137 assert!(deinterleave(&[1.0, 2.0], 0).is_empty());
1138 assert_eq!(deinterleave(&[], 2), vec![Vec::<f32>::new(); 2]);
1139 }
1140
1141 #[test]
1142 fn interleaving_uneven_planes_covers_the_shortest() {
1143 let mut out = Vec::new();
1144 // Three frames in one plane, two in the other: two frames interleave.
1145 assert_eq!(
1146 interleave(&[vec![1.0, 2.0, 3.0], vec![-1.0, -2.0]], &mut out),
1147 4
1148 );
1149 assert_eq!(out, [1.0, -1.0, 2.0, -2.0]);
1150
1151 out.clear();
1152 let empty: [Vec<f32>; 0] = [];
1153 assert_eq!(interleave(&empty, &mut out), 0);
1154 assert!(out.is_empty());
1155
1156 // Slices work as well as owned planes, without a reshaping copy.
1157 out.clear();
1158 let left: &[f32] = &[1.0, 2.0];
1159 let right: &[f32] = &[-1.0, -2.0];
1160 assert_eq!(interleave(&[left, right], &mut out), 4);
1161 assert_eq!(out, [1.0, -1.0, 2.0, -2.0]);
1162 }
1163
1164 /// Interleaving appends, like everything else that writes into a caller's
1165 /// buffer here.
1166 #[test]
1167 fn interleave_appends_rather_than_clears() {
1168 let mut out = vec![42.0_f32];
1169 interleave(&[vec![1.0], vec![2.0]], &mut out);
1170 assert_eq!(out, [42.0, 1.0, 2.0]);
1171 }
1172}