Skip to main content

decibri_decode/
g711.rs

1//! G.711 mu-law and A-law: the two ITU-T companding laws, both directions, and
2//! a [`Decoder`] for headerless G.711 streams.
3//!
4//! # Why this is the first codec
5//!
6//! G.711's correct answer is published and finite. There are exactly 256 codes
7//! per law, so the decode gate is not a sample of the input domain. It *is*
8//! the input domain, and so is the 65,536-value encode gate. Nothing else this
9//! crate will carry has that property, which makes this the cheapest place to
10//! establish that the codec layer is sound.
11//!
12//! # A sample format, not a rate
13//!
14//! G.711 is overwhelmingly carried at 8 kHz in telephony and nothing in the
15//! recommendation says so. The rate comes from the [`AudioSpec`] the caller
16//! hands [`G711Decoder::new`]; nothing here defaults to 8000 or checks for it.
17//!
18//! # Where the tables come from
19//!
20//! The ITU-T G.711 recommendation defines both laws as explicit tables: eight
21//! segments per law, sixteen intervals per segment, and a decoder output at each
22//! interval's midpoint. The code below derives that geometry from the
23//! recommendation's own structure (segment boundaries are powers of two, so a
24//! segment index is a bit position and an interval index is a shift) rather
25//! than transcribing a third-party implementation's tables. The crate is
26//! Apache-2.0 and published, so reference data with an unestablished licence is
27//! a real constraint rather than a formality.
28//!
29//! # Layering
30//!
31//! Decode is a G.711 code to `i16` through the table, then `i16` to `f32`
32//! through [`i16_to_f32`]. Encode is the reverse: `f32` to `i16` through
33//! [`f32_to_i16`], then `i16` to a code. There is deliberately **no** direct
34//! code-to-`f32` path. One scaling rule in the crate is one opportunity to
35//! disagree with decibri by a fraction of a bit; two would be two, and the rule
36//! in [`sample`](crate::sample) has already been matched against decibri and
37//! exhaustively tested.
38//!
39//! # Lossy, and idempotent anyway
40//!
41//! G.711 discards information: a round trip through it is not the identity, and
42//! the crate does not pretend otherwise. What *does* hold is that a second pass
43//! costs nothing: encoding, decoding and encoding again returns the code the
44//! first encode produced. A codec failing that loses information on every pass
45//! rather than only on the first.
46//!
47//! The one wrinkle is mu-law's second zero. The recommendation gives mu-law two
48//! codes for silence, `0xFF` and `0x7F`, and the encoder can only ever emit
49//! `0xFF` because a two's-complement zero has no sign to carry. `0x7F` decodes
50//! to `0` like its twin and re-encodes to `0xFF`; nothing is lost, and it is the
51//! one code in either law that is not its own fixed point. See
52//! [`G711Law::code_to_linear`].
53
54use crate::audio::AudioSpec;
55use crate::decoder::Decoder;
56use crate::error::DecodeError;
57use crate::sample::{f32_to_i16, i16_to_f32};
58
59/// How many decoded samples accumulate before [`feed`](Decoder::feed) stops
60/// taking bytes.
61///
62/// The same figure [`PcmDecoder`](crate::PcmDecoder) holds, for the same
63/// reason: a caller handing over a whole file in one call gets back-pressure and
64/// a bounded decoder rather than a buffer the size of the file. G.711 is one
65/// byte per sample, so this is also the largest number of bytes a single `feed`
66/// will ever take.
67const READY_LIMIT: usize = 65_536;
68
69/// The bias G.711 adds to a mu-law magnitude before segmenting it, and takes
70/// off again on the way out.
71///
72/// 33 in the 14-bit domain the recommendation writes mu-law in. It is what
73/// makes the first mu-law segment start at 32 rather than at 0, and it is the
74/// single constant that distinguishes the two laws' otherwise identical
75/// segment geometry.
76const MU_BIAS: i32 = 33;
77
78/// One of the two G.711 companding laws.
79///
80/// Not `#[non_exhaustive]`, unlike [`SampleFormat`](crate::SampleFormat): G.711
81/// defines exactly two laws and has since 1972. There is no third one to leave
82/// room for, so a consumer gets an exhaustive match instead of a `_` arm they
83/// can never reach.
84///
85/// mu-law is the North American and Japanese law; A-law is the European and
86/// international one. They are not interchangeable, because decoding one as
87/// the other produces audible, wrong audio rather than an error, so the law is
88/// a constructor argument to [`G711Decoder`] and never inferred.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90pub enum G711Law {
91    /// mu-law, ITU-T G.711 clause 2: 14-bit magnitude, biased by 33.
92    MuLaw,
93    /// A-law, ITU-T G.711 clause 3: 13-bit magnitude, unbiased.
94    ALaw,
95}
96
97impl G711Law {
98    /// One G.711 code to the linear 16-bit sample the ITU table gives for it.
99    ///
100    /// The recommendation writes mu-law over a 14-bit magnitude and A-law over a
101    /// 13-bit one; both are scaled here to the 16-bit linear domain the rest of
102    /// the crate converts from, by 4 and by 8 respectively. That puts mu-law's
103    /// range at +/-32124 and A-law's at +/-32256. Neither reaches [`i16::MAX`],
104    /// which is a property of the laws and not of this implementation.
105    ///
106    /// Every one of the 256 codes is valid input. There is no such thing as a
107    /// malformed G.711 code, which is why this returns a sample rather than a
108    /// `Result`.
109    ///
110    /// ```
111    /// use decibri_decode::G711Law;
112    ///
113    /// // Silence: 0xFF in mu-law, 0xD5 in A-law. A file of 0x00 bytes is loud
114    /// // in both, which is the mistake this asymmetry exists to make visible.
115    /// assert_eq!(G711Law::MuLaw.code_to_linear(0xFF), 0);
116    /// assert_eq!(G711Law::ALaw.code_to_linear(0xD5), 8);
117    /// assert_eq!(G711Law::MuLaw.code_to_linear(0x00), -32124);
118    ///
119    /// // mu-law's second zero decodes to silence like its twin.
120    /// assert_eq!(G711Law::MuLaw.code_to_linear(0x7F), 0);
121    /// ```
122    pub const fn code_to_linear(self, code: u8) -> i16 {
123        match self {
124            Self::MuLaw => mu_law_to_linear(code),
125            Self::ALaw => a_law_to_linear(code),
126        }
127    }
128
129    /// One linear 16-bit sample to the G.711 code whose quantisation interval
130    /// contains it.
131    ///
132    /// Total over the whole `i16` domain: every input has a code, and a
133    /// magnitude past the top of the last segment clamps to the extreme code
134    /// rather than wrapping.
135    ///
136    /// ```
137    /// use decibri_decode::G711Law;
138    ///
139    /// assert_eq!(G711Law::MuLaw.linear_to_code(0), 0xFF);
140    /// assert_eq!(G711Law::ALaw.linear_to_code(0), 0xD5);
141    /// // Past the top of the last segment, and still the extreme code.
142    /// assert_eq!(G711Law::MuLaw.linear_to_code(i16::MAX), 0x80);
143    /// ```
144    pub const fn linear_to_code(self, sample: i16) -> u8 {
145        match self {
146            Self::MuLaw => linear_to_mu_law(sample),
147            Self::ALaw => linear_to_a_law(sample),
148        }
149    }
150
151    /// Appends one `f32` per code in `codes` to `output`, and returns how many
152    /// it appended.
153    ///
154    /// One code is one byte and one sample, so the return is `codes.len()`.
155    /// There is no partial sample to hold and no code this can reject.
156    ///
157    /// `output` is appended to, never cleared, the same convention as
158    /// [`SampleFormat::decode`](crate::SampleFormat::decode) and
159    /// [`Decoder::decode`], so a decoder's output vector feeds a resampler with
160    /// no copy in between.
161    ///
162    /// ```
163    /// use decibri_decode::G711Law;
164    ///
165    /// let mut samples = Vec::new();
166    /// assert_eq!(G711Law::ALaw.decode(&[0xD5, 0x55], &mut samples), 2);
167    /// assert_eq!(samples, [8.0 / 32768.0, -8.0 / 32768.0]);
168    /// ```
169    pub fn decode(self, codes: &[u8], output: &mut Vec<f32>) -> usize {
170        output.reserve(codes.len());
171        for &code in codes {
172            // Through the i16 table and then through the crate's one scaling
173            // rule. Never straight from a code to an f32.
174            output.push(i16_to_f32(self.code_to_linear(code)));
175        }
176        codes.len()
177    }
178
179    /// Appends one code per sample in `samples` to `output`, and returns how
180    /// many bytes it appended.
181    ///
182    /// One sample is one byte, so the return is `samples.len()`. The `f32`
183    /// reaches the table through [`f32_to_i16`], so a sample past full scale
184    /// clamps exactly as it does for linear PCM.
185    ///
186    /// ```
187    /// use decibri_decode::G711Law;
188    ///
189    /// let mut codes = Vec::new();
190    /// assert_eq!(G711Law::MuLaw.encode(&[0.0, 1.0], &mut codes), 2);
191    /// assert_eq!(codes, [0xFF, 0x80]);
192    /// ```
193    pub fn encode(self, samples: &[f32], output: &mut Vec<u8>) -> usize {
194        output.reserve(samples.len());
195        for &sample in samples {
196            output.push(self.linear_to_code(f32_to_i16(sample)));
197        }
198        samples.len()
199    }
200}
201
202/// A mu-law code to its 16-bit linear sample.
203///
204/// The code travels with every bit inverted, so the table is read off the
205/// complement: bit 7 is the sign, bits 6-4 the segment, bits 3-0 the interval.
206/// The magnitude is the interval's midpoint in the biased 14-bit domain, less
207/// the bias, scaled to 16 bits.
208const fn mu_law_to_linear(code: u8) -> i16 {
209    let value = !code;
210    let negative = value & 0x80 != 0;
211    let segment = ((value >> 4) & 0x07) as i32;
212    let interval = (value & 0x0F) as i32;
213
214    // Segment `n` of mu-law covers biased magnitudes `2^(n+5)` upwards in steps
215    // of `2^(n+1)`; sixteen such steps reach the start of segment `n+1`.
216    let start = 1_i32 << (segment + 5);
217    let step = 1_i32 << (segment + 1);
218    let magnitude = start + step * interval + step / 2 - MU_BIAS;
219
220    // 14-bit table to the 16-bit linear domain.
221    let linear = magnitude * 4;
222    if negative {
223        (-linear) as i16
224    } else {
225        linear as i16
226    }
227}
228
229/// A 16-bit linear sample to its mu-law code.
230const fn linear_to_mu_law(sample: i16) -> u8 {
231    let sample = sample as i32;
232    let negative = sample < 0;
233    // The 14-bit magnitude. The sign is taken first, so `>> 2` is the two bits
234    // the law discards rather than an arithmetic shift of a negative value.
235    let magnitude = if negative {
236        -(sample >> 2)
237    } else {
238        sample >> 2
239    };
240
241    // Bias, then clamp to the top of the last segment. i16::MIN reduces to a
242    // magnitude of 8192, which is past the 8158 the table reaches; the
243    // recommendation sends everything above the last segment to the extreme
244    // code.
245    let biased = magnitude + MU_BIAS;
246    let biased = if biased > 0x1FFF { 0x1FFF } else { biased };
247
248    // The segment is the bit position, because the segment boundaries are
249    // powers of two: biased magnitudes run 33..=8191, i.e. 2^5..=2^13 - 1.
250    let segment = biased.ilog2() as i32 - 5;
251    let start = 1_i32 << (segment + 5);
252    let step = 1_i32 << (segment + 1);
253    let interval = (biased - start) / step;
254
255    let word = if negative { 0x80_u8 } else { 0 } | ((segment as u8) << 4) | interval as u8;
256    // mu-law inverts every bit for transmission, which is what puts silence at
257    // 0xFF rather than at 0x00.
258    !word
259}
260
261/// An A-law code to its 16-bit linear sample.
262///
263/// A-law inverts the even bits for transmission, so the table is read off
264/// `code ^ 0x55`: bit 7 is the sign (set for *positive*, the opposite way
265/// round from mu-law's complemented word), bits 6-4 the segment, bits 3-0 the
266/// interval.
267const fn a_law_to_linear(code: u8) -> i16 {
268    let value = code ^ 0x55;
269    let positive = value & 0x80 != 0;
270    let segment = ((value >> 4) & 0x07) as i32;
271    let interval = (value & 0x0F) as i32;
272
273    // A-law's first two segments share a step of 2: segment 0 covers 13-bit
274    // magnitudes 0..=31 and segment 1 covers 32..=63, which is why the start of
275    // segment `n` is `2^(n+4)` for every segment but the first, where it is 0.
276    let start = if segment == 0 {
277        0
278    } else {
279        1_i32 << (segment + 4)
280    };
281    let step = if segment == 0 { 2 } else { 1_i32 << segment };
282    let magnitude = start + step * interval + step / 2;
283
284    // 13-bit table to the 16-bit linear domain.
285    let linear = magnitude * 8;
286    if positive {
287        linear as i16
288    } else {
289        (-linear) as i16
290    }
291}
292
293/// A 16-bit linear sample to its A-law code.
294const fn linear_to_a_law(sample: i16) -> u8 {
295    let sample = sample as i32;
296    let positive = sample >= 0;
297    // The 13-bit magnitude. The negative half folds about -1/2 rather than about
298    // 0, because the magnitude of a negative sample is `(-1 - x) >> 3`, which
299    // makes A-law's two halves symmetric and every one of its 256 codes its own
300    // fixed point under a second encode.
301    let magnitude = if positive {
302        sample >> 3
303    } else {
304        (-1 - sample) >> 3
305    };
306
307    // 13 bits from a 16-bit input never exceeds 4095, which is inside the last
308    // segment, so A-law needs no clamp: unlike mu-law, its table covers the
309    // whole reduced domain.
310    let segment = if magnitude < 32 {
311        0
312    } else {
313        magnitude.ilog2() as i32 - 4
314    };
315    let start = if segment == 0 {
316        0
317    } else {
318        1_i32 << (segment + 4)
319    };
320    let step = if segment == 0 { 2 } else { 1_i32 << segment };
321    let interval = (magnitude - start) / step;
322
323    let word = if positive { 0x80_u8 } else { 0 } | ((segment as u8) << 4) | interval as u8;
324    // A-law inverts the even bits for transmission, which puts silence at 0xD5.
325    word ^ 0x55
326}
327
328/// Decodes a headerless G.711 stream: one byte per sample in the law given at
329/// construction, samples out at an [`AudioSpec`] the caller states.
330///
331/// Headerless G.711 is what an RTP payload and a raw telephony capture carry, so
332/// nothing in the stream declares its rate, layout or law: they arrive out of
333/// band and are given at construction. Both are then fixed for the life of the
334/// instance, as [`Decoder::output_spec`] requires.
335///
336/// # Partial frames
337///
338/// One byte is one whole sample, so unlike [`PcmDecoder`](crate::PcmDecoder)
339/// there is never a partial *sample* to hold. There is still a partial *frame*:
340/// a stereo stream that ends after an odd number of bytes ended mid-frame, and
341/// reporting that as a clean end would hand the caller a buffer whose length is
342/// not a whole number of frames. [`flush`](Decoder::flush) is where that becomes
343/// [`DecodeError::Truncated`].
344///
345/// # Example
346///
347/// ```
348/// use decibri_decode::{AudioSpec, Decoder, G711Decoder, G711Law};
349///
350/// // The rate is the caller's to state. 8 kHz is the usual one for telephony
351/// // and nothing here assumes it.
352/// let mut decoder = G711Decoder::new(G711Law::MuLaw, AudioSpec::mono(16_000));
353/// let mut samples = Vec::new();
354///
355/// decoder.feed(&[0xFF, 0x80])?;
356/// decoder.decode(&mut samples)?;
357/// decoder.flush(&mut samples)?;
358/// assert_eq!(samples, [0.0, 32124.0 / 32768.0]);
359/// # Ok::<(), decibri_decode::DecodeError>(())
360/// ```
361#[derive(Debug)]
362pub struct G711Decoder {
363    /// Which companding law the incoming bytes are in.
364    law: G711Law,
365    /// The rate and layout of the samples produced.
366    spec: AudioSpec,
367    /// Samples decoded but not yet handed to a caller.
368    ready: Vec<f32>,
369    /// Samples produced since construction or the last `reset`, which is what
370    /// says whether the stream is on a frame boundary.
371    produced: u64,
372    /// Set by `flush`: end of stream until `reset`.
373    finished: bool,
374}
375
376impl G711Decoder {
377    /// A decoder for `law` codes producing samples at `spec`.
378    ///
379    /// Nothing is validated because nothing can be: a headerless stream carries
380    /// no claim to check the arguments against. `spec` is the assertion, and so
381    /// is `law`: decoding mu-law bytes as A-law is wrong but not detectable.
382    pub const fn new(law: G711Law, spec: AudioSpec) -> Self {
383        Self {
384            law,
385            spec,
386            ready: Vec::new(),
387            produced: 0,
388            finished: false,
389        }
390    }
391
392    /// The companding law this decoder reads.
393    pub const fn law(&self) -> G711Law {
394        self.law
395    }
396
397    /// How many bytes are held awaiting the rest of their frame.
398    ///
399    /// `0` means the stream is on a frame boundary and could be cut here without
400    /// loss, the same meaning the figure carries on
401    /// [`PcmDecoder::buffered_bytes`](crate::PcmDecoder::buffered_bytes), and
402    /// the same figure [`flush`](Decoder::flush) reports as `available` when it
403    /// rejects a truncated stream.
404    ///
405    /// There is never a partial sample here, so this counts only whole samples
406    /// sitting past the last frame boundary, one byte each.
407    pub fn buffered_bytes(&self) -> usize {
408        let channels = u64::from(self.spec.channels).max(1);
409        (self.produced % channels) as usize
410    }
411
412    /// How many bytes one whole frame occupies.
413    ///
414    /// A spec with no channels has no frame at all, so one sample stands in for
415    /// one: it keeps the truncation report meaningful instead of dividing by
416    /// zero, matching [`PcmDecoder`](crate::PcmDecoder).
417    fn frame_bytes(&self) -> usize {
418        usize::from(self.spec.channels).max(1)
419    }
420}
421
422impl Decoder for G711Decoder {
423    fn output_spec(&self) -> AudioSpec {
424        self.spec
425    }
426
427    fn feed(&mut self, input: &[u8]) -> Result<usize, DecodeError> {
428        if self.finished {
429            return Ok(0);
430        }
431        // One byte is one sample, so room in samples is room in bytes. At zero,
432        // the caller has to drain before feeding again.
433        let room = READY_LIMIT.saturating_sub(self.ready.len());
434        let taken = input.len().min(room);
435        self.produced += self.law.decode(&input[..taken], &mut self.ready) as u64;
436        Ok(taken)
437    }
438
439    fn decode(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError> {
440        if self.finished {
441            return Ok(0);
442        }
443        let produced = self.ready.len();
444        output.append(&mut self.ready);
445        Ok(produced)
446    }
447
448    fn flush(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError> {
449        if self.finished {
450            return Ok(0);
451        }
452        self.finished = true;
453        let held = self.buffered_bytes();
454        if held > 0 {
455            // The one place a partial frame is an error. A caller following the
456            // documented loop has already drained everything whole through
457            // `decode`, so nothing complete is lost with the rejection.
458            return Err(DecodeError::Truncated {
459                expected: self.frame_bytes() as u64,
460                available: held as u64,
461            });
462        }
463        let produced = self.ready.len();
464        output.append(&mut self.ready);
465        Ok(produced)
466    }
467
468    fn reset(&mut self) {
469        self.ready.clear();
470        self.produced = 0;
471        self.finished = false;
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478    use crate::audio::AudioBuffer;
479
480    const BOTH: [G711Law; 2] = [G711Law::MuLaw, G711Law::ALaw];
481
482    // -- The reference, built from the recommendation's tables ------------
483    //
484    // Everything below this line is an independent reading of ITU-T G.711.
485    // The implementation above derives each segment's start and step from a bit
486    // position, because the boundaries happen to be powers of two; the reference
487    // carries the same geometry as literal data, read off the recommendation's
488    // tables. A shift written one place out above is therefore not mirrored
489    // here, which is the whole point of having a reference at all.
490
491    /// A-law segment geometry in the 13-bit domain the recommendation writes it
492    /// in: the first magnitude each of the eight segments covers, and the width
493    /// of one of its sixteen intervals.
494    ///
495    /// The first two segments share a step of 2. That is the ITU table, not a
496    /// typo, and it is why A-law resolves small signals as finely as it does.
497    const A_LAW_SEGMENTS: [(i32, i32); 8] = [
498        (0, 2),
499        (32, 2),
500        (64, 4),
501        (128, 8),
502        (256, 16),
503        (512, 32),
504        (1024, 64),
505        (2048, 128),
506    ];
507
508    /// mu-law segment geometry in the *biased* 14-bit domain: the recommendation
509    /// adds 33 before segmenting, which is why the first segment starts at 32
510    /// rather than at 0 and why mu-law's steps are one power of two larger than
511    /// A-law's throughout.
512    const MU_LAW_SEGMENTS: [(i32, i32); 8] = [
513        (32, 2),
514        (64, 4),
515        (128, 8),
516        (256, 16),
517        (512, 32),
518        (1024, 64),
519        (2048, 128),
520        (4096, 256),
521    ];
522
523    /// The decoder output the ITU table gives for `code`, in the 16-bit linear
524    /// domain.
525    fn reference_decode(law: G711Law, code: u8) -> i16 {
526        let (segments, value) = match law {
527            // mu-law transmits the complement of the table word.
528            G711Law::MuLaw => (MU_LAW_SEGMENTS, !code),
529            // A-law transmits the table word with its even bits inverted.
530            G711Law::ALaw => (A_LAW_SEGMENTS, code ^ 0x55),
531        };
532        let (start, step) = segments[usize::from((value >> 4) & 0x07)];
533        let interval = i32::from(value & 0x0F);
534        let midpoint = start + step * interval + step / 2;
535        let (magnitude, negative) = match law {
536            // 14-bit, biased, scaled by 4. The sign bit of the complemented word
537            // is set for negative.
538            G711Law::MuLaw => ((midpoint - 33) * 4, value & 0x80 != 0),
539            // 13-bit, unbiased, scaled by 8. The sign bit is set for *positive*,
540            // the opposite way round.
541            G711Law::ALaw => (midpoint * 8, value & 0x80 == 0),
542        };
543        if negative {
544            -magnitude as i16
545        } else {
546            magnitude as i16
547        }
548    }
549
550    /// The range of 16-bit linear inputs the recommendation assigns to `code`,
551    /// or `None` for a code the encoder can never emit.
552    ///
553    /// Derived from the segment table and from the domain reduction each law
554    /// applies (mu-law drops two bits and takes the magnitude of a negative
555    /// sample as `-(x >> 2)`, A-law drops three and folds about `-1/2`), not
556    /// from the encoder under test.
557    fn reference_input_range(law: G711Law, code: u8) -> Option<(i16, i16)> {
558        let (segments, value) = match law {
559            G711Law::MuLaw => (MU_LAW_SEGMENTS, !code),
560            G711Law::ALaw => (A_LAW_SEGMENTS, code ^ 0x55),
561        };
562        let segment = usize::from((value >> 4) & 0x07);
563        let interval = i32::from(value & 0x0F);
564        let (start, step) = segments[segment];
565
566        let positive = match law {
567            G711Law::MuLaw => value & 0x80 == 0,
568            G711Law::ALaw => value & 0x80 != 0,
569        };
570        // The reduced-domain magnitudes this code stands for.
571        let low = match law {
572            G711Law::MuLaw => start + step * interval - 33,
573            G711Law::ALaw => start + step * interval,
574        };
575        let high = low + step - 1;
576        // Back out to 16 bits, through each law's own sign convention.
577        let (mut lo, mut hi) = match (law, positive) {
578            (G711Law::MuLaw, true) => (low * 4, high * 4 + 3),
579            (G711Law::MuLaw, false) => (-(high * 4), -(low * 4) + 3),
580            (G711Law::ALaw, true) => (low * 8, high * 8 + 7),
581            (G711Law::ALaw, false) => (-(high * 8) - 8, -(low * 8) - 1),
582        };
583        // The topmost interval absorbs everything past the last segment: a
584        // magnitude the table does not reach clamps to the extreme code.
585        if segment == 7 && interval == 15 {
586            if positive {
587                hi = i32::from(i16::MAX);
588            } else {
589                lo = i32::from(i16::MIN);
590            }
591        }
592        // A code's range only covers its own half of the domain. mu-law's second
593        // zero is the code this rules out entirely: its interval lies wholly on
594        // the positive side while its sign bit says negative.
595        let (floor, ceiling) = if positive {
596            (0, i32::from(i16::MAX))
597        } else {
598            (i32::from(i16::MIN), -1)
599        };
600        let (lo, hi) = (lo.max(floor), hi.min(ceiling));
601        if lo > hi {
602            None
603        } else {
604            Some((lo as i16, hi as i16))
605        }
606    }
607
608    /// Every 16-bit input mapped to its code, painted one code at a time from
609    /// [`reference_input_range`].
610    ///
611    /// Building it this way proves the intervals tile the domain: a value
612    /// claimed twice or not at all fails here rather than showing up as a
613    /// mysterious mismatch later.
614    fn reference_encode_table(law: G711Law) -> Vec<u8> {
615        let mut table: Vec<Option<u8>> = vec![None; 65_536];
616        for code in 0..=u8::MAX {
617            let Some((lo, hi)) = reference_input_range(law, code) else {
618                continue;
619            };
620            for sample in lo..=hi {
621                let slot =
622                    &mut table[usize::try_from(i32::from(sample) + 32_768).expect("in range")];
623                assert!(
624                    slot.is_none(),
625                    "{law:?}: {sample} is claimed by two codes, 0x{:02x} and 0x{code:02x}",
626                    slot.unwrap_or_default()
627                );
628                *slot = Some(code);
629            }
630        }
631        table
632            .into_iter()
633            .enumerate()
634            .map(|(index, code)| {
635                code.unwrap_or_else(|| {
636                    panic!("{law:?}: no code covers {}", index as i32 - 32_768);
637                })
638            })
639            .collect()
640    }
641
642    fn reference_encode(table: &[u8], sample: i16) -> u8 {
643        table[usize::try_from(i32::from(sample) + 32_768).expect("in range")]
644    }
645
646    /// Drives a decoder to completion over `input` split into `chunk`-byte
647    /// pieces, the way the trait documents a caller should.
648    fn drive(
649        decoder: &mut dyn Decoder,
650        input: &[u8],
651        chunk: usize,
652    ) -> Result<AudioBuffer, DecodeError> {
653        let mut samples = Vec::new();
654        for piece in input.chunks(chunk) {
655            let mut offset = 0;
656            while offset < piece.len() {
657                offset += decoder.feed(&piece[offset..])?;
658                while decoder.decode(&mut samples)? > 0 {}
659            }
660        }
661        decoder.flush(&mut samples)?;
662        Ok(AudioBuffer::from_samples(decoder.output_spec(), samples))
663    }
664
665    /// Every code, in order, as a byte slice.
666    fn all_codes() -> Vec<u8> {
667        (0..=u8::MAX).collect()
668    }
669
670    // -- Gate 5: exhaustive decode against the ITU table -------------------
671    //
672    // Path exercised: `code_to_linear`, i.e. the table itself. This is the
673    // complete input domain, all 256 codes per law, and it says nothing at
674    // all about the byte path, which gate 8 covers separately.
675
676    /// All 256 mu-law codes against the ITU table, exact.
677    #[test]
678    fn every_mu_law_code_decodes_to_the_itu_table() {
679        for code in 0..=u8::MAX {
680            assert_eq!(
681                G711Law::MuLaw.code_to_linear(code),
682                reference_decode(G711Law::MuLaw, code),
683                "mu-law 0x{code:02x}"
684            );
685        }
686    }
687
688    /// All 256 A-law codes against the ITU table, exact.
689    #[test]
690    fn every_a_law_code_decodes_to_the_itu_table() {
691        for code in 0..=u8::MAX {
692            assert_eq!(
693                G711Law::ALaw.code_to_linear(code),
694                reference_decode(G711Law::ALaw, code),
695                "A-law 0x{code:02x}"
696            );
697        }
698    }
699
700    /// The published values, written as literals rather than derived from
701    /// anything.
702    ///
703    /// A reference that shares a misreading with the implementation agrees with
704    /// it perfectly, so these anchors are the outside check on both: silence,
705    /// the extremes and the two laws' well-known ranges.
706    #[test]
707    fn the_published_anchor_values_hold() {
708        // Silence. A G.711 file of 0x00 bytes is full-scale noise in both laws,
709        // which is the mistake this asymmetry exists to make visible.
710        assert_eq!(G711Law::MuLaw.code_to_linear(0xFF), 0);
711        assert_eq!(G711Law::ALaw.code_to_linear(0xD5), 8);
712        assert_eq!(G711Law::ALaw.code_to_linear(0x55), -8);
713
714        // The ranges: mu-law reaches +/-32124, A-law +/-32256. Neither reaches
715        // i16::MAX, and they do not reach the same place as each other.
716        assert_eq!(G711Law::MuLaw.code_to_linear(0x80), 32_124);
717        assert_eq!(G711Law::MuLaw.code_to_linear(0x00), -32_124);
718        assert_eq!(G711Law::ALaw.code_to_linear(0xAA), 32_256);
719        assert_eq!(G711Law::ALaw.code_to_linear(0x2A), -32_256);
720
721        // The step at the bottom of each law: A-law's first segment steps by 16
722        // in the 16-bit domain, mu-law's by 8.
723        assert_eq!(G711Law::ALaw.code_to_linear(0xD4), 24);
724        assert_eq!(G711Law::MuLaw.code_to_linear(0xFE), 8);
725
726        // And the two laws genuinely differ: decoding one as the other is
727        // wrong, not merely differently scaled.
728        assert_ne!(
729            G711Law::MuLaw.code_to_linear(0x00),
730            G711Law::ALaw.code_to_linear(0x00)
731        );
732    }
733
734    // -- Gate 6: exhaustive encode against the ITU table -------------------
735    //
736    // Path exercised: `linear_to_code`. Also the complete input domain: all
737    // 65,536 i16 values per law.
738
739    /// The reference's own gate. If the 256 quantisation intervals did not tile
740    /// the 16-bit domain exactly once, the reference would be wrong and every
741    /// encode assertion built on it would be worthless.
742    #[test]
743    fn the_reference_intervals_tile_the_whole_16_bit_domain() {
744        // `reference_encode_table` panics on an overlap or a gap; reaching the
745        // end is the assertion.
746        for law in BOTH {
747            let table = reference_encode_table(law);
748            assert_eq!(table.len(), 65_536);
749        }
750
751        // A-law can emit all 256 codes. mu-law can emit 255: its second zero is
752        // a negative code whose interval lies wholly on the positive side, so
753        // no input reaches it.
754        let emitted = |law| {
755            (0..=u8::MAX)
756                .filter(|&code| reference_input_range(law, code).is_some())
757                .count()
758        };
759        assert_eq!(emitted(G711Law::ALaw), 256);
760        assert_eq!(emitted(G711Law::MuLaw), 255);
761        assert!(reference_input_range(G711Law::MuLaw, 0x7F).is_none());
762    }
763
764    /// All 65,536 `i16` values per law against the reference, exact.
765    #[test]
766    fn every_i16_encodes_to_the_itu_code_in_both_laws() {
767        for law in BOTH {
768            let table = reference_encode_table(law);
769            for sample in i16::MIN..=i16::MAX {
770                assert_eq!(
771                    law.linear_to_code(sample),
772                    reference_encode(&table, sample),
773                    "{law:?} on {sample}"
774                );
775            }
776        }
777    }
778
779    /// The extremes and the clamp, stated separately from the sweep so the
780    /// failure names the case rather than the first of 65,536.
781    #[test]
782    fn the_encoder_is_total_and_clamps_rather_than_wrapping() {
783        for law in BOTH {
784            // The extremes land on the extreme codes, not somewhere in the
785            // middle of the table.
786            assert_eq!(
787                law.code_to_linear(law.linear_to_code(i16::MAX)).signum(),
788                1,
789                "{law:?} sent i16::MAX negative"
790            );
791            assert_eq!(
792                law.code_to_linear(law.linear_to_code(i16::MIN)).signum(),
793                -1,
794                "{law:?} sent i16::MIN positive"
795            );
796            // Silence encodes to silence.
797            assert!(
798                law.code_to_linear(law.linear_to_code(0)).abs() <= 8,
799                "{law:?} did not put silence at the bottom of the table"
800            );
801        }
802        assert_eq!(G711Law::MuLaw.linear_to_code(0), 0xFF);
803        assert_eq!(G711Law::ALaw.linear_to_code(0), 0xD5);
804        assert_eq!(G711Law::MuLaw.linear_to_code(i16::MAX), 0x80);
805        assert_eq!(G711Law::MuLaw.linear_to_code(i16::MIN), 0x00);
806        assert_eq!(G711Law::ALaw.linear_to_code(i16::MAX), 0xAA);
807        assert_eq!(G711Law::ALaw.linear_to_code(i16::MIN), 0x2A);
808    }
809
810    // -- Gate 7: idempotence -----------------------------------------------
811    //
812    // Path exercised: `code_to_linear` and `linear_to_code` together.
813
814    /// G.711 is lossy, so a round trip is not the identity. A *second* pass
815    /// must cost nothing: encoding, decoding and encoding again returns the
816    /// code the first encode produced. A codec failing this loses information
817    /// on every pass rather than only on the first.
818    ///
819    /// The one exception is mu-law's second zero, `0x7F`. The recommendation
820    /// gives mu-law two codes for silence and the encoder can only emit one of
821    /// them, because a two's-complement zero has no sign to carry. `0x7F` is
822    /// therefore not in the encoder's image, and re-encoding it yields its twin
823    /// `0xFF`. Nothing is lost, since both decode to `0`, but it is a real
824    /// departure from the property, stated here rather than smoothed over.
825    #[test]
826    fn re_encoding_a_decoded_code_returns_it_except_for_mu_laws_second_zero() {
827        for law in BOTH {
828            for code in 0..=u8::MAX {
829                let linear = law.code_to_linear(code);
830                let again = law.linear_to_code(linear);
831
832                // The information-preserving form, which holds for all 256
833                // codes of both laws with no exception at all.
834                assert_eq!(
835                    law.code_to_linear(again),
836                    linear,
837                    "{law:?} 0x{code:02x} lost information on a second pass"
838                );
839
840                if law == G711Law::MuLaw && code == 0x7F {
841                    assert_eq!(again, 0xFF, "mu-law's second zero must fold onto 0xFF");
842                    assert_eq!(linear, 0, "mu-law's second zero must be silence");
843                } else {
844                    assert_eq!(
845                        again, code,
846                        "{law:?} 0x{code:02x} is not its own fixed point"
847                    );
848                }
849            }
850        }
851    }
852
853    /// Idempotence from the other end: for every `i16`, encoding twice with a
854    /// decode in between gives the same code. This is the property a repeated
855    /// transcode actually depends on.
856    #[test]
857    fn a_second_encode_of_any_sample_returns_the_first_code() {
858        for law in BOTH {
859            for sample in i16::MIN..=i16::MAX {
860                let first = law.linear_to_code(sample);
861                let again = law.linear_to_code(law.code_to_linear(first));
862                assert_eq!(again, first, "{law:?} on {sample}");
863            }
864        }
865    }
866
867    // -- Gate 8: the byte path, exercised separately from the table --------
868    //
869    // Paths exercised: `G711Law::decode`, `G711Law::encode` and
870    // `G711Decoder::{feed, decode, flush}`. These gates would pass with the
871    // table completely broken and the table gates would pass with these
872    // completely broken, which is exactly why both exist. Step 2's negative
873    // control lived in a byte path that its strongest table gate never touched.
874
875    /// The slice decode API against the scalar table, code by code, at several
876    /// chunk sizes and offsets. Any reordering, duplication or skipped byte in
877    /// the loop shows up here and nowhere in gate 5.
878    #[test]
879    fn the_slice_decode_api_matches_the_scalar_path() {
880        let codes = all_codes();
881        for law in BOTH {
882            let expected: Vec<f32> = codes
883                .iter()
884                .map(|&code| i16_to_f32(law.code_to_linear(code)))
885                .collect();
886
887            // In one call.
888            let mut whole = Vec::new();
889            assert_eq!(law.decode(&codes, &mut whole), codes.len());
890            assert_eq!(whole, expected, "{law:?} in one call");
891
892            // And split at every size that lands on a different set of
893            // boundaries, appending into the same vector each time.
894            for chunk in [1, 2, 3, 5, 7, 17, 128, 255] {
895                let mut pieced = Vec::new();
896                for piece in codes.chunks(chunk) {
897                    assert_eq!(law.decode(piece, &mut pieced), piece.len());
898                }
899                assert_eq!(pieced, expected, "{law:?} in {chunk}-byte pieces");
900            }
901        }
902    }
903
904    /// The slice encode API against the scalar path, sample by sample.
905    #[test]
906    fn the_slice_encode_api_matches_the_scalar_path() {
907        // A signal built from integer arithmetic, so it is the same everywhere,
908        // and reaching past full scale so the clamp is on the path too.
909        let samples: Vec<f32> = (-600..=600)
910            .map(|i| i as f32 / 512.0)
911            .chain([f32::NAN, f32::INFINITY, f32::NEG_INFINITY])
912            .collect();
913        for law in BOTH {
914            let expected: Vec<u8> = samples
915                .iter()
916                .map(|&sample| law.linear_to_code(f32_to_i16(sample)))
917                .collect();
918
919            let mut whole = Vec::new();
920            assert_eq!(law.encode(&samples, &mut whole), samples.len());
921            assert_eq!(whole, expected, "{law:?} in one call");
922
923            for chunk in [1, 3, 7, 64] {
924                let mut pieced = Vec::new();
925                for piece in samples.chunks(chunk) {
926                    assert_eq!(law.encode(piece, &mut pieced), piece.len());
927                }
928                assert_eq!(pieced, expected, "{law:?} in {chunk}-sample pieces");
929            }
930        }
931    }
932
933    /// The decoder's byte path, `feed` and `decode` on a slice, against the
934    /// scalar path, at several feed sizes.
935    ///
936    /// This is the gate that would have caught step 2's defect: the exhaustive
937    /// table gate above never touches `feed`, and `feed` could drop, duplicate
938    /// or reorder bytes with the table perfectly correct.
939    #[test]
940    fn the_decoder_byte_path_matches_the_scalar_path_at_every_chunk_size() {
941        let codes = all_codes();
942        for law in BOTH {
943            let expected: Vec<f32> = codes
944                .iter()
945                .map(|&code| i16_to_f32(law.code_to_linear(code)))
946                .collect();
947            for chunk in [1, 2, 3, 5, 7, 17, 128, 255, 256, 1024] {
948                let mut decoder = G711Decoder::new(law, AudioSpec::mono(16_000));
949                let decoded = drive(&mut decoder, &codes, chunk).expect("decode");
950                assert_eq!(
951                    decoded.samples(),
952                    expected.as_slice(),
953                    "{law:?} changed with a {chunk}-byte feed size"
954                );
955            }
956        }
957    }
958
959    /// The bytes arrive in the order they were fed. A path that decoded each
960    /// chunk correctly but assembled the chunks wrongly passes every assertion
961    /// about individual codes and fails this one.
962    #[test]
963    fn the_decoder_preserves_byte_order_across_feeds() {
964        let mut decoder = G711Decoder::new(G711Law::ALaw, AudioSpec::mono(8_000));
965        let mut out = Vec::new();
966        for code in [0xD5_u8, 0x2A, 0xAA, 0x55] {
967            assert_eq!(decoder.feed(&[code]).expect("feed"), 1);
968            assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
969        }
970        decoder.flush(&mut out).expect("flush");
971        assert_eq!(
972            out,
973            [
974                8.0 / 32768.0,
975                -32_256.0 / 32768.0,
976                32_256.0 / 32768.0,
977                -8.0 / 32768.0
978            ]
979        );
980    }
981
982    /// Back-pressure: a caller that hands over more than the decoder will hold
983    /// gets a short return and has to drain. Nothing is lost and the loop still
984    /// terminates.
985    ///
986    /// This is the only gate that exercises `feed`'s short-return path, which
987    /// makes it the only gate standing between a caller and silently dropped
988    /// audio on a whole-file feed.
989    #[test]
990    fn a_full_decoder_applies_back_pressure_instead_of_growing() {
991        let law = G711Law::MuLaw;
992        let mut decoder = G711Decoder::new(law, AudioSpec::mono(16_000));
993        // Three times what the decoder will hold, so the short return is
994        // unavoidable rather than incidental.
995        let bytes: Vec<u8> = (0..READY_LIMIT * 3).map(|i| (i % 256) as u8).collect();
996
997        let first = decoder.feed(&bytes).expect("feed");
998        assert!(first < bytes.len(), "a full decoder must return short");
999        assert_eq!(first, READY_LIMIT);
1000        assert_eq!(decoder.feed(&bytes[first..]).expect("feed"), 0);
1001
1002        let decoded = drive(&mut decoder, &bytes, bytes.len()).expect("decode");
1003        // The first feed's samples are still in there, ahead of the rest, and
1004        // every byte of the second pass is accounted for.
1005        assert_eq!(decoded.samples().len(), bytes.len() + first);
1006        let expected: Vec<f32> = bytes
1007            .iter()
1008            .map(|&code| i16_to_f32(law.code_to_linear(code)))
1009            .collect();
1010        assert_eq!(&decoded.samples()[..first], &expected[..first]);
1011        assert_eq!(&decoded.samples()[first..], expected.as_slice());
1012    }
1013
1014    /// The documented caller loop over an input larger than the decoder will
1015    /// hold, end to end: every byte arrives, in order, and none is lost to the
1016    /// short return.
1017    ///
1018    /// This exists because of what the byte-path negative control measured. A
1019    /// `feed` that decodes the right prefix but reports the whole input as
1020    /// consumed loses every byte past the limit, and *nothing else in this file
1021    /// notices*: the 256-code table gates, the 65,536-value encode gate and the
1022    /// chunk-size gate all use inputs far below `READY_LIMIT`, so the
1023    /// short-return path never runs. One gate standing between a caller and
1024    /// silently dropped audio is one too few, so this is the second.
1025    #[test]
1026    fn a_whole_file_feed_loses_nothing_to_the_short_return() {
1027        // Deliberately not a multiple of READY_LIMIT: the last partial pass
1028        // through the limit is where an off-by-one would sit.
1029        let bytes: Vec<u8> = (0..READY_LIMIT * 2 + 7).map(|i| (i % 251) as u8).collect();
1030        for law in BOTH {
1031            let expected: Vec<f32> = bytes
1032                .iter()
1033                .map(|&code| i16_to_f32(law.code_to_linear(code)))
1034                .collect();
1035            // Fed in one call, so every byte past the first limit has to come
1036            // back through a short return.
1037            let mut decoder = G711Decoder::new(law, AudioSpec::mono(8_000));
1038            let decoded = drive(&mut decoder, &bytes, bytes.len()).expect("decode");
1039            assert_eq!(
1040                decoded.samples(),
1041                expected.as_slice(),
1042                "{law:?} lost or reordered bytes on a whole-file feed"
1043            );
1044        }
1045    }
1046
1047    // -- Gate 9: frame straddling ------------------------------------------
1048    //
1049    // Path exercised: `G711Decoder::{flush, buffered_bytes}`.
1050
1051    /// A stereo stream that ends after an odd number of bytes ended mid-frame.
1052    /// One byte per sample means there is no straddling *sample* to hold, but
1053    /// there is still a straddling *frame*, and reporting it clean would hand
1054    /// back a buffer whose length is not a whole number of frames.
1055    #[test]
1056    fn a_stereo_stream_ending_mid_frame_is_truncated() {
1057        let mut decoder = G711Decoder::new(G711Law::MuLaw, AudioSpec::new(8_000, 2));
1058        let mut out = Vec::new();
1059        decoder.feed(&[0xFF]).expect("feed");
1060        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
1061        assert_eq!(
1062            decoder.buffered_bytes(),
1063            1,
1064            "one sample into a 2-byte frame"
1065        );
1066
1067        let error = decoder.flush(&mut out).expect_err("flush must reject");
1068        assert!(
1069            matches!(
1070                error,
1071                DecodeError::Truncated {
1072                    expected: 2,
1073                    available: 1
1074                }
1075            ),
1076            "unexpected error: {error}"
1077        );
1078        // Idempotent: the second flush is a quiet no-op, not a second error.
1079        assert_eq!(decoder.flush(&mut out).expect("second flush"), 0);
1080
1081        // And the same stream one byte longer ends cleanly.
1082        let mut decoder = G711Decoder::new(G711Law::MuLaw, AudioSpec::new(8_000, 2));
1083        let decoded = drive(&mut decoder, &[0xFF, 0x80], 1).expect("decode");
1084        assert_eq!(decoded.frames(), 1);
1085        assert_eq!(decoded.samples(), [0.0, 32_124.0 / 32768.0]);
1086    }
1087
1088    /// The same at wider layouts, at every position inside a frame, so the
1089    /// report is against the frame and not against whatever the last chunk
1090    /// happened to be.
1091    #[test]
1092    fn every_position_inside_a_frame_is_truncated_and_only_the_boundary_is_clean() {
1093        for channels in [2_u16, 3, 6] {
1094            for bytes in 1..=(channels * 2) {
1095                let mut decoder = G711Decoder::new(G711Law::ALaw, AudioSpec::new(48_000, channels));
1096                let input = vec![0xD5_u8; usize::from(bytes)];
1097                let result = drive(&mut decoder, &input, 4);
1098                if bytes % channels == 0 {
1099                    let decoded = result.expect("a whole number of frames must decode");
1100                    assert_eq!(decoded.frames(), usize::from(bytes / channels));
1101                } else {
1102                    let error = result.expect_err("a partial frame must reject");
1103                    assert!(
1104                        matches!(
1105                            error,
1106                            DecodeError::Truncated { expected, available }
1107                                if expected == u64::from(channels)
1108                                    && available == u64::from(bytes % channels)
1109                        ),
1110                        "{channels} channels, {bytes} bytes: unexpected error: {error}"
1111                    );
1112                }
1113            }
1114        }
1115    }
1116
1117    // -- The decoder's remaining contract ----------------------------------
1118
1119    #[test]
1120    fn a_headerless_g711_stream_decodes_at_the_spec_it_was_given() {
1121        let mut decoder = G711Decoder::new(G711Law::ALaw, AudioSpec::mono(8_000));
1122        assert_eq!(decoder.law(), G711Law::ALaw);
1123        assert_eq!(decoder.output_spec(), AudioSpec::mono(8_000));
1124
1125        let decoded = drive(&mut decoder, &[0xD5, 0x55, 0xAA, 0x2A], 64).expect("decode");
1126        assert_eq!(
1127            decoded.samples(),
1128            [
1129                8.0 / 32768.0,
1130                -8.0 / 32768.0,
1131                32_256.0 / 32768.0,
1132                -32_256.0 / 32768.0
1133            ]
1134        );
1135        assert_eq!(decoded.sample_rate(), 8_000);
1136        assert_eq!(decoded.frames(), 4);
1137    }
1138
1139    /// The rate is the caller's and nothing here defaults to telephony's 8 kHz.
1140    /// G.711 is a sample format, not a rate.
1141    #[test]
1142    fn the_rate_is_whatever_the_spec_says_and_never_assumed() {
1143        for rate in [8_000, 16_000, 44_100, 48_000, 192_000, 1] {
1144            let mut decoder = G711Decoder::new(G711Law::MuLaw, AudioSpec::mono(rate));
1145            let decoded = drive(&mut decoder, &[0xFF, 0xFF], 1).expect("decode");
1146            assert_eq!(decoded.sample_rate(), rate);
1147            // The samples do not depend on the rate either.
1148            assert_eq!(decoded.samples(), [0.0, 0.0]);
1149        }
1150    }
1151
1152    /// The sample-count guarantee, stated for this decoder: `n` frames in,
1153    /// exactly `n * channels` samples out, whatever the feed size.
1154    #[test]
1155    fn the_sample_count_is_exact_for_every_layout() {
1156        for law in BOTH {
1157            for channels in [1_u16, 2, 6] {
1158                let frames = 50;
1159                let spec = AudioSpec::new(48_000, channels);
1160                let count = frames * usize::from(channels);
1161                let input: Vec<u8> = (0..count).map(|i| (i % 256) as u8).collect();
1162                let mut decoder = G711Decoder::new(law, spec);
1163                let decoded = drive(&mut decoder, &input, 13).expect("decode");
1164                assert_eq!(
1165                    decoded.samples().len(),
1166                    count,
1167                    "{law:?} at {channels} channels produced the wrong count"
1168                );
1169                assert_eq!(decoded.frames(), frames);
1170            }
1171        }
1172    }
1173
1174    /// A starved decoder says `0`, which means "feed me", not "end of stream".
1175    #[test]
1176    fn a_starved_decoder_reports_zero_rather_than_end_of_stream() {
1177        let mut decoder = G711Decoder::new(G711Law::ALaw, AudioSpec::mono(16_000));
1178        let mut out = Vec::new();
1179        assert_eq!(decoder.decode(&mut out).expect("decode"), 0);
1180        assert!(out.is_empty());
1181        assert_eq!(decoder.feed(&[]).expect("empty feed"), 0);
1182        assert_eq!(decoder.decode(&mut out).expect("decode"), 0);
1183        assert_eq!(decoder.feed(&[0xD5]).expect("feed"), 1);
1184        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
1185    }
1186
1187    #[test]
1188    fn feeding_after_flush_is_quiet_until_reset() {
1189        let mut decoder = G711Decoder::new(G711Law::MuLaw, AudioSpec::mono(8_000));
1190        let mut out = Vec::new();
1191        assert_eq!(decoder.flush(&mut out).expect("flush"), 0);
1192        assert_eq!(decoder.flush(&mut out).expect("second flush"), 0);
1193        assert_eq!(decoder.feed(&[0xFF]).expect("feed"), 0);
1194        assert_eq!(decoder.decode(&mut out).expect("decode"), 0);
1195        assert!(out.is_empty());
1196
1197        decoder.reset();
1198        assert_eq!(decoder.feed(&[0x80]).expect("feed"), 1);
1199        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
1200        assert_eq!(out, [32_124.0 / 32768.0]);
1201    }
1202
1203    /// `reset` drops the frame position, so the next stream starts on a
1204    /// boundary rather than inheriting one.
1205    #[test]
1206    fn reset_drops_the_frame_position() {
1207        let mut decoder = G711Decoder::new(G711Law::MuLaw, AudioSpec::new(16_000, 2));
1208        decoder.feed(&[0xFF]).expect("feed");
1209        assert_eq!(decoder.buffered_bytes(), 1);
1210        decoder.reset();
1211        assert_eq!(decoder.buffered_bytes(), 0);
1212        let mut out = Vec::new();
1213        assert_eq!(decoder.flush(&mut out).expect("flush after reset"), 0);
1214    }
1215
1216    #[test]
1217    fn the_decoder_is_object_safe_and_sendable() {
1218        fn assert_send<T: Send>() {}
1219        assert_send::<G711Decoder>();
1220
1221        let boxed: Box<dyn Decoder> =
1222            Box::new(G711Decoder::new(G711Law::ALaw, AudioSpec::new(44_100, 2)));
1223        assert_eq!(boxed.output_spec().channels, 2);
1224    }
1225
1226    /// A spec with no channels is degenerate but must not divide by zero.
1227    #[test]
1228    fn a_zero_channel_spec_does_not_divide_by_zero() {
1229        let mut decoder = G711Decoder::new(G711Law::MuLaw, AudioSpec::new(16_000, 0));
1230        let mut out = Vec::new();
1231        decoder.feed(&[0xFF]).expect("feed");
1232        assert_eq!(decoder.decode(&mut out).expect("decode"), 1);
1233        assert_eq!(decoder.buffered_bytes(), 0);
1234        assert_eq!(decoder.flush(&mut out).expect("flush"), 0);
1235    }
1236
1237    // -- Gate 10: cross-platform determinism -------------------------------
1238
1239    /// FNV-1a over the little-endian bit patterns, so the witness is the bytes
1240    /// themselves and not a float comparison.
1241    fn fnv1a(bytes: impl IntoIterator<Item = u8>) -> u64 {
1242        let mut hash = 0xcbf2_9ce4_8422_2325_u64;
1243        for byte in bytes {
1244            hash ^= u64::from(byte);
1245            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
1246        }
1247        hash
1248    }
1249
1250    /// One number that changes if any bit of any decoded sample or encoded code
1251    /// changes, over the complete code domain and a fixed signal.
1252    ///
1253    /// Running this on two toolchains and getting the same constant is the
1254    /// evidence for the byte-identical claim; a tolerance-based test would pass
1255    /// on both while the outputs differed. The constant is pinned rather than
1256    /// recomputed at run time so that a change shows up as a diff in this file.
1257    ///
1258    /// Both directions and both paths are in the hash: decode goes through the
1259    /// decoder's `feed`, so a byte-path change moves the constant too.
1260    #[test]
1261    fn g711_output_is_bit_identical_to_a_pinned_witness() {
1262        let codes = all_codes();
1263        // Integer arithmetic and an exact division by a power of two, so the
1264        // signal is the same on every target. The tail is past full scale, so
1265        // the clamp is inside the witness.
1266        let signal: Vec<f32> = (-2048..=2048)
1267            .map(|i| i as f32 / 2048.0)
1268            .chain([1.5, -3.0])
1269            .collect();
1270
1271        let mut bytes: Vec<u8> = Vec::new();
1272        for law in BOTH {
1273            let mut decoder = G711Decoder::new(law, AudioSpec::mono(16_000));
1274            // 7 is coprime with every chunk size that matters here, so the
1275            // decoder is driven across its short-feed path as well.
1276            let decoded = drive(&mut decoder, &codes, 7).expect("decode");
1277            bytes.extend(
1278                decoded
1279                    .samples()
1280                    .iter()
1281                    .flat_map(|s| s.to_bits().to_le_bytes()),
1282            );
1283            law.encode(&signal, &mut bytes);
1284        }
1285        assert_eq!(bytes.len(), 2 * (256 * 4 + signal.len()));
1286        assert_eq!(fnv1a(bytes), 0x81b6_c667_9170_0ce0, "G.711 output changed");
1287    }
1288}