opus-rs 0.1.39

pure Rust implementation of Opus codec
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
//! no_std / std compatibility shims — zero external dependencies.
//!
//! Provides:
//! * [`OnceCell`] — a dependency-free, **heap-free** lazy cell backed by a 3-state
//!   atomic and inline `UnsafeCell<MaybeUninit<T>>` storage. The value is
//!   constructed exactly once into the inline storage, so no global allocator is
//!   required. Replaces `std::sync::LazyLock`.
//! * [`x86_has_avx`] / [`x86_has_avx2`] / [`x86_has_avx_fma`] / [`x86_has_avx2_fma`]
//!   — x86 SIMD availability probes. Under the
//!   `std` feature these use the OS-backed `is_x86_feature_detected!`; without `std`
//!   they fall back to compile-time `cfg!(target_feature = ...)`.

use core::cell::UnsafeCell;
use core::hint;
use core::mem::MaybeUninit;
#[cfg(not(feature = "portable-atomic"))]
use core::sync::atomic::AtomicU8;
use core::sync::atomic::Ordering;
#[cfg(feature = "portable-atomic")]
use portable_atomic::AtomicU8;

// ---------------------------------------------------------------------------
// OnceCell (heap-free lazy initialization)
// ---------------------------------------------------------------------------

/// Lazily-initialized value stored in inline (non-heap) storage.
///
/// State machine encoded in [`AtomicU8`]:
/// * `0` — uninitialized, idle
/// * `1` — a thread is currently initializing
/// * `2` — initialization complete; the value is live
///
/// The stored value is constructed exactly once into the embedded
/// `MaybeUninit<T>` and never mutated afterwards. Publication uses `Release`
/// ordering so all field writes are visible to any reader that observes state `2`
/// with `Acquire` ordering.
pub struct OnceCell<T: Sync> {
    state: AtomicU8,
    storage: UnsafeCell<MaybeUninit<T>>,
}

// SAFETY: `OnceCell` hands out shared `&T` references to a value that is
// constructed once and never mutated. `T: Sync` makes shared access sound. The
// `UnsafeCell` is only ever written by the single initializer before publication.
unsafe impl<T: Sync> Sync for OnceCell<T> {}

impl<T: Sync> OnceCell<T> {
    /// Create a new, uninitialized cell. `const`-constructible so it can live in a
    /// `static`.
    pub const fn new() -> Self {
        Self {
            state: AtomicU8::new(0),
            storage: UnsafeCell::new(MaybeUninit::uninit()),
        }
    }

    /// Return a shared reference to the value, initializing it on first access.
    ///
    /// `init` is invoked at most once across all threads. It must not panic: a
    /// panic would leave the cell in the `initializing` (1) state and subsequent
    /// callers would spin indefinitely. In practice the only initializer used by
    /// this crate (`CeltMode::new_48000_960_120`) is infallible.
    pub fn get(&self, init: impl FnOnce() -> T) -> &T {
        if self.state.load(Ordering::Acquire) == 2 {
            // SAFETY: initialization is complete; storage holds a valid `T`.
            return unsafe { (*self.storage.get()).assume_init_ref() };
        }
        self.get_slow(init)
    }

    #[cold]
    fn get_slow(&self, init: impl FnOnce() -> T) -> &T {
        // Spin until we either claim the initializer slot (0 -> 1) or observe a
        // finished initialization.
        while self
            .state
            .compare_exchange(0, 1, Ordering::Acquire, Ordering::Relaxed)
            .is_err()
        {
            if self.state.load(Ordering::Acquire) == 2 {
                // SAFETY: another thread finished initialization.
                return unsafe { (*self.storage.get()).assume_init_ref() };
            }
            hint::spin_loop();
        }

        // We claimed the slot; construct into the inline storage and publish.
        // SAFETY: we are the sole writer (state == 1); no reader can observe the
        // storage until we publish state == 2 with Release ordering.
        unsafe {
            (*self.storage.get()).write(init());
        }
        self.state.store(2, Ordering::Release);
        // SAFETY: initialization is complete and published.
        unsafe { (*self.storage.get()).assume_init_ref() }
    }
}

