rvoip-codec-core 0.2.2

G.711 and optional G.729A/G.729AB audio codec implementation for RVOIP
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! SIMD utilities for cross-platform optimizations
//!
//! This module provides SIMD capability detection and optimized operations
//! for audio processing across different architectures.

use std::sync::OnceLock;

/// SIMD support information
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SimdSupport {
    /// x86_64 SSE2 support
    pub sse2: bool,
    /// x86_64 AVX2 support
    pub avx2: bool,
    /// AArch64 NEON support
    pub neon: bool,
}

/// Global SIMD support detection
static SIMD_SUPPORT: OnceLock<SimdSupport> = OnceLock::new();

/// Initialize SIMD support detection
pub fn init_simd_support() {
    SIMD_SUPPORT.get_or_init(|| detect_simd_support());
}

/// Internal function to detect SIMD support
fn detect_simd_support() -> SimdSupport {
    #[cfg(target_arch = "x86_64")]
    {
        SimdSupport {
            sse2: is_x86_feature_detected!("sse2"),
            avx2: is_x86_feature_detected!("avx2"),
            neon: false,
        }
    }
    #[cfg(target_arch = "aarch64")]
    {
        SimdSupport {
            sse2: false,
            avx2: false,
            neon: std::arch::is_aarch64_feature_detected!("neon"),
        }
    }
    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
    {
        SimdSupport {
            sse2: false,
            avx2: false,
            neon: false,
        }
    }
}

/// Get SIMD support information
pub fn get_simd_support() -> SimdSupport {
    *SIMD_SUPPORT.get_or_init(|| detect_simd_support())
}

/// Check if any SIMD support is available
pub fn has_simd_support() -> bool {
    let support = get_simd_support();
    support.sse2 || support.avx2 || support.neon
}

/// SIMD-optimized μ-law encoding (x86_64 SSE2)
#[cfg(target_arch = "x86_64")]
pub fn encode_mulaw_simd_sse2(samples: &[i16], output: &mut [u8]) {
    use std::arch::x86_64::*;

    if !get_simd_support().sse2 {
        return encode_mulaw_scalar(samples, output);
    }

    let mut chunks = samples.chunks_exact(8);
    let mut out_idx = 0;

    unsafe {
        for chunk in chunks.by_ref() {
            // Load 8 samples at once
            let samples_vec = _mm_loadu_si128(chunk.as_ptr() as *const __m128i);

            // Process each sample - need to unroll or use different approach
            // _mm_extract_epi16 requires compile-time constant, so we unroll
            output[out_idx] = linear_to_mulaw_scalar(_mm_extract_epi16(samples_vec, 0) as i16);
            output[out_idx + 1] = linear_to_mulaw_scalar(_mm_extract_epi16(samples_vec, 1) as i16);
            output[out_idx + 2] = linear_to_mulaw_scalar(_mm_extract_epi16(samples_vec, 2) as i16);
            output[out_idx + 3] = linear_to_mulaw_scalar(_mm_extract_epi16(samples_vec, 3) as i16);
            output[out_idx + 4] = linear_to_mulaw_scalar(_mm_extract_epi16(samples_vec, 4) as i16);
            output[out_idx + 5] = linear_to_mulaw_scalar(_mm_extract_epi16(samples_vec, 5) as i16);
            output[out_idx + 6] = linear_to_mulaw_scalar(_mm_extract_epi16(samples_vec, 6) as i16);
            output[out_idx + 7] = linear_to_mulaw_scalar(_mm_extract_epi16(samples_vec, 7) as i16);
            out_idx += 8;
        }
    }

    // Handle remainder
    for &sample in chunks.remainder() {
        output[out_idx] = linear_to_mulaw_scalar(sample);
        out_idx += 1;
    }
}

/// SIMD-optimized μ-law encoding (AArch64 NEON)
#[cfg(target_arch = "aarch64")]
pub fn encode_mulaw_simd_neon(samples: &[i16], output: &mut [u8]) {
    if !get_simd_support().neon {
        return encode_mulaw_scalar(samples, output);
    }

    // For now, fall back to scalar implementation for simplicity
    encode_mulaw_scalar(samples, output);
}

/// Scalar μ-law encoding fallback
pub fn encode_mulaw_scalar(samples: &[i16], output: &mut [u8]) {
    for (i, &sample) in samples.iter().enumerate() {
        output[i] = linear_to_mulaw_scalar(sample);
    }
}

