Skip to main content

codec_core/utils/
simd.rs

1//! SIMD utilities for cross-platform optimizations
2//!
3//! This module provides SIMD capability detection and optimized operations
4//! for audio processing across different architectures.
5
6use std::sync::OnceLock;
7
8/// SIMD support information
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct SimdSupport {
11    /// `x86_64` SSE2 support
12    pub sse2: bool,
13    /// `x86_64` AVX2 support
14    pub avx2: bool,
15    /// `AArch64` NEON support
16    pub neon: bool,
17}
18
19/// Global SIMD support detection
20static SIMD_SUPPORT: OnceLock<SimdSupport> = OnceLock::new();
21
22#[cfg(target_arch = "x86_64")]
23const fn extracted_i16(value: i32) -> i16 {
24    let bytes = value.to_le_bytes();
25    i16::from_le_bytes([bytes[0], bytes[1]])
26}
27
28/// Initialize SIMD support detection
29pub fn init_simd_support() {
30    SIMD_SUPPORT.get_or_init(detect_simd_support);
31}
32
33/// Internal function to detect SIMD support
34fn detect_simd_support() -> SimdSupport {
35    #[cfg(target_arch = "x86_64")]
36    {
37        SimdSupport {
38            sse2: is_x86_feature_detected!("sse2"),
39            avx2: is_x86_feature_detected!("avx2"),
40            neon: false,
41        }
42    }
43    #[cfg(target_arch = "aarch64")]
44    {
45        SimdSupport {
46            sse2: false,
47            avx2: false,
48            neon: std::arch::is_aarch64_feature_detected!("neon"),
49        }
50    }
51    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
52    {
53        SimdSupport {
54            sse2: false,
55            avx2: false,
56            neon: false,
57        }
58    }
59}
60
61/// Get SIMD support information
62#[must_use]
63pub fn get_simd_support() -> SimdSupport {
64    *SIMD_SUPPORT.get_or_init(detect_simd_support)
65}
66
67/// Check if any SIMD support is available
68#[must_use]
69pub fn has_simd_support() -> bool {
70    let support = get_simd_support();
71    support.sse2 || support.avx2 || support.neon
72}
73
74/// SIMD-optimized μ-law encoding (`x86_64` SSE2).
75#[cfg(target_arch = "x86_64")]
76#[allow(clippy::cast_ptr_alignment)] // `_mm_loadu_si128` explicitly supports unaligned input.
77pub fn encode_mulaw_simd_sse2(samples: &[i16], output: &mut [u8]) {
78    use std::arch::x86_64::{__m128i, _mm_extract_epi16, _mm_loadu_si128};
79
80    if !get_simd_support().sse2 {
81        return encode_mulaw_scalar(samples, output);
82    }
83
84    let mut chunks = samples.chunks_exact(8);
85    let mut out_idx = 0;
86
87    unsafe {
88        for chunk in chunks.by_ref() {
89            // Load 8 samples at once
90            let samples_vec = _mm_loadu_si128(chunk.as_ptr().cast::<__m128i>());
91
92            // Process each sample - need to unroll or use different approach
93            // _mm_extract_epi16 requires compile-time constant, so we unroll
94            output[out_idx] =
95                linear_to_mulaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 0)));
96            output[out_idx + 1] =
97                linear_to_mulaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 1)));
98            output[out_idx + 2] =
99                linear_to_mulaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 2)));
100            output[out_idx + 3] =
101                linear_to_mulaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 3)));
102            output[out_idx + 4] =
103                linear_to_mulaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 4)));
104            output[out_idx + 5] =
105                linear_to_mulaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 5)));
106            output[out_idx + 6] =
107                linear_to_mulaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 6)));
108            output[out_idx + 7] =
109                linear_to_mulaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 7)));
110            out_idx += 8;
111        }
112    }
113
114    // Handle remainder
115    for &sample in chunks.remainder() {
116        output[out_idx] = linear_to_mulaw_scalar(sample);
117        out_idx += 1;
118    }
119}
120
121/// SIMD-optimized μ-law encoding (`AArch64` NEON)
122#[cfg(target_arch = "aarch64")]
123pub fn encode_mulaw_simd_neon(samples: &[i16], output: &mut [u8]) {
124    if !get_simd_support().neon {
125        return encode_mulaw_scalar(samples, output);
126    }
127
128    // For now, fall back to scalar implementation for simplicity
129    encode_mulaw_scalar(samples, output);
130}
131
132/// Scalar μ-law encoding fallback
133pub fn encode_mulaw_scalar(samples: &[i16], output: &mut [u8]) {
134    for (i, &sample) in samples.iter().enumerate() {
135        output[i] = linear_to_mulaw_scalar(sample);
136    }
137}
138
139/// SIMD-optimized A-law encoding (`x86_64` SSE2).
140#[cfg(target_arch = "x86_64")]
141#[allow(clippy::cast_ptr_alignment)] // `_mm_loadu_si128` explicitly supports unaligned input.
142pub fn encode_alaw_simd_sse2(samples: &[i16], output: &mut [u8]) {
143    use std::arch::x86_64::{__m128i, _mm_extract_epi16, _mm_loadu_si128};
144
145    if !get_simd_support().sse2 {
146        return encode_alaw_scalar(samples, output);
147    }
148
149    let mut chunks = samples.chunks_exact(8);
150    let mut out_idx = 0;
151
152    unsafe {
153        for chunk in chunks.by_ref() {
154            // Load 8 samples at once
155            let samples_vec = _mm_loadu_si128(chunk.as_ptr().cast::<__m128i>());
156
157            // Process each sample - need to unroll or use different approach
158            // _mm_extract_epi16 requires compile-time constant, so we unroll
159            output[out_idx] =
160                linear_to_alaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 0)));
161            output[out_idx + 1] =
162                linear_to_alaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 1)));
163            output[out_idx + 2] =
164                linear_to_alaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 2)));
165            output[out_idx + 3] =
166                linear_to_alaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 3)));
167            output[out_idx + 4] =
168                linear_to_alaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 4)));
169            output[out_idx + 5] =
170                linear_to_alaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 5)));
171            output[out_idx + 6] =
172                linear_to_alaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 6)));
173            output[out_idx + 7] =
174                linear_to_alaw_scalar(extracted_i16(_mm_extract_epi16(samples_vec, 7)));
175            out_idx += 8;
176        }
177    }
178
179    // Handle remainder
180    for &sample in chunks.remainder() {
181        output[out_idx] = linear_to_alaw_scalar(sample);
182        out_idx += 1;
183    }
184}
185
186/// SIMD-optimized A-law encoding (`AArch64` NEON)
187#[cfg(target_arch = "aarch64")]
188pub fn encode_alaw_simd_neon(samples: &[i16], output: &mut [u8]) {
189    if !get_simd_support().neon {
190        return encode_alaw_scalar(samples, output);
191    }
192
193    // For now, fall back to scalar implementation for simplicity
194    encode_alaw_scalar(samples, output);
195}
196
197/// Scalar A-law encoding fallback
198pub fn encode_alaw_scalar(samples: &[i16], output: &mut [u8]) {
199    for (i, &sample) in samples.iter().enumerate() {
200        output[i] = linear_to_alaw_scalar(sample);
201    }
202}
203
204/// Cross-platform μ-law encoding dispatcher
205pub fn encode_mulaw_optimized(samples: &[i16], output: &mut [u8]) {
206    #[cfg(target_arch = "x86_64")]
207    {
208        if get_simd_support().sse2 {
209            return encode_mulaw_simd_sse2(samples, output);
210        }
211    }
212
213    #[cfg(target_arch = "aarch64")]
214    {
215        if get_simd_support().neon {
216            return encode_mulaw_simd_neon(samples, output);
217        }
218    }
219
220    encode_mulaw_scalar(samples, output);
221}
222
223/// Cross-platform A-law encoding dispatcher
224pub fn encode_alaw_optimized(samples: &[i16], output: &mut [u8]) {
225    #[cfg(target_arch = "x86_64")]
226    {
227        if get_simd_support().sse2 {
228            return encode_alaw_simd_sse2(samples, output);
229        }
230    }
231
232    #[cfg(target_arch = "aarch64")]
233    {
234        if get_simd_support().neon {
235            return encode_alaw_simd_neon(samples, output);
236        }
237    }
238
239    encode_alaw_scalar(samples, output);
240}
241
242/// Scalar μ-law conversion (ITU-T G.711)
243#[must_use]
244pub const fn linear_to_mulaw_scalar(sample: i16) -> u8 {
245    const CLIP: i16 = 32635;
246    const BIAS: i16 = 0x84;
247    const MULAW_MAX: u8 = 0x7F;
248
249    let mut sample = sample;
250    let sign = if sample < 0 {
251        // Handle i16::MIN case to avoid overflow
252        sample = if sample == i16::MIN {
253            i16::MAX
254        } else {
255            -sample
256        };
257        0x80
258    } else {
259        0x00
260    };
261
262    if sample > CLIP {
263        sample = CLIP;
264    }
265
266    sample += BIAS;
267
268    let exponent = if sample <= 0x1F {
269        0
270    } else if sample <= 0x3F {
271        1
272    } else if sample <= 0x7F {
273        2
274    } else if sample <= 0xFF {
275        3
276    } else if sample <= 0x1FF {
277        4
278    } else if sample <= 0x3FF {
279        5
280    } else if sample <= 0x7FF {
281        6
282    } else {
283        7
284    };
285
286    let mantissa = (sample >> (exponent + 3)) & 0x0F;
287    let mulaw = ((exponent << 4) | mantissa).to_le_bytes()[0];
288
289    (mulaw ^ MULAW_MAX) | sign
290}
291
292/// Scalar A-law conversion (ITU-T G.711)
293#[must_use]
294pub const fn linear_to_alaw_scalar(sample: i16) -> u8 {
295    const CLIP: i16 = 32635;
296    const ALAW_MAX: u8 = 0x7F;
297
298    let mut sample = sample;
299    let sign = if sample < 0 {
300        // Handle i16::MIN case to avoid overflow
301        sample = if sample == i16::MIN {
302            i16::MAX
303        } else {
304            -sample
305        };
306        0x80
307    } else {
308        0x00
309    };
310
311    if sample > CLIP {
312        sample = CLIP;
313    }
314
315    let alaw = if sample < 256 {
316        sample >> 4
317    } else {
318        let exponent = if sample < 512 {
319            1
320        } else if sample < 1024 {
321            2
322        } else if sample < 2048 {
323            3
324        } else if sample < 4096 {
325            4
326        } else if sample < 8192 {
327            5
328        } else if sample < 16384 {
329            6
330        } else {
331            7
332        };
333
334        let mantissa = (sample >> (exponent + 3)) & 0x0F;
335        ((exponent << 4) | mantissa) + 16
336    };
337
338    (alaw.to_le_bytes()[0] ^ ALAW_MAX) | sign
339}
340
341/// Scalar μ-law to linear conversion
342#[must_use]
343#[allow(clippy::cast_lossless)]
344pub const fn mulaw_to_linear_scalar(mulaw: u8) -> i16 {
345    const BIAS: i16 = 0x84;
346    const MULAW_MAX: u8 = 0x7F;
347
348    let mulaw = mulaw ^ MULAW_MAX;
349    let sign = mulaw & 0x80;
350    let exponent = (mulaw >> 4) & 0x07;
351    let mantissa = mulaw & 0x0F;
352
353    let mut sample = ((mantissa as i16) << (exponent + 3)) + BIAS;
354
355    if exponent > 0 {
356        sample += 1i16 << (exponent + 2);
357    }
358
359    if sign != 0 {
360        -sample
361    } else {
362        sample
363    }
364}
365
366/// Scalar A-law to linear conversion
367#[must_use]
368pub fn alaw_to_linear_scalar(alaw: u8) -> i16 {
369    const ALAW_MAX: u8 = 0x7F;
370
371    let alaw = alaw ^ ALAW_MAX;
372    let sign = alaw & 0x80;
373    let magnitude = alaw & 0x7F;
374
375    let sample = if magnitude < 16 {
376        u16::from(magnitude) << 4
377    } else {
378        let exponent = (magnitude >> 4) & 0x07;
379        let mantissa = magnitude & 0x0F;
380
381        // Prevent overflow by clamping shift amounts and using wider types
382        let exp_shift = u32::from(exponent + 3).min(15);
383        let gain_shift = u32::from(exponent + 2).min(15);
384
385        (u16::from(mantissa) << exp_shift) + (1_u16 << gain_shift)
386    } + 8;
387
388    if sign != 0 {
389        -sample.cast_signed()
390    } else {
391        sample.cast_signed()
392    }
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398
399    #[test]
400    fn test_simd_support_detection() {
401        init_simd_support();
402        let support = get_simd_support();
403
404        // At least one of the fields should be accessible
405        #[cfg(target_arch = "x86_64")]
406        {
407            // SSE2 is widely supported on x86_64
408            println!("SSE2 support: {}", support.sse2);
409        }
410
411        #[cfg(target_arch = "aarch64")]
412        {
413            // NEON is standard on AArch64
414            println!("NEON support: {}", support.neon);
415        }
416    }
417
418    #[test]
419    fn test_mulaw_roundtrip() {
420        let original = 12345i16;
421        let encoded = linear_to_mulaw_scalar(original);
422        let decoded = mulaw_to_linear_scalar(encoded);
423
424        // G.711 is lossy, so we expect some difference
425        let error = (original - decoded).abs();
426        assert!(error < 1000, "Error too large: {error}");
427    }
428
429    #[test]
430    fn test_alaw_roundtrip() {
431        let original = 12345i16;
432        let encoded = linear_to_alaw_scalar(original);
433        let decoded = alaw_to_linear_scalar(encoded);
434
435        // G.711 A-law is lossy, so we expect some difference
436        // A-law has different quantization than μ-law, so use more lenient threshold
437        // A-law can have significant quantization errors for certain values
438        let error = (original - decoded).abs();
439        assert!(
440            error < 5000,
441            "Error too large: {error} (original: {original}, decoded: {decoded})"
442        );
443    }
444
445    #[test]
446    fn test_simd_vs_scalar() {
447        let samples = vec![0, 1000, -1000, 16000, -16000, 32000, -32000, 12345];
448        let mut simd_output = vec![0u8; samples.len()];
449        let mut scalar_output = vec![0u8; samples.len()];
450
451        encode_mulaw_optimized(&samples, &mut simd_output);
452        encode_mulaw_scalar(&samples, &mut scalar_output);
453
454        // Results should be identical
455        assert_eq!(simd_output, scalar_output);
456    }
457
458    #[test]
459    fn test_empty_input() {
460        let samples: Vec<i16> = vec![];
461        let mut output: Vec<u8> = vec![];
462
463        encode_mulaw_optimized(&samples, &mut output);
464        assert_eq!(output.len(), 0);
465    }
466
467    #[test]
468    fn test_edge_cases() {
469        let samples = vec![i16::MAX, i16::MIN, 0];
470        let mut output = vec![0u8; samples.len()];
471
472        encode_mulaw_optimized(&samples, &mut output);
473
474        // Should not panic and produce valid output
475        assert_eq!(output.len(), samples.len());
476    }
477}