Skip to main content

gemini_adk_fluent_rs/telephony/
g711.rs

1//! G.711 μ-law and A-law codecs — the audio dialect of the public phone
2//! network.
3//!
4//! Every PSTN leg (Twilio Media Streams, SIP trunks, carrier gateways)
5//! delivers 8 kHz audio in one of these two companding formats: μ-law in
6//! North America and Japan, A-law nearly everywhere else. Both pack a
7//! 14/13-bit linear sample into one logarithmically-companded byte.
8//!
9//! The functions here are pure, allocation-explicit, and implement ITU-T
10//! G.711 directly (bit manipulation, no tables to drift): encode from mono
11//! PCM16, decode back to mono PCM16. Pair them with
12//! [`resample`](crate::voice::resample) to move between the 8 kHz telephone
13//! rate and the Live API's 16 kHz-in / 24 kHz-out contract.
14
15/// Encode one linear PCM16 sample as a μ-law byte (ITU-T G.711).
16///
17/// The rule is ITU-T G.191's `ulaw_compress` (the STL reference
18/// implementation of G.711): the 16-bit sample is taken to the 14-bit
19/// domain with an arithmetic shift, a negative sample's magnitude is its
20/// one's complement (so `-1` encodes as negative zero, `0x7F`, and `-4` as
21/// the first negative step), the bias of 33 is added, and the segment and
22/// mantissa are read off the biased value. Bit-exact with G.191 for every
23/// input (`reference_tests`). The Sun `g711.c` formulation used by sox and
24/// Asterisk negates instead of complementing and differs from G.191 by one
25/// code at negative step boundaries; decoders agree on both.
26pub fn linear_to_ulaw(sample: i16) -> u8 {
27    const BIAS: i32 = 33; // the G.711 bias (0x84) in the 14-bit domain
28    const CLIP: i32 = 0x1FFF;
29
30    let value = i32::from(sample);
31    let absno = if value < 0 { (!value) >> 2 } else { value >> 2 } + BIAS;
32    let absno = absno.min(CLIP);
33    // Segment: one plus the number of significant bits above the lowest six.
34    let segno = 1 + (32 - (absno >> 6).leading_zeros()) as i32;
35    let high_nibble = 8 - segno;
36    let low_nibble = 0x0F - ((absno >> segno) & 0x0F);
37    let byte = ((high_nibble << 4) | low_nibble) as u8;
38    // The sign bit is set for non-negative samples (all-ones is silence).
39    if value >= 0 { byte | 0x80 } else { byte }
40}
41
42/// Decode one μ-law byte to a linear PCM16 sample (ITU-T G.711).
43pub fn ulaw_to_linear(byte: u8) -> i16 {
44    let byte = !byte;
45    let sign = byte & 0x80;
46    let segment = (byte >> 4) & 0x07;
47    let mantissa = byte & 0x0F;
48
49    let magnitude = ((((mantissa as i32) << 3) + 0x84) << segment) - 0x84;
50    if sign != 0 {
51        -magnitude as i16
52    } else {
53        magnitude as i16
54    }
55}
56
57/// Encode one linear PCM16 sample as an A-law byte (ITU-T G.711).
58///
59/// G.711 defines the encoder on a 13-bit input; the 16-bit sample is taken
60/// to that domain with an arithmetic shift and a negative sample's
61/// magnitude is `-v - 1`, which equals the one's complement ITU-T G.191's
62/// `alaw_compress` takes. Bit-exact with G.191 for every input
63/// (`reference_tests`).
64pub fn linear_to_alaw(sample: i16) -> u8 {
65    // Upper bound of each segment in the 13-bit domain.
66    const SEG_END: [i32; 8] = [0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF];
67
68    let value = i32::from(sample) >> 3;
69    // A-law XORs alternate bits on the wire (0x55), and the sign bit is set
70    // for non-negative samples: the two masks fold both into one XOR.
71    let (magnitude, mask) = if value >= 0 {
72        (value, 0xD5u8)
73    } else {
74        (-value - 1, 0x55u8)
75    };
76    let segment = SEG_END.iter().position(|&end| magnitude <= end);
77    let Some(segment) = segment else {
78        return 0x7F ^ mask;
79    };
80    let shift = if segment < 2 { 1 } else { segment };
81    let mantissa = ((magnitude >> shift) & 0x0F) as u8;
82    (((segment as u8) << 4) | mantissa) ^ mask
83}
84
85/// Decode one A-law byte to a linear PCM16 sample (ITU-T G.711).
86pub fn alaw_to_linear(byte: u8) -> i16 {
87    let byte = byte ^ 0x55;
88    let sign = byte & 0x80;
89    let segment = (byte >> 4) & 0x07;
90    let mantissa = (byte & 0x0F) as i32;
91
92    let magnitude = match segment {
93        0 => (mantissa << 4) + 8,
94        _ => ((mantissa << 4) + 0x108) << (segment - 1),
95    };
96    if sign != 0 {
97        magnitude as i16
98    } else {
99        -magnitude as i16
100    }
101}
102
103/// Decode a μ-law byte stream to mono PCM16 samples.
104pub fn decode_ulaw(bytes: &[u8]) -> Vec<i16> {
105    bytes.iter().map(|&b| ulaw_to_linear(b)).collect()
106}
107
108/// Encode mono PCM16 samples as a μ-law byte stream.
109pub fn encode_ulaw(samples: &[i16]) -> Vec<u8> {
110    samples.iter().map(|&s| linear_to_ulaw(s)).collect()
111}
112
113/// Decode an A-law byte stream to mono PCM16 samples.
114pub fn decode_alaw(bytes: &[u8]) -> Vec<i16> {
115    bytes.iter().map(|&b| alaw_to_linear(b)).collect()
116}
117
118/// Encode mono PCM16 samples as an A-law byte stream.
119pub fn encode_alaw(samples: &[i16]) -> Vec<u8> {
120    samples.iter().map(|&s| linear_to_alaw(s)).collect()
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn ulaw_silence_is_all_ones_on_the_wire() {
129        // The inverted encoding makes digital silence 0xFF — the classic
130        // "μ-law idle pattern".
131        assert_eq!(linear_to_ulaw(0), 0xFF);
132        assert_eq!(ulaw_to_linear(0xFF), 0);
133    }
134
135    #[test]
136    fn ulaw_known_extremes() {
137        // Full-scale positive clips to the largest positive code.
138        assert_eq!(ulaw_to_linear(linear_to_ulaw(32_767)), 32_124);
139        assert_eq!(ulaw_to_linear(linear_to_ulaw(-32_768)), -32_124);
140    }
141
142    #[test]
143    fn ulaw_round_trip_is_within_segment_quantisation() {
144        // Companding is lossy but monotone: error bounded by the segment's
145        // step size (≤ 1/16 of the magnitude, plus the smallest step).
146        for &s in &[0i16, 1, -1, 100, -100, 1000, -1000, 8000, -8000, 30000] {
147            let rt = ulaw_to_linear(linear_to_ulaw(s));
148            let tolerance = (s.unsigned_abs() as i32 / 16).max(16);
149            assert!(
150                ((rt as i32) - (s as i32)).abs() <= tolerance,
151                "sample {s} round-tripped to {rt}"
152            );
153        }
154    }
155
156    #[test]
157    fn ulaw_is_monotone() {
158        // Decoded values must never decrease as input increases — a codec
159        // that reorders amplitudes garbles speech even if errors are small.
160        let mut last = i16::MIN;
161        for s in (-32_768i32..=32_767).step_by(257) {
162            let rt = ulaw_to_linear(linear_to_ulaw(s as i16));
163            assert!(rt >= last, "non-monotone at input {s}");
164            last = rt;
165        }
166    }
167
168    #[test]
169    fn alaw_round_trip_is_within_segment_quantisation() {
170        for &s in &[0i16, 8, -8, 100, -100, 1000, -1000, 8000, -8000, 30000] {
171            let rt = alaw_to_linear(linear_to_alaw(s));
172            let tolerance = (s.unsigned_abs() as i32 / 16).max(24);
173            assert!(
174                ((rt as i32) - (s as i32)).abs() <= tolerance,
175                "sample {s} round-tripped to {rt}"
176            );
177        }
178    }
179
180    #[test]
181    fn alaw_is_monotone() {
182        let mut last = i16::MIN;
183        for s in (-32_768i32..=32_767).step_by(257) {
184            let rt = alaw_to_linear(linear_to_alaw(s as i16));
185            assert!(rt >= last, "non-monotone at input {s}");
186            last = rt;
187        }
188    }
189
190    #[test]
191    fn stream_helpers_round_trip_shape() {
192        let samples = vec![0i16, 500, -500, 12_000, -12_000];
193        assert_eq!(decode_ulaw(&encode_ulaw(&samples)).len(), samples.len());
194        assert_eq!(decode_alaw(&encode_alaw(&samples)).len(), samples.len());
195    }
196
197    #[test]
198    fn ulaw_segment_boundaries() {
199        // Test round-trip accuracy at segment transitions (where step size changes)
200        // Segment boundaries in μ-law are at magnitudes where probe changes (256, 512, 1024, ...)
201        for &boundary in &[256i16, 512, 1024, 2048, 4096, 8192, 16384] {
202            for offset in &[-1i32, 0, 1] {
203                let s = (boundary as i32 + offset) as i16;
204                let rt = ulaw_to_linear(linear_to_ulaw(s));
205                let tolerance = (s.unsigned_abs() as i32 / 16).max(16);
206                assert!(
207                    ((rt as i32) - (s as i32)).abs() <= tolerance,
208                    "sample {s} at boundary round-tripped to {rt}, error exceeds tolerance"
209                );
210            }
211        }
212    }
213
214    #[test]
215    fn alaw_segment_boundaries() {
216        // Test round-trip accuracy at segment transitions in A-law
217        // A-law segment 0 spans magnitude 0-255, then transitions to segment 1
218        for &boundary in &[256i16, 512, 1024, 2048, 4096, 8192, 16384] {
219            for offset in &[-1i32, 0, 1] {
220                let s = (boundary as i32 + offset) as i16;
221                let rt = alaw_to_linear(linear_to_alaw(s));
222                let tolerance = (s.unsigned_abs() as i32 / 16).max(24);
223                assert!(
224                    ((rt as i32) - (s as i32)).abs() <= tolerance,
225                    "alaw sample {s} at boundary round-tripped to {rt}, error exceeds tolerance"
226                );
227            }
228        }
229    }
230
231    #[test]
232    fn ulaw_all_mantissas_per_segment() {
233        // Verify each mantissa value (0-15) in each segment (0-7) codes/decodes correctly
234        for segment in 0u8..=7 {
235            for mantissa in 0u8..=15 {
236                // Reconstruct the encoded byte: !(sign | segment<<4 | mantissa)
237                let encoded = !((segment << 4) | mantissa);
238                let decoded = ulaw_to_linear(encoded);
239                // Re-encode to verify round-trip consistency
240                let re_encoded = linear_to_ulaw(decoded);
241                assert_eq!(
242                    re_encoded, encoded,
243                    "mantissa {mantissa} in segment {segment}: round-trip mismatch"
244                );
245            }
246        }
247    }
248
249    #[test]
250    fn alaw_all_mantissas_per_segment() {
251        // Verify A-law mantissas (0-15) in each segment (0-7) code/decode correctly
252        for segment in 0u8..=7 {
253            for mantissa in 0u8..=15 {
254                // Reconstruct the encoded byte per A-law spec
255                let compressed = (segment << 4) | mantissa;
256                let encoded = (0x80 | compressed) ^ 0x55; // with sign bit + XOR
257                let decoded = alaw_to_linear(encoded);
258                // Re-encode to verify consistency
259                let re_encoded = linear_to_alaw(decoded);
260                assert_eq!(
261                    re_encoded, encoded,
262                    "alaw mantissa {mantissa} in segment {segment}: round-trip mismatch"
263                );
264            }
265        }
266    }
267
268    /// μ-law's sign symmetry is G.191's, not naive negation: a negative
269    /// sample's magnitude is its one's complement, so `-x` encodes as the
270    /// mirror of `x - 1`, and the round trip of `-x` is the negation of the
271    /// round trip of `x - 1`.
272    #[test]
273    fn ulaw_negative_values_mirror_the_reference() {
274        for x in 1..=i16::MAX {
275            assert_eq!(
276                linear_to_ulaw(-x) ^ 0x80,
277                linear_to_ulaw(x - 1),
278                "μ-law mirror relation at {x}"
279            );
280            assert_eq!(
281                i32::from(ulaw_to_linear(linear_to_ulaw(-x))),
282                -i32::from(ulaw_to_linear(linear_to_ulaw(x - 1))),
283                "μ-law round-trip mirror at {x}"
284            );
285        }
286    }
287
288    /// A-law's sign symmetry is the reference's, not naive negation: a
289    /// two's-complement input has no negative zero, so `-x` encodes as the
290    /// mirror of `x - 1` (ITU-T G.191 `alaw_compress` takes `~x`, the Sun
291    /// reference `-x - 1`). At an exact segment boundary such as ±256 the
292    /// two reconstructions therefore differ by one step (264 and -248), and
293    /// the decoder is exactly odd: mirrored codes decode to negated values.
294    #[test]
295    fn alaw_negative_values_mirror_the_reference() {
296        for x in 1..=i16::MAX {
297            assert_eq!(
298                linear_to_alaw(-x) ^ 0x80,
299                linear_to_alaw(x - 1),
300                "A-law: -{x} must mirror {}",
301                x - 1
302            );
303        }
304        for byte in 0..=u8::MAX {
305            assert_eq!(
306                i32::from(alaw_to_linear(byte ^ 0x80)),
307                -i32::from(alaw_to_linear(byte)),
308                "A-law decoder must be odd at byte {byte:#04x}"
309            );
310        }
311        // Away from a boundary the round trips are still negatives of each
312        // other, which is what a listener hears.
313        for &abs_val in &[100i16, 1000, 8000, 20000] {
314            let pos_rt = alaw_to_linear(linear_to_alaw(abs_val));
315            let neg_rt = alaw_to_linear(linear_to_alaw(-abs_val));
316            assert_eq!(i32::from(pos_rt) + i32::from(neg_rt), 0, "{abs_val}");
317        }
318    }
319
320    #[test]
321    fn ulaw_clipping_at_extremes() {
322        // Values beyond CLIP (32635) should clip to the same rounded value
323        let large_pos = ulaw_to_linear(linear_to_ulaw(32_767));
324        let large_pos2 = ulaw_to_linear(linear_to_ulaw(32_700));
325        assert_eq!(
326            large_pos, large_pos2,
327            "μ-law should clip large positive values to same result"
328        );
329
330        let large_neg = ulaw_to_linear(linear_to_ulaw(-32_768));
331        let large_neg2 = ulaw_to_linear(linear_to_ulaw(-32_700));
332        assert_eq!(
333            large_neg, large_neg2,
334            "μ-law should clip large negative values to same result"
335        );
336    }
337
338    #[test]
339    fn alaw_clipping_at_extremes() {
340        // A-law should also clip consistently
341        let large_pos = alaw_to_linear(linear_to_alaw(32_767));
342        let large_pos2 = alaw_to_linear(linear_to_alaw(32_700));
343        assert_eq!(
344            large_pos, large_pos2,
345            "A-law should clip large positive values to same result"
346        );
347
348        let large_neg = alaw_to_linear(linear_to_alaw(-32_768));
349        let large_neg2 = alaw_to_linear(linear_to_alaw(-32_700));
350        assert_eq!(
351            large_neg, large_neg2,
352            "A-law should clip large negative values to same result"
353        );
354    }
355}
356
357/// Comparison against a transcription of ITU-T G.191's `g711.c` (the STL
358/// reference implementation of G.711, version 3.01, fetched from the ITU's
359/// repository): every encoder and decoder is compared for every input, the
360/// decoders' outputs round-trip through the encoders, and a handful of
361/// literal pairs from the G.711 tables anchor both directions so a shared
362/// transcription error cannot pass.
363#[cfg(test)]
364mod reference_tests {
365    use super::*;
366
367    // ---- ITU-T G.191 g711.c, ulaw_compress ---------------------------------
368    // `short` arithmetic in the original; i32 here holds the same values.
369    fn g191_ulaw_compress(linbuf: i16) -> u8 {
370        let linbuf = i32::from(linbuf);
371        let mut absno = if linbuf < 0 {
372            ((!linbuf) >> 2) + 33
373        } else {
374            (linbuf >> 2) + 33
375        };
376        if absno > 0x1FFF {
377            absno = 0x1FFF;
378        }
379        let mut i = absno >> 6;
380        let mut segno = 1;
381        while i != 0 {
382            segno += 1;
383            i >>= 1;
384        }
385        let high_nibble = 0x0008 - segno;
386        let mut low_nibble = (absno >> segno) & 0x000F;
387        low_nibble = 0x000F - low_nibble;
388        let mut logbuf = (high_nibble << 4) | low_nibble;
389        if linbuf >= 0 {
390            logbuf |= 0x0080;
391        }
392        logbuf as u8
393    }
394
395    // ---- ITU-T G.191 g711.c, ulaw_expand ----------------------------------
396    fn g191_ulaw_expand(logbuf: u8) -> i16 {
397        let logbuf = i32::from(logbuf);
398        let sign = if logbuf < 0x0080 { -1 } else { 1 };
399        let mut mantissa = !logbuf;
400        let exponent = (mantissa >> 4) & 0x0007;
401        let segment = exponent + 1;
402        mantissa &= 0x000F;
403        let step = 4 << segment;
404        (sign * ((0x0080 << exponent) + step * mantissa + step / 2 - 4 * 33)) as i16
405    }
406
407    // ---- ITU-T G.191 g711.c, alaw_compress ---------------------------------
408    fn g191_alaw_compress(linbuf: i16) -> u8 {
409        let linbuf = i32::from(linbuf);
410        let mut ix = if linbuf < 0 {
411            (!linbuf) >> 4
412        } else {
413            linbuf >> 4
414        };
415        if ix > 15 {
416            let mut iexp = 1;
417            while ix > 16 + 15 {
418                ix >>= 1;
419                iexp += 1;
420            }
421            ix -= 16;
422            ix += iexp << 4;
423        }
424        if linbuf >= 0 {
425            ix |= 0x0080;
426        }
427        (ix ^ 0x0055) as u8
428    }
429
430    // ---- ITU-T G.191 g711.c, alaw_expand -----------------------------------
431    fn g191_alaw_expand(logbuf: u8) -> i16 {
432        let logbuf = i32::from(logbuf);
433        let mut ix = logbuf ^ 0x0055;
434        ix &= 0x007F;
435        let iexp = ix >> 4;
436        let mut mant = ix & 0x000F;
437        if iexp > 0 {
438            mant += 16;
439        }
440        mant = (mant << 4) + 0x0008;
441        if iexp > 1 {
442            mant <<= iexp - 1;
443        }
444        (if logbuf > 127 { mant } else { -mant }) as i16
445    }
446
447    fn disagreements(name: &str, f: impl Fn(i16) -> u8, g: impl Fn(i16) -> u8) {
448        let bad: Vec<String> = (i16::MIN..=i16::MAX)
449            .filter(|&s| f(s) != g(s))
450            .map(|s| format!("sample {s}: crate {:#04x} G.191 {:#04x}", f(s), g(s)))
451            .collect();
452        assert!(
453            bad.is_empty(),
454            "{name}: {} of 65536 disagree; first 20: {:#?}",
455            bad.len(),
456            &bad[..bad.len().min(20)]
457        );
458    }
459
460    #[test]
461    fn ulaw_encoder_matches_g191_for_every_i16() {
462        disagreements("ulaw", linear_to_ulaw, g191_ulaw_compress);
463    }
464
465    #[test]
466    fn alaw_encoder_matches_g191_for_every_i16() {
467        disagreements("alaw", linear_to_alaw, g191_alaw_compress);
468    }
469
470    #[test]
471    fn decoders_match_g191_for_every_byte() {
472        for b in 0..=u8::MAX {
473            assert_eq!(ulaw_to_linear(b), g191_ulaw_expand(b), "ulaw {b:#04x}");
474            assert_eq!(alaw_to_linear(b), g191_alaw_expand(b), "alaw {b:#04x}");
475        }
476    }
477
478    /// Every code's decoded value encodes back to the same code, except
479    /// μ-law negative zero (`0x7F`), which decodes to 0 and re-encodes as
480    /// positive zero (`0xFF`).
481    #[test]
482    fn decoded_values_round_trip_through_the_encoders() {
483        for b in 0..=u8::MAX {
484            assert_eq!(linear_to_alaw(alaw_to_linear(b)), b, "alaw {b:#04x}");
485            let expected = if b == 0x7F { 0xFF } else { b };
486            assert_eq!(linear_to_ulaw(ulaw_to_linear(b)), expected, "ulaw {b:#04x}");
487        }
488    }
489
490    /// Literal anchors from the G.711 tables (Table 2a/2b): full scale,
491    /// silence and the first steps, in both directions.
492    #[test]
493    fn known_ulaw_pairs() {
494        let decode: [(u8, i16); 6] = [
495            (0xFF, 0),       // positive zero: silence
496            (0x7F, 0),       // negative zero
497            (0x00, -32_124), // most negative
498            (0x80, 32_124),  // most positive
499            (0xFE, 8),       // first positive step
500            (0x7E, -8),      // first negative step
501        ];
502        for (byte, pcm) in decode {
503            assert_eq!(ulaw_to_linear(byte), pcm, "decode {byte:#04x}");
504        }
505        let encode: [(i16, u8); 7] = [
506            (0, 0xFF),
507            (32_767, 0x80),
508            (-32_768, 0x00),
509            (8, 0xFE),
510            (-8, 0x7E),
511            (-1, 0x7F), // one's complement: the smallest negative is negative zero
512            (-4, 0x7F), // ~(-4) >> 2 = 0: still negative zero; -8 is the first step
513        ];
514        for (pcm, byte) in encode {
515            assert_eq!(linear_to_ulaw(pcm), byte, "encode {pcm}");
516        }
517    }
518
519    #[test]
520    fn known_alaw_pairs() {
521        let decode: [(u8, i16); 6] = [
522            (0xD5, 8), // A-law silence byte
523            (0x55, -8),
524            (0xAA, 32_256),  // largest positive
525            (0x2A, -32_256), // largest negative
526            (0xD4, 24),
527            (0x54, -24),
528        ];
529        for (byte, pcm) in decode {
530            assert_eq!(alaw_to_linear(byte), pcm, "decode {byte:#04x}");
531        }
532        let encode: [(i16, u8); 5] = [
533            (0, 0xD5),
534            (32_767, 0xAA),
535            (-32_768, 0x2A),
536            (8, 0xD5),
537            (-8, 0x55),
538        ];
539        for (pcm, byte) in encode {
540            assert_eq!(linear_to_alaw(pcm), byte, "encode {pcm}");
541        }
542    }
543}