/// SIMD-optimized A-law encoding (x86_64 SSE2)
#[cfg(target_arch = "x86_64")]
pub fn encode_alaw_simd_sse2(samples: &[i16], output: &mut [u8]) {
    use std::arch::x86_64::*;

    if !get_simd_support().sse2 {
        return encode_alaw_scalar(samples, output);
    }

    let mut chunks = samples.chunks_exact(8);
    let mut out_idx = 0;

    unsafe {
        for chunk in chunks.by_ref() {
            // Load 8 samples at once
            let samples_vec = _mm_loadu_si128(chunk.as_ptr() as *const __m128i);

            // Process each sample - need to unroll or use different approach
            // _mm_extract_epi16 requires compile-time constant, so we unroll
            output[out_idx] = linear_to_alaw_scalar(_mm_extract_epi16(samples_vec, 0) as i16);
            output[out_idx + 1] = linear_to_alaw_scalar(_mm_extract_epi16(samples_vec, 1) as i16);
            output[out_idx + 2] = linear_to_alaw_scalar(_mm_extract_epi16(samples_vec, 2) as i16);
            output[out_idx + 3] = linear_to_alaw_scalar(_mm_extract_epi16(samples_vec, 3) as i16);
            output[out_idx + 4] = linear_to_alaw_scalar(_mm_extract_epi16(samples_vec, 4) as i16);
            output[out_idx + 5] = linear_to_alaw_scalar(_mm_extract_epi16(samples_vec, 5) as i16);
            output[out_idx + 6] = linear_to_alaw_scalar(_mm_extract_epi16(samples_vec, 6) as i16);
            output[out_idx + 7] = linear_to_alaw_scalar(_mm_extract_epi16(samples_vec, 7) as i16);
            out_idx += 8;
        }
    }

    // Handle remainder
    for &sample in chunks.remainder() {
        output[out_idx] = linear_to_alaw_scalar(sample);
        out_idx += 1;
    }
}

/// SIMD-optimized A-law encoding (AArch64 NEON)
#[cfg(target_arch = "aarch64")]
pub fn encode_alaw_simd_neon(samples: &[i16], output: &mut [u8]) {
    if !get_simd_support().neon {
        return encode_alaw_scalar(samples, output);
    }

    // For now, fall back to scalar implementation for simplicity
    encode_alaw_scalar(samples, output);
}

/// Scalar A-law encoding fallback
pub fn encode_alaw_scalar(samples: &[i16], output: &mut [u8]) {
    for (i, &sample) in samples.iter().enumerate() {
        output[i] = linear_to_alaw_scalar(sample);
    }
}

/// Cross-platform μ-law encoding dispatcher
pub fn encode_mulaw_optimized(samples: &[i16], output: &mut [u8]) {
    #[cfg(target_arch = "x86_64")]
    {
        if get_simd_support().sse2 {
            return encode_mulaw_simd_sse2(samples, output);
        }
    }

    #[cfg(target_arch = "aarch64")]
    {
        if get_simd_support().neon {
            return encode_mulaw_simd_neon(samples, output);
        }
    }

    encode_mulaw_scalar(samples, output);
}

/// Cross-platform A-law encoding dispatcher
pub fn encode_alaw_optimized(samples: &[i16], output: &mut [u8]) {
    #[cfg(target_arch = "x86_64")]
    {
        if get_simd_support().sse2 {
            return encode_alaw_simd_sse2(samples, output);
        }
    }

    #[cfg(target_arch = "aarch64")]
    {
        if get_simd_support().neon {
            return encode_alaw_simd_neon(samples, output);
        }
    }

    encode_alaw_scalar(samples, output);
}

/// Scalar μ-law conversion (ITU-T G.711)
pub fn linear_to_mulaw_scalar(sample: i16) -> u8 {
    const CLIP: i16 = 32635;
    const BIAS: i16 = 0x84;
    const MULAW_MAX: u8 = 0x7F;

    let mut sample = sample;
    let sign = if sample < 0 {
        // Handle i16::MIN case to avoid overflow
        sample = if sample == i16::MIN {
            i16::MAX
        } else {
            -sample
        };
        0x80
    } else {
        0x00
    };

    if sample > CLIP {
        sample = CLIP;
    }

    sample = sample + BIAS;

    let exponent = if sample <= 0x1F {
        0
    } else if sample <= 0x3F {
        1
    } else if sample <= 0x7F {
        2
    } else if sample <= 0xFF {
        3
    } else if sample <= 0x1FF {
        4
    } else if sample <= 0x3FF {
        5
    } else if sample <= 0x7FF {
        6
    } else {
        7
    };

    let mantissa = (sample >> (exponent + 3)) & 0x0F;
    let mulaw = ((exponent << 4) | mantissa) as u8;

    (mulaw ^ MULAW_MAX) | sign
}

