1pub fn linear_to_ulaw(sample: i16) -> u8 {
27 const BIAS: i32 = 33; 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 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 if value >= 0 { byte | 0x80 } else { byte }
40}
41
42pub 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
57pub fn linear_to_alaw(sample: i16) -> u8 {
65 const SEG_END: [i32; 8] = [0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF];
67
68 let value = i32::from(sample) >> 3;
69 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
85pub 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
103pub fn decode_ulaw(bytes: &[u8]) -> Vec<i16> {
105 bytes.iter().map(|&b| ulaw_to_linear(b)).collect()
106}
107
108pub fn encode_ulaw(samples: &[i16]) -> Vec<u8> {
110 samples.iter().map(|&s| linear_to_ulaw(s)).collect()
111}
112
113pub fn decode_alaw(bytes: &[u8]) -> Vec<i16> {
115 bytes.iter().map(|&b| alaw_to_linear(b)).collect()
116}
117
118pub 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 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 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 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 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 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 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 for segment in 0u8..=7 {
235 for mantissa in 0u8..=15 {
236 let encoded = !((segment << 4) | mantissa);
238 let decoded = ulaw_to_linear(encoded);
239 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 for segment in 0u8..=7 {
253 for mantissa in 0u8..=15 {
254 let compressed = (segment << 4) | mantissa;
256 let encoded = (0x80 | compressed) ^ 0x55; let decoded = alaw_to_linear(encoded);
258 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 #[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 #[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 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 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 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#[cfg(test)]
364mod reference_tests {
365 use super::*;
366
367 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 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 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 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 #[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 #[test]
493 fn known_ulaw_pairs() {
494 let decode: [(u8, i16); 6] = [
495 (0xFF, 0), (0x7F, 0), (0x00, -32_124), (0x80, 32_124), (0xFE, 8), (0x7E, -8), ];
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), (-4, 0x7F), ];
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), (0x55, -8),
524 (0xAA, 32_256), (0x2A, -32_256), (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}