impl<T: Sync> Default for OnceCell<T> {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// No-std slice sorting (`alloc` provides `[T]::sort*` as inherent methods; since
// this crate does not depend on `alloc`, we provide small insertion sorts here).
// ---------------------------------------------------------------------------

/// Sort a slice by a comparator (insertion sort). Intended for the small slices
/// used in this crate (energy bands, NLSF coefficients, median-of-3/5); O(n²) is
/// fine because `n` is tiny.
pub fn sort_by<T>(slice: &mut [T], mut cmp: impl FnMut(&T, &T) -> core::cmp::Ordering) {
    for i in 1..slice.len() {
        let mut j = i;
        while j > 0 && cmp(&slice[j - 1], &slice[j]) == core::cmp::Ordering::Greater {
            slice.swap(j - 1, j);
            j -= 1;
        }
    }
}

/// Sort a slice in ascending order (`Ord` version). See [`sort_by`].
pub fn sort<T: Ord>(slice: &mut [T]) {
    sort_by(slice, |a, b| a.cmp(b));
}

// ---------------------------------------------------------------------------
// x86 SIMD feature detection
// ---------------------------------------------------------------------------

/// Whether the `avx` x86 feature is usable.
///
/// * With the `std` feature: OS-backed runtime detection via CPUID.
/// * Without `std`: compile-time detection (`cfg!(target_feature = "avx")`); build
///   with e.g. `RUSTFLAGS="-C target-feature=+avx"` to enable it.
#[cfg(all(feature = "std", target_arch = "x86_64"))]
pub fn x86_has_avx() -> bool {
    std::arch::is_x86_feature_detected!("avx")
}
#[cfg(not(all(feature = "std", target_arch = "x86_64")))]
#[allow(dead_code)]
pub fn x86_has_avx() -> bool {
    cfg!(target_feature = "avx")
}

/// Whether the `avx2` x86 feature is usable. See [`x86_has_avx`].
#[cfg(all(feature = "std", target_arch = "x86_64"))]
pub fn x86_has_avx2() -> bool {
    std::arch::is_x86_feature_detected!("avx2")
}
#[cfg(not(all(feature = "std", target_arch = "x86_64")))]
#[allow(dead_code)]
pub fn x86_has_avx2() -> bool {
    cfg!(target_feature = "avx2")
}

/// Whether both `avx` and `fma` are usable. Gates kernels compiled with
/// `#[target_feature(enable = "avx,fma")]`: AVX alone is not enough, since
/// Sandy Bridge / Ivy Bridge (and some VMs) have AVX without FMA and would fault
/// with SIGILL on the first `vfmadd`. See [`x86_has_avx`].
#[cfg(all(feature = "std", target_arch = "x86_64"))]
pub fn x86_has_avx_fma() -> bool {
    std::arch::is_x86_feature_detected!("avx") && std::arch::is_x86_feature_detected!("fma")
}
#[cfg(not(all(feature = "std", target_arch = "x86_64")))]
#[allow(dead_code)]
pub fn x86_has_avx_fma() -> bool {
    cfg!(all(target_feature = "avx", target_feature = "fma"))
}

/// Whether both `avx2` and `fma` are usable. Gates kernels compiled with
/// `#[target_feature(enable = "avx2,fma")]`; AVX2 does not architecturally imply
/// FMA. See [`x86_has_avx_fma`].
#[cfg(all(feature = "std", target_arch = "x86_64"))]
pub fn x86_has_avx2_fma() -> bool {
    std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma")
}
#[cfg(not(all(feature = "std", target_arch = "x86_64")))]
#[allow(dead_code)]
pub fn x86_has_avx2_fma() -> bool {
    cfg!(all(target_feature = "avx2", target_feature = "fma"))
}

// ---------------------------------------------------------------------------
// Float math (no_std needs libm for transcendentals / rounding)
// ---------------------------------------------------------------------------

#[cfg(not(feature = "std"))]
#[cfg(not(feature = "libm"))]
compile_error!(
    "opus-rs no_std builds require the `libm` feature (or the `std` feature). \
     Set features = [\"libm\"] (or re-enable default-features)."
);

/// Extension trait giving `f32`/`f64` the usual math methods (`sqrt`, `sin`, ...)
/// under `no_std` by forwarding to `libm`. Under the `std` feature the inherent
/// methods take priority and this trait is simply unused.
///
/// Bring it into scope with `use crate::compat::Math;` in any module that calls
/// these methods so the same `x.sqrt()` syntax works in both build modes.
#[cfg(all(not(feature = "std"), feature = "libm"))]
#[allow(dead_code)]
pub trait Math {
    fn sqrt(self) -> Self;
    fn floor(self) -> Self;
    fn ceil(self) -> Self;
    fn round(self) -> Self;
    fn trunc(self) -> Self;
    fn fract(self) -> Self;
    fn abs(self) -> Self;
    fn ln(self) -> Self;
    fn log2(self) -> Self;
    fn log10(self) -> Self;
    fn log(self, base: Self) -> Self;
    fn exp(self) -> Self;
    fn exp2(self) -> Self;
    fn powf(self, n: Self) -> Self;
    fn powi(self, n: i32) -> Self;
    fn sin(self) -> Self;
    fn cos(self) -> Self;
    fn tan(self) -> Self;
    fn atan2(self, other: Self) -> Self;
    fn atan(self) -> Self;
    fn asin(self) -> Self;
    fn acos(self) -> Self;
    fn sinh(self) -> Self;
    fn cosh(self) -> Self;
    fn tanh(self) -> Self;
    fn cbrt(self) -> Self;
    fn hypot(self, other: Self) -> Self;
    fn mul_add(self, a: Self, b: Self) -> Self;
}

#[cfg(all(not(feature = "std"), feature = "libm"))]
impl Math for f32 {
    fn sqrt(self) -> Self {
        libm::sqrtf(self)
    }
    fn floor(self) -> Self {
        libm::floorf(self)
    }
    fn ceil(self) -> Self {
        libm::ceilf(self)
    }
    fn round(self) -> Self {
        libm::roundf(self)
    }
    fn trunc(self) -> Self {
        libm::truncf(self)
    }
    fn fract(self) -> Self {
        self - libm::truncf(self)
    }
    fn abs(self) -> Self {
        libm::fabsf(self)
    }
    fn ln(self) -> Self {
        libm::logf(self)
    }
    fn log2(self) -> Self {
        libm::log2f(self)
    }
    fn log10(self) -> Self {
        libm::log10f(self)
    }
    fn log(self, base: Self) -> Self {
        libm::logf(self) / libm::logf(base)
    }
    fn exp(self) -> Self {
        libm::expf(self)
    }
    fn exp2(self) -> Self {
        libm::exp2f(self)
    }
    fn powf(self, n: Self) -> Self {
        libm::powf(self, n)
    }
    fn powi(self, n: i32) -> Self {
        libm::powf(self, n as Self)
    }
    fn sin(self) -> Self {
        libm::sinf(self)
    }
    fn cos(self) -> Self {
        libm::cosf(self)
    }
    fn tan(self) -> Self {
        libm::tanf(self)
    }
    fn atan2(self, other: Self) -> Self {
        libm::atan2f(self, other)
    }
    fn atan(self) -> Self {
        libm::atanf(self)
    }
    fn asin(self) -> Self {
        libm::asinf(self)
    }
    fn acos(self) -> Self {
        libm::acosf(self)
    }
    fn sinh(self) -> Self {
        libm::sinhf(self)
    }
    fn cosh(self) -> Self {
        libm::coshf(self)
    }
    fn tanh(self) -> Self {
        libm::tanhf(self)
    }
    fn cbrt(self) -> Self {
        libm::cbrtf(self)
    }
    fn hypot(self, other: Self) -> Self {
        libm::hypotf(self, other)
    }
    fn mul_add(self, a: Self, b: Self) -> Self {
        libm::fmaf(self, a, b)
    }
}

#[cfg(all(not(feature = "std"), feature = "libm"))]
impl Math for f64 {
    fn sqrt(self) -> Self {
        libm::sqrt(self)
    }
    fn floor(self) -> Self {
        libm::floor(self)
    }
    fn ceil(self) -> Self {
        libm::ceil(self)
    }
    fn round(self) -> Self {
        libm::round(self)
    }
    fn trunc(self) -> Self {
        libm::trunc(self)
    }
    fn fract(self) -> Self {
        self - libm::trunc(self)
    }
    fn abs(self) -> Self {
        libm::fabs(self)
    }
    fn ln(self) -> Self {
        libm::log(self)
    }
    fn log2(self) -> Self {
        libm::log2(self)
    }
    fn log10(self) -> Self {
        libm::log10(self)
    }
    fn log(self, base: Self) -> Self {
        libm::log(self) / libm::log(base)
    }
    fn exp(self) -> Self {
        libm::exp(self)
    }
    fn exp2(self) -> Self {
        libm::exp2(self)
    }
    fn powf(self, n: Self) -> Self {
        libm::pow(self, n)
    }
    fn powi(self, n: i32) -> Self {
        libm::pow(self, n as Self)
    }
    fn sin(self) -> Self {
        libm::sin(self)
    }
    fn cos(self) -> Self {
        libm::cos(self)
    }
    fn tan(self) -> Self {
        libm::tan(self)
    }
    fn atan2(self, other: Self) -> Self {
        libm::atan2(self, other)
    }
    fn atan(self) -> Self {
        libm::atan(self)
    }
    fn asin(self) -> Self {
        libm::asin(self)
    }
    fn acos(self) -> Self {
        libm::acos(self)
    }
    fn sinh(self) -> Self {
        libm::sinh(self)
    }
    fn cosh(self) -> Self {
        libm::cosh(self)
    }
    fn tanh(self) -> Self {
        libm::tanh(self)
    }
    fn cbrt(self) -> Self {
        libm::cbrt(self)
    }
    fn hypot(self, other: Self) -> Self {
        libm::hypot(self, other)
    }
    fn mul_add(self, a: Self, b: Self) -> Self {
        libm::fma(self, a, b)
    }
}

#[cfg(all(test, feature = "std", target_arch = "x86_64"))]
mod tests {
    use super::*;

    #[test]
    fn fma_probes_require_both_features() {
        let fma = std::arch::is_x86_feature_detected!("fma");
        assert_eq!(x86_has_avx_fma(), x86_has_avx() && fma);
        assert_eq!(x86_has_avx2_fma(), x86_has_avx2() && fma);
    }
}