/// Scalar A-law conversion (ITU-T G.711)
pub fn linear_to_alaw_scalar(sample: i16) -> u8 {
    const CLIP: i16 = 32635;
    const ALAW_MAX: u8 = 0x7F;

    let mut sample = sample;
    let sign = if sample < 0 {
        // Handle i16::MIN case to avoid overflow
        sample = if sample == i16::MIN {
            i16::MAX
        } else {
            -sample
        };
        0x80
    } else {
        0x00
    };

    if sample > CLIP {
        sample = CLIP;
    }

    let alaw = if sample < 256 {
        sample >> 4
    } else {
        let exponent = if sample < 512 {
            1
        } else if sample < 1024 {
            2
        } else if sample < 2048 {
            3
        } else if sample < 4096 {
            4
        } else if sample < 8192 {
            5
        } else if sample < 16384 {
            6
        } else {
            7
        };

        let mantissa = (sample >> (exponent + 3)) & 0x0F;
        ((exponent << 4) | mantissa) + 16
    };

    ((alaw as u8) ^ ALAW_MAX) | sign
}

/// Scalar μ-law to linear conversion
pub fn mulaw_to_linear_scalar(mulaw: u8) -> i16 {
    const BIAS: i16 = 0x84;
    const MULAW_MAX: u8 = 0x7F;

    let mulaw = mulaw ^ MULAW_MAX;
    let sign = mulaw & 0x80;
    let exponent = (mulaw >> 4) & 0x07;
    let mantissa = mulaw & 0x0F;

    let mut sample = ((mantissa as i16) << (exponent + 3)) + BIAS;

    if exponent > 0 {
        sample += 1i16 << (exponent + 2);
    }

    if sign != 0 {
        -sample
    } else {
        sample
    }
}

/// Scalar A-law to linear conversion
pub fn alaw_to_linear_scalar(alaw: u8) -> i16 {
    const ALAW_MAX: u8 = 0x7F;

    let alaw = alaw ^ ALAW_MAX;
    let sign = alaw & 0x80;
    let magnitude = alaw & 0x7F;

    let sample = if magnitude < 16 {
        (magnitude as u16) << 4
    } else {
        let exponent = (magnitude >> 4) & 0x07;
        let mantissa = magnitude & 0x0F;

        // Prevent overflow by clamping shift amounts and using wider types
        let exp_shift = ((exponent + 3) as u32).min(15);
        let gain_shift = ((exponent + 2) as u32).min(15);

        ((mantissa as u16) << exp_shift) + ((1u16) << gain_shift)
    } + 8;

    if sign != 0 {
        -(sample as i16)
    } else {
        sample as i16
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simd_support_detection() {
        init_simd_support();
        let support = get_simd_support();

        // At least one of the fields should be accessible
        #[cfg(target_arch = "x86_64")]
        {
            // SSE2 is widely supported on x86_64
            println!("SSE2 support: {}", support.sse2);
        }

        #[cfg(target_arch = "aarch64")]
        {
            // NEON is standard on AArch64
            println!("NEON support: {}", support.neon);
        }
    }

    #[test]
    fn test_mulaw_roundtrip() {
        let original = 12345i16;
        let encoded = linear_to_mulaw_scalar(original);
        let decoded = mulaw_to_linear_scalar(encoded);

        // G.711 is lossy, so we expect some difference
        let error = (original - decoded).abs();
        assert!(error < 1000, "Error too large: {}", error);
    }

    #[test]
    fn test_alaw_roundtrip() {
        let original = 12345i16;
        let encoded = linear_to_alaw_scalar(original);
        let decoded = alaw_to_linear_scalar(encoded);

        // G.711 A-law is lossy, so we expect some difference
        // A-law has different quantization than μ-law, so use more lenient threshold
        // A-law can have significant quantization errors for certain values
        let error = (original - decoded).abs();
        assert!(
            error < 5000,
            "Error too large: {} (original: {}, decoded: {})",
            error,
            original,
            decoded
        );
    }

    #[test]
    fn test_simd_vs_scalar() {
        let samples = vec![0, 1000, -1000, 16000, -16000, 32000, -32000, 12345];
        let mut simd_output = vec![0u8; samples.len()];
        let mut scalar_output = vec![0u8; samples.len()];

        encode_mulaw_optimized(&samples, &mut simd_output);
        encode_mulaw_scalar(&samples, &mut scalar_output);

        // Results should be identical
        assert_eq!(simd_output, scalar_output);
    }

    #[test]
    fn test_empty_input() {
        let samples: Vec<i16> = vec![];
        let mut output: Vec<u8> = vec![];

        encode_mulaw_optimized(&samples, &mut output);
        assert_eq!(output.len(), 0);
    }

    #[test]
    fn test_edge_cases() {
        let samples = vec![i16::MAX, i16::MIN, 0];
        let mut output = vec![0u8; samples.len()];

        encode_mulaw_optimized(&samples, &mut output);

        // Should not panic and produce valid output
        assert_eq!(output.len(), samples.len());
    }
}