Skip to main content

opus1/
lib.rs

1//! opus1: the Opus audio codec (RFC 6716) in Rust, ported from libopus
2//! 1.6.1, the reference implementation in C.
3//!
4//! - [`OpusEncoder`] and [`OpusDecoder`] code one stream of mono or stereo
5//!   audio, at 8, 12, 16, 24 or 48 kHz ([`SampleRate`], [`Channels`]).
6//! - The module `multistream` codes several streams in one packet, for
7//!   example 5.1 surround sound (feature `alloc`, which the default feature
8//!   `std` turns on).
9//! - The module [`packet`] reads, splits and joins Opus packets without
10//!   decoding them, and [`extensions`] reads and writes the extensions in
11//!   their padding.
12//! - With the feature `dred`, the encoder adds deep redundancy (DRED) to
13//!   its packets, and `OpusDredDecoder` reads it back to rebuild lost
14//!   audio.
15//!
16//! Every call that can fail returns [`Error`], whose [`ErrorKind`] is the
17//! error code libopus returns in the same case.
18//!
19//! ```
20//! use opus1::{Application, Channels, OpusDecoder, OpusEncoder, SampleRate};
21//!
22//! let mut encoder = OpusEncoder::new(SampleRate::Hz48000, Channels::Mono, Application::Audio)?;
23//! let mut decoder = OpusDecoder::new(SampleRate::Hz48000, Channels::Mono)?;
24//! let pcm: Vec<f32> = (0..960).map(|i| (i as f32 * 0.05).sin() * 0.5).collect();
25//! let mut packet = [0u8; 1275];
26//! let len = encoder.encode(&pcm, 960, &mut packet)?;
27//! let mut out = [0.0f32; 960];
28//! assert_eq!(decoder.decode(&packet[..len], 960, &mut out)?, 960);
29//! # Ok::<(), opus1::Error>(())
30//! ```
31//!
32//! opus1 follows libopus 1.6.1. The tests of the repository
33//! compare its packets and its decoded audio with that release. The `docs`
34//! folder of the repository explains the codec, the library and where
35//! opus1 differs from libopus.
36
37#![cfg_attr(not(feature = "std"), no_std)]
38// docs.rs sets `--cfg docsrs` (see `[package.metadata.docs.rs]` in
39// Cargo.toml). The nightly feature `doc_cfg` then labels each item that
40// needs a cargo feature with that feature. Other builds ignore this line.
41#![cfg_attr(docsrs, feature(doc_cfg))]
42// Every `unsafe` block of the library needs a `// SAFETY:` comment that
43// says why it is sound (docs/guide/07-architecture.md, "Unsafe code"). The unit
44// tests are left out: they call kernels directly, on inputs they build.
45#![cfg_attr(not(test), warn(clippy::undocumented_unsafe_blocks))]
46#![allow(clippy::too_many_arguments)]
47#![allow(clippy::needless_range_loop)]
48
49// The unit tests use `vec!`, `format!` and `std::` paths. In a `no_std`
50// build they get them from `std`, which a test binary links anyway; the
51// library code itself stays `no_std`. With `std` in the test binary its
52// float methods are found before `compat::Math`, whose imports then look
53// unused.
54#![cfg_attr(all(test, not(feature = "std")), allow(unused_imports))]
55// The module `internals` exists only with the test-only feature
56// `__internals`. Without it, the items that only `internals` exposes to the
57// tests (reference versions of the vector kernels, test constructors and
58// the like) are unused. They stay in every build, so that every build
59// compiles them; the linker drops them.
60#![cfg_attr(not(feature = "__internals"), allow(dead_code, unused_imports))]
61
62// The aarch64 kernels use NEON (Advanced SIMD) without a run-time check, and
63// their `unsafe` calls rely on it. Almost every aarch64 target enables NEON;
64// a few, such as aarch64-unknown-none-softfloat (for kernels and firmware
65// that must not touch the vector registers), do not. opus1 does not support
66// those, so it stops the build there instead of running NEON code.
67#[cfg(all(target_arch = "aarch64", not(target_feature = "neon")))]
68compile_error!(
69    "opus1 needs NEON (Advanced SIMD) on aarch64; targets without it, such as \
70     aarch64-unknown-none-softfloat, are not supported"
71);
72#[cfg(all(test, not(feature = "std")))]
73#[macro_use]
74extern crate std;
75// `Vec` and `Box` of the `multistream` module, of the extension lists and of
76// the codec state with `heap` (feature `alloc`, which `std` and `heap` turn
77// on).
78#[cfg(feature = "alloc")]
79extern crate alloc;
80// The boxed codec state of `heap`. A `std` build has `Box` in its prelude.
81#[cfg(all(feature = "heap", not(feature = "std")))]
82use alloc::boxed::Box;
83
84mod compat;
85mod error;
86pub use error::{Error, ErrorKind};
87mod fixedvec;
88mod in_place;
89mod mathops;
90
91/// Tools that measure decoded audio: a port of libopus `opus_compare`, the
92/// MOC distance of the OSCE draft and the decoding loop of `opus_demo -d`.
93/// Reached as `internals::eval`; not part of the stable API. It needs
94/// `std` and the test-only feature `__internals`.
95#[cfg(all(feature = "std", feature = "__internals"))]
96mod eval;
97
98mod analysis;
99mod bands;
100mod celt;
101mod celt_lpc;
102mod deep_plc;
103#[cfg(feature = "dnn")]
104mod dnn;
105// `dnn` alone builds the shared code but no model, so the weight API comes
106// with `deep-plc`, the smallest feature that has a model.
107#[cfg(feature = "deep-plc")]
108pub use dnn::{DnnBlob, DnnModels};
109#[cfg(feature = "dred")]
110pub use dnn::dred::decoder::{DredParse, DredProcessing, OpusDred, OpusDredDecoder};
111mod hp_cutoff;
112/// Internal parts of the codec for the tests, benchmarks, examples and
113/// fuzz targets of this repository. Only with the test-only feature
114/// `__internals`, which is outside semantic versioning.
115#[cfg(feature = "__internals")]
116#[doc(hidden)]
117pub mod internals;
118mod kiss_fft;
119mod mdct;
120mod modes;
121mod osce_args;
122/// Multichannel encoding and decoding (several Opus streams in one packet).
123/// It allocates in its constructors, so it needs the `alloc` feature, which
124/// `std` and `heap` (both on by default) turn on. It works without `std`
125/// when the application has a global allocator. The constructors build
126/// each stream codec in place in that memory, so they need little stack,
127/// also without `heap`. The single-stream codec stays `no_std` without
128/// `alloc`.
129///
130#[cfg(feature = "alloc")]
131pub mod multistream;
132pub mod extensions;
133pub mod packet;
134mod pitch;
135mod pvq;
136mod quant_bands;
137mod range_coder;
138mod rate;
139mod silk;
140mod simd_mem;
141
142/// The Rust examples in `README.md` and in `docs/guide/`. `cargo test --doc`
143/// compiles and runs every ` ```rust ` block in these files, so the
144/// examples stay in step with the code. Nothing here is part of the
145/// library: these items exist only when rustdoc collects doc tests. Some
146/// examples use the `multistream` module, so they need the `std` feature.
147#[cfg(all(doctest, feature = "std"))]
148mod doc_examples {
149    #[doc = include_str!("../README.md")]
150    struct Readme;
151
152    #[doc = include_str!("../docs/guide/01-what-is-opus.md")]
153    struct WhatIsOpus;
154
155    #[doc = include_str!("../docs/guide/02-packets.md")]
156    struct Packets;
157
158    #[doc = include_str!("../docs/guide/03-encoder.md")]
159    struct Encoder;
160
161    #[doc = include_str!("../docs/guide/04-decoder.md")]
162    struct Decoder;
163
164    #[doc = include_str!("../docs/guide/05-multichannel.md")]
165    struct Multichannel;
166
167    #[doc = include_str!("../docs/guide/06-using-the-library.md")]
168    struct UsingTheLibrary;
169
170    #[doc = include_str!("../docs/guide/07-architecture.md")]
171    struct Architecture;
172
173    #[doc = include_str!("../docs/guide/08-performance.md")]
174    struct Performance;
175
176    #[doc = include_str!("../docs/guide/09-testing.md")]
177    struct Testing;
178
179    #[doc = include_str!("../docs/guide/10-differences-from-libopus.md")]
180    struct DifferencesFromLibopus;
181}
182
183/// The version of this crate, for example `"0.3.0"`: the `version` of its
184/// `Cargo.toml`.
185pub const VERSION: &str = env!("CARGO_PKG_VERSION");
186
187#[cfg(not(feature = "std"))]
188use crate::compat::Math;
189use crate::fixedvec::FixedVec;
190use crate::in_place::{HeapMemory, write_fields};
191use core::mem::MaybeUninit;
192use core::num::NonZeroU32;
193use analysis::{AnalysisGate, AnalysisInfo, AnalysisPcm, PcmRef, SecondChannel, is_digital_silence};
194use celt::{CeltDecoder, CeltEncoder};
195use hp_cutoff::{dc_reject_float, hp_cutoff, hp_cutoff_float};
196use mathops::mac;
197use range_coder::RangeCoder;
198use silk::define::{TYPE_NO_VOICE_ACTIVITY, VAD_NO_ACTIVITY, VAD_NO_DECISION};
199use silk::enc_api::{SilkControl, SilkEncoder, SilkInput, SilkPrefill};
200use silk::lin2log::silk_lin2log;
201use silk::log2lin::silk_log2lin;
202use silk::macros::*;
203
204// --- Heap-free buffer capacity constants (worst case: 2 channels). ---
205const OPUS_MAX_CHANNELS: usize = 2;
206/// Largest API frame in samples/channel (120 ms at 48 kHz). The encoder's
207/// SILK input buffer (`buf_filtered`) has this size too: it holds one part
208/// of a packet, at most 60 ms, of both channels.
209const OPUS_MAX_FRAME: usize = packet::MAX_PACKET_SAMPLES;
210/// Largest frame in samples per channel: 60 ms at 48 kHz.
211const OPUS_MAX_SUBFRAME: usize = 2880;
212/// High-pass filter state memory (`channels * 2`).
213const OPUS_HP_MEM: usize = OPUS_MAX_CHANNELS * 2;
214/// Decoder `w_pcm_i16` cap (`960 * max_channels`): one SILK frame of 20 ms
215/// at 48 kHz, interleaved.
216const OPUS_PCM_I16: usize = 960 * OPUS_MAX_CHANNELS;
217/// Largest packet of interleaved samples: 120 ms at 48 kHz, stereo. The
218/// decoder's output and `encode_i16`'s converted input have this size.
219const OPUS_PCM_PACKET: usize = OPUS_MAX_FRAME * OPUS_MAX_CHANNELS;
220/// Largest 5 ms of interleaved decoder output (`240 * max_channels`): the
221/// size of a redundancy frame or of the concealment that bridges a mode
222/// switch.
223const OPUS_PCM_TAIL: usize = 240 * OPUS_MAX_CHANNELS;
224/// The 2.5 ms a CELT encoder codes in front of a frame after a reset, at
225/// 48 kHz, for each channel: C `tmp_prefill`.
226const CELT_PREFILL: usize = 120 * OPUS_MAX_CHANNELS;
227/// The largest packet of one frame: the TOC byte and a frame of
228/// `packet::MAX_FRAME_BYTES` bytes (RFC 6716 ยง3.1).
229pub(crate) const OPUS_MAX_PACKET_BYTES: usize = 1 + packet::MAX_FRAME_BYTES;
230
231/// Room for the frames of one packet of several frames
232/// (`OpusEncoder::encode_multiframe`, C `tmp_data`).
233///
234/// - With VBR each frame takes at most [`OPUS_MAX_PACKET_BYTES`]. With
235///   DRED, one of them also carries the DRED data in its padding: at most
236///   `DRED_MAX_DATA_SIZE` bytes, the extension ID byte, the frame count
237///   byte of a code 3 packet and at most 4 bytes for the padding length.
238/// - With CBR each frame is padded to all of its room. A room is at most
239///   the frame's share of the CBR size (`nominal_part`). The first coded
240///   frame also gets the DRED bytes, which are first taken from every
241///   share. So the rooms add up to at most the CBR size (`cbr_bytes`),
242///   which `encode_impl` keeps within `6 * OPUS_MAX_PACKET_BYTES`. (With
243///   `Bitrate::Max` the joined packet is then padded to the whole buffer,
244///   which can be longer; that padding is not in this buffer.)
245#[cfg(feature = "dred")]
246const MULTIFRAME_BYTES: usize = 6 * OPUS_MAX_PACKET_BYTES + dnn::dred::DRED_MAX_DATA_SIZE + 6;
247#[cfg(not(feature = "dred"))]
248const MULTIFRAME_BYTES: usize = 6 * OPUS_MAX_PACKET_BYTES;
249/// C `OpusEncoder.delay_buffer[MAX_ENCODER_BUFFER*2]` (480 samples * 2 ch).
250/// Holds the delay-compensation ring feeding the CELT encoder.
251const OPUS_DELAY_BUF: usize = 480 * OPUS_MAX_CHANNELS;
252/// CELT/hybrid input staging cap: `(delay_compensation + frame)*channels`.
253/// Worst case 60 ms stereo @ 48 kHz: (192 + 2880) * 2 = 6144.
254const OPUS_PCM_BUF: usize = (192 + OPUS_MAX_SUBFRAME) * OPUS_MAX_CHANNELS;
255
256/// A sampling rate of the audio that an encoder takes or a decoder writes.
257/// Opus supports these five rates and no others.
258///
259/// The number of each value is the rate in Hz. More rates may be added in
260/// a later release (libopus has 96 kHz behind its QEXT option), so a
261/// `match` on it needs a `_` arm.
262///
263/// ```
264/// use opus1::SampleRate;
265///
266/// assert_eq!(SampleRate::Hz48000.hz(), 48000);
267/// assert_eq!(SampleRate::try_from(16000u32)?, SampleRate::Hz16000);
268/// assert!(SampleRate::try_from(44100u32).is_err());
269/// # Ok::<(), opus1::Error>(())
270/// ```
271#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
272#[non_exhaustive]
273pub enum SampleRate {
274    /// 8 kHz, enough for narrowband audio.
275    Hz8000 = 8000,
276    /// 12 kHz, enough for mediumband audio.
277    Hz12000 = 12000,
278    /// 16 kHz, enough for wideband audio.
279    Hz16000 = 16000,
280    /// 24 kHz, enough for super-wideband audio.
281    Hz24000 = 24000,
282    /// 48 kHz, enough for fullband audio. Opus codes at this rate inside.
283    Hz48000 = 48000,
284}
285
286impl SampleRate {
287    /// Every value, from the lowest rate to the highest.
288    ///
289    /// It is a slice, not an array, so that a later release can add a rate
290    /// (the enum is `#[non_exhaustive]`) without changing its type.
291    pub const ALL: &'static [SampleRate] = &[
292        SampleRate::Hz8000,
293        SampleRate::Hz12000,
294        SampleRate::Hz16000,
295        SampleRate::Hz24000,
296        SampleRate::Hz48000,
297    ];
298
299    /// The rate in Hz, for example 48000 for [`Hz48000`](Self::Hz48000).
300    pub const fn hz(self) -> u32 {
301        self as u32
302    }
303
304    /// The number of samples per channel in 120 ms, the longest packet: the
305    /// output room that a decoder call may need. 5760 at 48 kHz.
306    pub const fn max_frame_size(self) -> usize {
307        self as usize / 25 * 3
308    }
309
310    /// The rate of a codec field that was set from a `SampleRate`, so that
311    /// it holds one of the five rates.
312    pub(crate) const fn from_valid_hz(hz: i32) -> SampleRate {
313        match hz {
314            8000 => SampleRate::Hz8000,
315            12000 => SampleRate::Hz12000,
316            16000 => SampleRate::Hz16000,
317            24000 => SampleRate::Hz24000,
318            _ => {
319                debug_assert!(hz == 48000);
320                SampleRate::Hz48000
321            }
322        }
323    }
324}
325
326impl TryFrom<u32> for SampleRate {
327    type Error = crate::Error;
328
329    /// The value for a rate of `value` Hz. Any rate that Opus does not
330    /// support is refused with [`BadArg`](crate::ErrorKind::BadArg), as
331    /// libopus `opus_encoder_create` and `opus_decoder_create` refuse it.
332    fn try_from(value: u32) -> Result<Self, Self::Error> {
333        SampleRate::ALL
334            .iter()
335            .copied()
336            .find(|rate| rate.hz() == value)
337            .ok_or(Error::INVALID_SAMPLING_RATE)
338    }
339}
340
341impl TryFrom<i32> for SampleRate {
342    type Error = crate::Error;
343
344    /// The value for a rate of `value` Hz, the type libopus uses for rates
345    /// (`opus_int32`). Any rate that Opus does not support is refused with
346    /// [`BadArg`](crate::ErrorKind::BadArg).
347    fn try_from(value: i32) -> Result<Self, Self::Error> {
348        u32::try_from(value)
349            .map_err(|_| Error::INVALID_SAMPLING_RATE)
350            .and_then(SampleRate::try_from)
351    }
352}
353
354impl From<SampleRate> for u32 {
355    fn from(rate: SampleRate) -> u32 {
356        rate.hz()
357    }
358}
359
360/// The number of channels of the audio that an encoder takes or a decoder
361/// writes. A single Opus stream has one or two channels. For more, use the
362/// `multistream` module, which counts channels with a `usize`.
363///
364/// ```
365/// use opus1::Channels;
366///
367/// assert_eq!(Channels::Stereo.count(), 2);
368/// assert_eq!(Channels::try_from(1)?, Channels::Mono);
369/// assert!(Channels::try_from(3).is_err());
370/// # Ok::<(), opus1::Error>(())
371/// ```
372#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
373pub enum Channels {
374    /// One channel.
375    Mono = 1,
376    /// Two channels, interleaved left then right.
377    Stereo = 2,
378}
379
380impl Channels {
381    /// Both values: [`Mono`](Self::Mono), then [`Stereo`](Self::Stereo).
382    pub const ALL: [Channels; 2] = [Channels::Mono, Channels::Stereo];
383
384    /// The number of channels: 1 or 2.
385    pub const fn count(self) -> usize {
386        self as usize
387    }
388
389    /// The channel count of a codec field that was set from a `Channels`,
390    /// so that it is 1 or 2.
391    pub(crate) const fn from_valid_count(count: usize) -> Channels {
392        if count == 1 {
393            Channels::Mono
394        } else {
395            debug_assert!(count == 2);
396            Channels::Stereo
397        }
398    }
399}
400
401impl TryFrom<usize> for Channels {
402    type Error = crate::Error;
403
404    /// The value for `value` channels. Any count other than 1 or 2 is
405    /// refused with [`BadArg`](crate::ErrorKind::BadArg), as libopus
406    /// `opus_encoder_create` and `opus_decoder_create` refuse it.
407    fn try_from(value: usize) -> Result<Self, Self::Error> {
408        match value {
409            1 => Ok(Channels::Mono),
410            2 => Ok(Channels::Stereo),
411            _ => Err(Error::INVALID_CHANNELS),
412        }
413    }
414}
415
416impl From<Channels> for usize {
417    fn from(channels: Channels) -> usize {
418        channels.count()
419    }
420}
421
422/// What an encoder is tuned for: libopus `OPUS_APPLICATION_*`, the
423/// `application` argument of [`OpusEncoder::new`].
424///
425/// [`Voip`](Self::Voip) and [`Audio`](Self::Audio) only steer the
426/// encoder's choices. The three restricted applications also limit them:
427/// to CELT-only packets, or to SILK-only packets.
428///
429/// That limit holds for every packet that carries audio. A packet without
430/// audio can name another mode in its TOC byte, as in libopus. The encoder
431/// writes such a packet when there is no room to code the frame: the
432/// output buffer has fewer than 3 bytes, or the bitrate gives fewer than 3
433/// bytes per frame, or, for a frame of 40 ms or more, the bitrate is below
434/// 2400 b/s or the output buffer holds fewer than 300 bytes per second.
435/// The packet is the TOC byte, with a frame count byte for some frames of
436/// 60 ms or more, padded when the bitrate is constant (libopus's "PLC"
437/// packet). libopus takes its mode from the last frame the encoder coded,
438/// except that a frame shorter than 10 ms is marked CELT-only and a frame
439/// of 60 ms or more in a 1-byte buffer SILK-only. Before the first coded
440/// frame, and after [`reset_state`](OpusEncoder::reset_state), the last
441/// mode is libopus's initial one, Hybrid at fullband. So a restricted
442/// encoder whose bitrate is too low to code any frame can write a TOC byte
443/// that names Hybrid in every packet. A decoder conceals a packet without
444/// audio like a lost one.
445///
446/// The number of each value is the libopus constant of the same name
447/// ([`to_raw`](Self::to_raw)). More values may be added in a later release,
448/// so a `match` on it needs a `_` arm.
449#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
450#[non_exhaustive]
451pub enum Application {
452    /// libopus `OPUS_APPLICATION_VOIP` (2048): speech, for example in a
453    /// call. The encoder leans towards SILK and keeps speech intelligible.
454    Voip = 2048,
455    /// libopus `OPUS_APPLICATION_AUDIO` (2049): music and other audio that
456    /// should sound as close to the input as possible.
457    Audio = 2049,
458    /// libopus `OPUS_APPLICATION_RESTRICTED_LOWDELAY` (2051): the lowest
459    /// delay. Every packet that carries audio is CELT-only (see above for
460    /// packets without audio), and the encoder has no 4 ms look-ahead.
461    RestrictedLowDelay = 2051,
462    /// libopus `OPUS_APPLICATION_RESTRICTED_SILK` (2052, new in libopus
463    /// 1.6): every packet that carries audio is SILK-only, for a decoder
464    /// that only has SILK (see above for packets without audio).
465    ///
466    /// - The bandwidth is at most wideband (8 kHz of audio), whatever is
467    ///   set.
468    /// - Frames are 10 ms or longer. An encode call with 2.5 or 5 ms is
469    ///   refused with [`BadArg`](crate::ErrorKind::BadArg).
470    /// - The speech and music analysis does not run.
471    /// - The look-ahead ([`OpusEncoder::lookahead`]) is 6.5 ms, as with
472    ///   [`Voip`](Self::Voip) and [`Audio`](Self::Audio).
473    ///
474    /// It can only be chosen when the encoder is created:
475    /// [`OpusEncoder::set_application`] refuses to change to it or from it.
476    RestrictedSilk = 2052,
477    /// libopus `OPUS_APPLICATION_RESTRICTED_CELT` (2053, new in libopus
478    /// 1.6): every packet that carries audio is CELT-only, for a decoder
479    /// that only has CELT (see above for packets without audio).
480    /// The encoder codes as with [`RestrictedLowDelay`](Self::RestrictedLowDelay):
481    /// the same packets, and no 4 ms look-ahead.
482    ///
483    /// It can only be chosen when the encoder is created:
484    /// [`OpusEncoder::set_application`] refuses to change to it or from it.
485    RestrictedCelt = 2053,
486}
487
488impl Application {
489    /// The libopus number of the value, for example 2048 for
490    /// [`Voip`](Self::Voip).
491    pub const fn to_raw(self) -> i32 {
492        self as i32
493    }
494
495    /// The applications that can only be chosen when an encoder is created
496    /// (libopus 1.6 `OPUS_SET_APPLICATION`, opus_encoder.c:2789-2798).
497    const fn only_at_creation(self) -> bool {
498        matches!(self, Application::RestrictedSilk | Application::RestrictedCelt)
499    }
500
501    /// The applications whose frames are coded without the 4 ms delay that
502    /// lines CELT up with SILK (C `delay_compensation`,
503    /// opus_encoder.c:1903-1906). Their encoder keeps no delay buffer.
504    const fn without_delay_buffer(self) -> bool {
505        matches!(
506            self,
507            Application::RestrictedLowDelay | Application::RestrictedSilk | Application::RestrictedCelt
508        )
509    }
510}
511
512impl TryFrom<i32> for Application {
513    type Error = crate::Error;
514
515    /// The value with the libopus number `value`. Any other number is
516    /// refused with [`BadArg`](crate::ErrorKind::BadArg), as libopus
517    /// `opus_encoder_create` refuses it.
518    fn try_from(value: i32) -> Result<Self, Self::Error> {
519        match value {
520            2048 => Ok(Application::Voip),
521            2049 => Ok(Application::Audio),
522            2051 => Ok(Application::RestrictedLowDelay),
523            2052 => Ok(Application::RestrictedSilk),
524            2053 => Ok(Application::RestrictedCelt),
525            _ => Err(Error::bad_arg("invalid application")),
526        }
527    }
528}
529
530/// An audio bandwidth: libopus `OPUS_BANDWIDTH_*`. Each value says up to
531/// which frequency a packet carries audio.
532///
533/// The number of each value is the libopus constant of the same name
534/// ([`to_raw`](Self::to_raw)). The automatic choice of an encoder, libopus
535/// `OPUS_AUTO`, is not a bandwidth: it is `None` in
536/// [`OpusEncoder::set_bandwidth`].
537#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
538pub enum Bandwidth {
539    /// 4 kHz (libopus `OPUS_BANDWIDTH_NARROWBAND`, 1101).
540    Narrowband = 1101,
541    /// 6 kHz (libopus `OPUS_BANDWIDTH_MEDIUMBAND`, 1102).
542    Mediumband = 1102,
543    /// 8 kHz (libopus `OPUS_BANDWIDTH_WIDEBAND`, 1103).
544    Wideband = 1103,
545    /// 12 kHz (libopus `OPUS_BANDWIDTH_SUPERWIDEBAND`, 1104).
546    Superwideband = 1104,
547    /// 20 kHz (libopus `OPUS_BANDWIDTH_FULLBAND`, 1105).
548    Fullband = 1105,
549}
550
551impl TryFrom<i32> for Bandwidth {
552    type Error = crate::Error;
553
554    /// The value with the libopus number `value` (1101 to 1105). Any other
555    /// number, `OPUS_AUTO` too, is refused with
556    /// [`BadArg`](crate::ErrorKind::BadArg).
557    fn try_from(value: i32) -> Result<Self, Self::Error> {
558        match value {
559            1101 => Ok(Bandwidth::Narrowband),
560            1102 => Ok(Bandwidth::Mediumband),
561            1103 => Ok(Bandwidth::Wideband),
562            1104 => Ok(Bandwidth::Superwideband),
563            1105 => Ok(Bandwidth::Fullband),
564            _ => Err(Error::bad_arg("invalid bandwidth")),
565        }
566    }
567}
568
569impl Bandwidth {
570    /// The libopus number of the value, for example 1105 for
571    /// [`Fullband`](Self::Fullband).
572    pub const fn to_raw(self) -> i32 {
573        self as i32
574    }
575
576    /// The wider of two bandwidths (C `IMAX` of the bandwidth numbers).
577    fn max_by_index(self, other: Bandwidth) -> Bandwidth {
578        if bandwidth_fec_index(other) > bandwidth_fec_index(self) { other } else { self }
579    }
580
581    /// The number of CELT bands a packet of this bandwidth codes (libopus
582    /// `CELT_SET_END_BAND` in `opus_encode_frame_native` and
583    /// `opus_decode_frame`).
584    ///
585    /// This holds for Hybrid packets as well as CELT-only ones: a Hybrid
586    /// super-wideband packet codes bands 17 and 18 only.
587    #[inline]
588    pub(crate) fn celt_end_band(self) -> usize {
589        match self {
590            Bandwidth::Narrowband => 13,
591            Bandwidth::Mediumband | Bandwidth::Wideband => 17,
592            Bandwidth::Superwideband => 19,
593            Bandwidth::Fullband => 21,
594        }
595    }
596
597    /// The internal sampling rate of SILK for a SILK-only packet of this
598    /// bandwidth, in kHz: 8 for narrowband, 12 for mediumband, 16 otherwise.
599    #[inline]
600    pub(crate) fn silk_khz(self) -> i32 {
601        match self {
602            Bandwidth::Narrowband => 8,
603            Bandwidth::Mediumband => 12,
604            _ => 16,
605        }
606    }
607}
608
609/// The first CELT band of a Hybrid packet. SILK codes the bands below it,
610/// up to 8 kHz.
611const HYBRID_START_BAND: usize = 17;
612
613#[derive(Debug, Clone, Copy, PartialEq, Eq)]
614enum OpusMode {
615    SilkOnly,
616    Hybrid,
617    CeltOnly,
618}
619
620/// A coding mode the caller asks the encoder to use: libopus
621/// `MODE_SILK_ONLY`, `MODE_HYBRID` and `MODE_CELT_ONLY` for
622/// `OPUS_SET_FORCE_MODE`. See [`OpusEncoder::set_force_mode`].
623///
624/// The number of each value is the libopus constant
625/// ([`to_raw`](Self::to_raw)). More values may be added in a later release,
626/// so a `match` on it needs a `_` arm.
627#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
628#[non_exhaustive]
629pub enum ForcedMode {
630    /// SILK alone: speech up to wideband (8 kHz of audio). libopus
631    /// `MODE_SILK_ONLY` (1000).
632    SilkOnly = 1000,
633    /// SILK below 8 kHz and CELT above: super-wideband and fullband speech.
634    /// libopus `MODE_HYBRID` (1001).
635    Hybrid = 1001,
636    /// CELT alone: music, and frames shorter than 10 ms. libopus
637    /// `MODE_CELT_ONLY` (1002).
638    CeltOnly = 1002,
639}
640
641impl ForcedMode {
642    /// The libopus number of the value, for example 1000 for
643    /// [`SilkOnly`](Self::SilkOnly).
644    pub const fn to_raw(self) -> i32 {
645        self as i32
646    }
647}
648
649impl TryFrom<i32> for ForcedMode {
650    type Error = crate::Error;
651
652    /// The value with the libopus number `value` (1000 to 1002). Any other
653    /// number is refused with [`BadArg`](crate::ErrorKind::BadArg).
654    /// libopus's `OPUS_SET_FORCE_MODE` also takes `OPUS_AUTO`, which is
655    /// `None` in [`OpusEncoder::set_force_mode`].
656    fn try_from(value: i32) -> Result<Self, Self::Error> {
657        match value {
658            1000 => Ok(ForcedMode::SilkOnly),
659            1001 => Ok(ForcedMode::Hybrid),
660            1002 => Ok(ForcedMode::CeltOnly),
661            _ => Err(Error::bad_arg("invalid forced mode")),
662        }
663    }
664}
665
666/// The bitrate setting of an encoder: libopus `OPUS_SET_BITRATE`. See
667/// [`OpusEncoder::set_bitrate`]; `MultistreamEncoder::set_bitrate` takes it
668/// too.
669///
670/// ```
671/// use core::num::NonZeroU32;
672/// use opus1::Bitrate;
673///
674/// let bitrate = Bitrate::BitsPerSecond(NonZeroU32::new(64_000).unwrap());
675/// assert_ne!(bitrate, Bitrate::default());
676/// ```
677#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
678pub enum Bitrate {
679    /// libopus `OPUS_AUTO`, the default: the encoder picks the bitrate from
680    /// the sampling rate, the channel count and the frame duration. An
681    /// [`OpusEncoder`] takes `60 * rate / frame_size + rate * channels` bits
682    /// per second: 19,000 b/s for 16 kHz mono and 99,000 b/s for 48 kHz
683    /// stereo in 20 ms frames.
684    #[default]
685    Auto,
686    /// libopus `OPUS_BITRATE_MAX`: as many bits as the output buffer holds.
687    /// An [`OpusEncoder`] takes at most 1,500,000 b/s.
688    Max,
689    /// Bits per second for all channels together. The encoder limits the
690    /// value as [`OpusEncoder::set_bitrate`] says.
691    BitsPerSecond(NonZeroU32),
692}
693
694impl Bitrate {
695    /// [`BitsPerSecond`](Self::BitsPerSecond) for a bitrate that is already
696    /// within an encoder's limits, so at least 500 b/s. A value below 1
697    /// would become 1 b/s; no caller passes one.
698    pub(crate) fn within_limits(bps: i32) -> Bitrate {
699        let bps = u32::try_from(bps).unwrap_or(0);
700        Bitrate::BitsPerSecond(NonZeroU32::new(bps).unwrap_or(NonZeroU32::MIN))
701    }
702
703    /// The bits per second of [`BitsPerSecond`](Self::BitsPerSecond) as the
704    /// `opus_int32` of libopus: a value above `i32::MAX` becomes
705    /// `i32::MAX`. Every encoder limit is far below it.
706    pub(crate) fn bps_to_i32(bps: NonZeroU32) -> i32 {
707        i32::try_from(bps.get()).unwrap_or(i32::MAX)
708    }
709}
710
711/// The frame duration setting of an encoder: libopus
712/// `OPUS_SET_EXPERT_FRAME_DURATION`. See
713/// [`OpusEncoder::set_expert_frame_duration`];
714/// `MultistreamEncoder::set_expert_frame_duration` takes it too.
715///
716/// The number of each value is the libopus constant of the same name
717/// (`OPUS_FRAMESIZE_ARG` is 5000, `OPUS_FRAMESIZE_2_5_MS` is 5001, and so
718/// on). [`FrameDuration::try_from`] takes those numbers and refuses every
719/// other one, as libopus's encoder control does.
720#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
721pub enum FrameDuration {
722    /// libopus `OPUS_FRAMESIZE_ARG`, the default: each frame lasts as long
723    /// as the `frame_size` argument of the encode call says.
724    #[default]
725    Argument = 5000,
726    /// 2.5 ms (`OPUS_FRAMESIZE_2_5_MS`).
727    Ms2_5 = 5001,
728    /// 5 ms (`OPUS_FRAMESIZE_5_MS`).
729    Ms5 = 5002,
730    /// 10 ms (`OPUS_FRAMESIZE_10_MS`).
731    Ms10 = 5003,
732    /// 20 ms (`OPUS_FRAMESIZE_20_MS`).
733    Ms20 = 5004,
734    /// 40 ms (`OPUS_FRAMESIZE_40_MS`).
735    Ms40 = 5005,
736    /// 60 ms (`OPUS_FRAMESIZE_60_MS`).
737    Ms60 = 5006,
738    /// 80 ms (`OPUS_FRAMESIZE_80_MS`).
739    Ms80 = 5007,
740    /// 100 ms (`OPUS_FRAMESIZE_100_MS`).
741    Ms100 = 5008,
742    /// 120 ms (`OPUS_FRAMESIZE_120_MS`).
743    Ms120 = 5009,
744}
745
746impl FrameDuration {
747    /// Every value, in the order of their libopus numbers.
748    pub const ALL: [FrameDuration; 10] = [
749        FrameDuration::Argument,
750        FrameDuration::Ms2_5,
751        FrameDuration::Ms5,
752        FrameDuration::Ms10,
753        FrameDuration::Ms20,
754        FrameDuration::Ms40,
755        FrameDuration::Ms60,
756        FrameDuration::Ms80,
757        FrameDuration::Ms100,
758        FrameDuration::Ms120,
759    ];
760
761    /// The libopus number of the value, for example 5000 for
762    /// [`Argument`](Self::Argument).
763    pub const fn to_raw(self) -> i32 {
764        self as i32
765    }
766
767    /// The frame size in samples per channel at `sampling_rate`, or `None`
768    /// for [`Argument`](Self::Argument). The arithmetic is that of libopus
769    /// `frame_size_select`, and gives a whole number at every sampling rate
770    /// Opus has.
771    pub fn samples(self, sampling_rate: SampleRate) -> Option<usize> {
772        let fs = sampling_rate.hz() as usize;
773        Some(match self {
774            FrameDuration::Argument => return None,
775            FrameDuration::Ms2_5 => fs / 400,
776            FrameDuration::Ms5 => fs / 400 * 2,
777            FrameDuration::Ms10 => fs / 400 * 4,
778            FrameDuration::Ms20 => fs / 400 * 8,
779            FrameDuration::Ms40 => fs / 400 * 16,
780            FrameDuration::Ms60 => 3 * fs / 50,
781            FrameDuration::Ms80 => 4 * fs / 50,
782            FrameDuration::Ms100 => 5 * fs / 50,
783            FrameDuration::Ms120 => 6 * fs / 50,
784        })
785    }
786}
787
788impl TryFrom<i32> for FrameDuration {
789    type Error = crate::Error;
790
791    /// The value with the libopus number `value` (5000 to 5009). Any other
792    /// number is refused, as libopus's `OPUS_SET_EXPERT_FRAME_DURATION`
793    /// refuses it with `OPUS_BAD_ARG`.
794    fn try_from(value: i32) -> Result<Self, Self::Error> {
795        FrameDuration::ALL
796            .into_iter()
797            .find(|d| d.to_raw() == value)
798            .ok_or(Error::bad_arg("invalid frame duration"))
799    }
800}
801
802/// What the input of an encoder is: libopus `OPUS_SET_SIGNAL`. See
803/// [`OpusEncoder::set_signal`].
804///
805/// The number of each value is the libopus constant
806/// ([`to_raw`](Self::to_raw)). More values may be added in a later release,
807/// so a `match` on it needs a `_` arm.
808#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
809#[non_exhaustive]
810pub enum Signal {
811    /// libopus `OPUS_AUTO` (-1000), the default. From complexity 7 on, the
812    /// encoder's speech and music analysis estimates it for every packet.
813    /// Below, the application decides: speech for `Voip`, mostly music for
814    /// `Audio`.
815    #[default]
816    Auto = -1000,
817    /// libopus `OPUS_SIGNAL_VOICE` (3001): speech. The encoder leans
818    /// towards SILK and narrower bandwidths.
819    Voice = 3001,
820    /// libopus `OPUS_SIGNAL_MUSIC` (3002): music. The encoder leans towards
821    /// CELT.
822    Music = 3002,
823}
824
825impl Signal {
826    /// The libopus number of the value, for example 3001 for
827    /// [`Voice`](Self::Voice).
828    pub const fn to_raw(self) -> i32 {
829        self as i32
830    }
831}
832
833impl TryFrom<i32> for Signal {
834    type Error = crate::Error;
835
836    /// The value with the libopus number `value`: `OPUS_AUTO` (-1000),
837    /// 3001 or 3002. Any other number is refused with
838    /// [`BadArg`](crate::ErrorKind::BadArg), as libopus's `OPUS_SET_SIGNAL`
839    /// refuses it.
840    fn try_from(value: i32) -> Result<Self, Self::Error> {
841        match value {
842            OPUS_AUTO => Ok(Signal::Auto),
843            3001 => Ok(Signal::Voice),
844            3002 => Ok(Signal::Music),
845            _ => Err(Error::bad_arg("invalid signal type")),
846        }
847    }
848}
849
850/// In-band forward error correction (FEC): libopus `OPUS_SET_INBAND_FEC`.
851/// See [`OpusEncoder::set_inband_fec`].
852///
853/// The number of each value is the libopus value
854/// ([`to_raw`](Self::to_raw)). More values may be added in a later release,
855/// so a `match` on it needs a `_` arm.
856#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
857#[non_exhaustive]
858pub enum InbandFec {
859    /// libopus 0, the default: no FEC.
860    #[default]
861    Off = 0,
862    /// libopus 1: FEC. With enough packet loss the encoder codes SILK,
863    /// because only SILK frames carry it.
864    On = 1,
865    /// libopus 2: FEC, but the encoder does not move to SILK for it when
866    /// it is confident the input is music (an estimated speech
867    /// probability of at most 25 in 127). This needs the speech and
868    /// music analysis, from complexity 7 on, or [`Signal::Music`].
869    OnUnlessMusic = 2,
870}
871
872impl InbandFec {
873    /// The libopus value, 0 to 2.
874    pub const fn to_raw(self) -> i32 {
875        self as i32
876    }
877}
878
879impl TryFrom<i32> for InbandFec {
880    type Error = crate::Error;
881
882    /// The value with the libopus value `value` (0 to 2). Any other number
883    /// is refused with [`BadArg`](crate::ErrorKind::BadArg), as libopus's
884    /// `OPUS_SET_INBAND_FEC` refuses it.
885    fn try_from(value: i32) -> Result<Self, Self::Error> {
886        match value {
887            0 => Ok(InbandFec::Off),
888            1 => Ok(InbandFec::On),
889            2 => Ok(InbandFec::OnUnlessMusic),
890            _ => Err(Error::bad_arg("invalid in-band FEC setting")),
891        }
892    }
893}
894
895/// The decisions `opus_encode_native` makes once per packet and hands to
896/// `opus_encode_frame_native` for each frame of the packet.
897#[derive(Debug, Clone, Copy)]
898struct FrameDecisions {
899    mode: OpusMode,
900    bandwidth: Bandwidth,
901    /// Whether the packet codes in-band FEC (libopus `LBRR_coded`).
902    lbrr_coded: i32,
903    /// C `redundancy`: the frame carries a 5 ms CELT frame that bridges a
904    /// switch between CELT-only and SILK-only or Hybrid.
905    redundancy: bool,
906    /// C `celt_to_silk`: the redundant frame comes before the main frame
907    /// (the stream leaves CELT-only). Otherwise it comes after it.
908    celt_to_silk: bool,
909    /// C `to_celt`: the next packet is CELT-only. This one is still coded
910    /// in the previous mode, with the redundant frame at its end.
911    to_celt: bool,
912    /// C `prefill`: the SILK encoder restarts after CELT-only packets and
913    /// is first fed the 10 ms before this frame.
914    prefill: bool,
915    /// C `equiv_rate`: the bitrate the decisions went by.
916    equiv_rate: i32,
917}
918
919/// What the speech and music analysis says about one frame, and whether the
920/// frame is digital silence: the arguments `analysis_info` and `is_silence`
921/// of libopus `opus_encode_frame_native`.
922#[derive(Debug, Clone, Copy, Default)]
923struct FrameAnalysis {
924    info: AnalysisInfo,
925    is_silence: bool,
926}
927
928/// silk/define.h `DTX_ACTIVITY_THRESHOLD`: the activity probability of the
929/// analysis below which a frame counts as inactive.
930const DTX_ACTIVITY_THRESHOLD: f32 = 0.1;
931
932/// opus_encoder.c `PSEUDO_SNR_THRESHOLD`: 25 dB. A frame the analysis finds
933/// inactive still counts as active when its energy is within this factor
934/// of the peak energy.
935const PSEUDO_SNR_THRESHOLD: f32 = 316.23;
936
937/// libopus `compute_frame_energy` of the float build: the mean square of
938/// the interleaved samples. The sum is libopus `celt_inner_prod`.
939fn frame_energy(pcm: &[f32]) -> f32 {
940    pitch::inner_prod(pcm, pcm, pcm.len()) / pcm.len() as f32
941}
942
943/// libopus `decide_dtx_mode` (opus_encoder.c:1115-1140): whether the DTX
944/// of the Opus layer leaves this frame out.
945///
946/// `nb_no_activity_ms_q1` counts the time without activity in half
947/// milliseconds, and `frame_ms_q1` is the frame's duration in the same
948/// unit. A frame with `activity` (any value but 0) clears the count. The
949/// first 200 ms without activity are coded, the next 400 ms are left out,
950/// and then the count goes back to 200 ms, so that one frame is coded
951/// before the next 400 ms are left out.
952fn decide_dtx_mode(activity: i32, nb_no_activity_ms_q1: &mut i32, frame_ms_q1: i32) -> bool {
953    use silk::define::{MAX_CONSECUTIVE_DTX, NB_SPEECH_FRAMES_BEFORE_DTX};
954    if activity != 0 {
955        *nb_no_activity_ms_q1 = 0;
956        return false;
957    }
958    *nb_no_activity_ms_q1 += frame_ms_q1;
959    if *nb_no_activity_ms_q1 > NB_SPEECH_FRAMES_BEFORE_DTX * 20 * 2 {
960        if *nb_no_activity_ms_q1 <= (NB_SPEECH_FRAMES_BEFORE_DTX + MAX_CONSECUTIVE_DTX) * 20 * 2 {
961            // "Valid frame for DTX!"
962            return true;
963        }
964        *nb_no_activity_ms_q1 = NB_SPEECH_FRAMES_BEFORE_DTX * 20 * 2;
965    }
966    false
967}
968
969/// libopus `compute_redundancy_bytes` (opus_encoder.c:1142): the size of the
970/// redundant 5 ms CELT frame, or 0 when the packet has no room for one that
971/// is worth its bits.
972fn compute_redundancy_bytes(
973    max_data_bytes: usize,
974    bitrate_bps: i32,
975    frame_rate: i32,
976    channels: usize,
977) -> usize {
978    let channels = channels as i32;
979    let base_bits = 40 * channels + 20;
980    // Equivalent rate for 5 ms frames.
981    let redundancy_rate = bitrate_bps + base_bits * (200 - frame_rate);
982    // "For VBR, further increase the bitrate if we can afford it."
983    let redundancy_rate = 3 * redundancy_rate / 2;
984    let mut redundancy_bytes = redundancy_rate / 1600;
985    // The largest rate that fits, given CBR or VBR with a cap.
986    let available_bits = max_data_bytes as i32 * 8 - 2 * base_bits;
987    let cap = (available_bits * 240 / (240 + 48000 / frame_rate) + base_bits) / 8;
988    redundancy_bytes = redundancy_bytes.min(cap);
989    // "If we can't get enough bits for redundancy to be worth it, rely on
990    // the decoder PLC."
991    if redundancy_bytes > 4 + 8 * channels {
992        redundancy_bytes.min(257) as usize
993    } else {
994        0
995    }
996}
997
998/// libopus `stereo_fade` (opus_encoder.c:548): narrow the stereo image of an
999/// interleaved stereo frame. A gain of 1 keeps the signal and a gain of 0
1000/// leaves the average of the two channels in both. The gain moves from `g1`
1001/// to `g2` over CELT's overlap (2.5 ms), following the squared CELT window.
1002///
1003/// libopus computes the gain as `MAC16_16(MULT16_16(w,g2), Q15ONE-w, g1)`.
1004/// clang on 64-bit ARM rounds `(1 - w) * g1` and fuses `w * g2` into the
1005/// sum, at -Os, -O2 and -O3 alike; `mac` does the same.
1006fn stereo_fade(pcm: &mut [f32], g1: f32, g2: f32, frame_size: usize, fs: i32) {
1007    let window = modes::default_mode().window;
1008    let inc = celt::resampling_factor(fs).unwrap_or(1);
1009    let overlap = (window.len() / inc).min(frame_size);
1010    let (g1, g2) = (1.0 - g1, 1.0 - g2);
1011    let pcm = &mut pcm[..2 * frame_size];
1012    for i in 0..frame_size {
1013        let g = if i < overlap {
1014            let w = window[i * inc] * window[i * inc];
1015            mac((1.0 - w) * g1, w, g2)
1016        } else {
1017            g2
1018        };
1019        let diff = g * (0.5 * (pcm[2 * i] - pcm[2 * i + 1]));
1020        pcm[2 * i] -= diff;
1021        pcm[2 * i + 1] += diff;
1022    }
1023}
1024
1025/// The test libopus makes on the filtered input of a frame
1026/// (opus_encoder.c:2016-2028): "This should filter out both NaNs and
1027/// ridiculous signals that could cause NaNs further down". The frame is
1028/// sane when the sum of its squares is below 1e9 and is a number.
1029///
1030/// libopus takes the sum with `celt_inner_prod`, whose vector version adds
1031/// the squares in another order than one sample after the other. The order
1032/// decides frames whose sum lies within a few parts in ten million of the
1033/// limit, so the sum here is `pitch::inner_prod`, the port of
1034/// `celt_inner_prod`.
1035#[inline]
1036fn input_is_sane(x: &[f32]) -> bool {
1037    let sum = pitch::inner_prod(x, x, x.len());
1038    // C: `!(sum < 1e9f) || celt_isnan(sum)` clears the frame.
1039    sum < 1e9
1040}
1041
1042/// Code `n` samples per channel of interleaved `pcm` as one CELT frame of
1043/// exactly `out.len()` bytes, all bands, at a constant bitrate: the
1044/// redundant frame of a mode switch (opus_encoder.c:2428-2441 and
1045/// 2513-2538), and the 2.5 ms in front of the one at the end of a packet.
1046/// Returns the final range of the frame's range coder.
1047fn encode_celt_redundancy(
1048    celt: &mut CeltEncoder,
1049    pcm: &[f32],
1050    n: usize,
1051    out: &mut [u8],
1052) -> Result<u32, Error> {
1053    let mut rc = RangeCoder::new_encoder(out.len() as u32);
1054    let _ = celt.set_start_band(0);
1055    celt.set_vbr(false);
1056    let _ = celt.set_bitrate(OPUS_BITRATE_MAX);
1057    celt.encode(pcm, n, &mut rc);
1058    rc.done();
1059    if rc.error != 0 || rc.buf.len() < out.len() {
1060        return Err(Error::internal("CELT redundancy frame does not fit"));
1061    }
1062    out.copy_from_slice(&rc.buf[..out.len()]);
1063    Ok(rc.rng)
1064}
1065
1066/// An encoder of one Opus stream of mono or stereo audio: libopus
1067/// `OpusEncoder`.
1068///
1069/// [`new`](Self::new) builds one for a sampling rate, a channel count and
1070/// an [`Application`]. [`init`](Self::init) builds the same encoder in
1071/// memory that the caller provides. Each call of [`encode`](Self::encode)
1072/// (`f32` samples), [`encode_i16`](Self::encode_i16) or
1073/// [`encode24`](Self::encode24) codes one packet from 2.5 to 120 ms of
1074/// interleaved audio. The `set_*` methods are the requests of libopus
1075/// `opus_encoder_ctl`, and most have a getter.
1076///
1077/// ```
1078/// use opus1::{Application, Channels, OpusEncoder, SampleRate};
1079///
1080/// let mut encoder = OpusEncoder::new(SampleRate::Hz48000, Channels::Stereo, Application::Audio)?;
1081/// let pcm = [0.0f32; 960 * 2]; // 20 ms of stereo silence
1082/// let mut packet = [0u8; 1275];
1083/// let len = encoder.encode(&pcm, 960, &mut packet)?;
1084/// assert!(len > 0);
1085/// # Ok::<(), opus1::Error>(())
1086/// ```
1087///
1088/// Without the `heap` feature the encoder holds all of its state inline,
1089/// about 150 KB; see [`init`](Self::init).
1090pub struct OpusEncoder {
1091    #[cfg(not(feature = "heap"))]
1092    celt_enc: CeltEncoder,
1093    #[cfg(feature = "heap")]
1094    celt_enc: Box<CeltEncoder>,
1095    /// The SILK encoder, with a channel state and an input resampler for
1096    /// each input channel.
1097    silk: SilkEncoder,
1098    application: Application,
1099    sampling_rate: i32,
1100    channels: usize,
1101    /// C `st->bandwidth`: the audio bandwidth of the last packet. It is
1102    /// decided again for each packet, but SILK and Hybrid only reconsider
1103    /// the rate-dependent choice when SILK allows a switch.
1104    bandwidth: Bandwidth,
1105    /// C `st->auto_bandwidth`: the bandwidth the bitrate alone called for
1106    /// last time, kept for the hysteresis of the next decision.
1107    auto_bandwidth: Bandwidth,
1108    /// C `st->user_bandwidth`: a bandwidth the caller asked for
1109    /// (`set_bandwidth`), or `None` for the automatic choice.
1110    user_bandwidth: Option<Bandwidth>,
1111    /// C `st->max_bandwidth`: the widest bandwidth the automatic choice may
1112    /// pick (`set_max_bandwidth`).
1113    max_bandwidth: Bandwidth,
1114    /// C `st->user_forced_mode`: a mode the caller asked for
1115    /// (`set_force_mode`), or `None` for the automatic choice.
1116    user_forced_mode: Option<OpusMode>,
1117    /// C `st->lfe`: this encoder codes a low-frequency-effects channel.
1118    lfe: bool,
1119    /// C `st->energy_masking`: 21 values per channel that say how far each
1120    /// band lies above what the other channels of a surround stream mask,
1121    /// or `None` without a mask. libopus keeps a pointer to the caller's
1122    /// array; this is a copy.
1123    energy_mask: Option<[f32; 21 * OPUS_MAX_CHANNELS]>,
1124    /// C `st->rangeFinal`: the state of the range coder after the last
1125    /// frame, 0 when the packet carries no range-coded data.
1126    range_final: u32,
1127    /// C `st->first`: no packet has been coded yet.
1128    first: bool,
1129    /// C `silk_mode.allowBandwidthSwitch`: SILK's speech activity is low
1130    /// enough for a bandwidth switch to go unheard.
1131    silk_allow_bandwidth_switch: bool,
1132    /// C `silk_mode.inWBmodeWithoutVariableLP`: SILK runs at 16 kHz and is
1133    /// not in a low-pass transition.
1134    silk_in_wb_mode_without_variable_lp: bool,
1135    /// C `silk_mode.opusCanSwitch`: SILK reported on the last packet that it
1136    /// is ready to change its internal rate, so it may on this one.
1137    silk_opus_can_switch: bool,
1138    /// C `st->silk_mode.LBRR_coded`: the last packet was to carry in-band
1139    /// FEC. The next decision leans the same way (`decide_fec`). CELT-only
1140    /// packets clear it. libopus keeps it across `OPUS_RESET_STATE`.
1141    silk_lbrr_coded: i32,
1142    /// C `st->nonfinal_frame`: this part of a packet made of several frames
1143    /// is not the last one.
1144    nonfinal_frame: bool,
1145    /// C `st->stream_channels`: the channel count the packets code. Stereo
1146    /// input is coded as mono at low bitrates (`decide_stream_channels`).
1147    stream_channels: usize,
1148    /// C `st->force_channels` (`OPUS_SET_FORCE_CHANNELS`): the channel count
1149    /// the caller asks the packets to code, or `None` for the automatic
1150    /// choice.
1151    force_channels: Option<usize>,
1152    /// C `st->prev_channels`: the channel count of the last frame that was
1153    /// coded, 0 before the first one.
1154    prev_channels: usize,
1155    /// C `st->silk_mode.toMono`: this packet is the last one with two
1156    /// channels before the stream goes on in mono. SILK fades its side
1157    /// signal out over it.
1158    silk_to_mono: bool,
1159    /// C `st->silk_bw_switch`: the last packet ended with a redundant CELT
1160    /// frame because SILK changes its internal rate on this one.
1161    silk_bw_switch: bool,
1162    /// C `st->hybrid_stereo_width_Q14`: the stereo width the last frame's
1163    /// CELT input was reduced to (16384 is full width).
1164    hybrid_stereo_width_q14: i32,
1165    /// C `st->silk_mode.stereoWidth_Q14`: the stereo width for this frame's
1166    /// CELT input.
1167    silk_stereo_width_q14: i32,
1168    /// C `st->width_mem`: the state of the stereo width estimate.
1169    width_mem: StereoWidthState,
1170    /// C `stereo_width` of `opus_encode_native`: the estimate for the
1171    /// current packet, 0 for mono input.
1172    stereo_width: f32,
1173    /// C `st->user_bitrate_bps`: the bitrate setting
1174    /// ([`set_bitrate`](Self::set_bitrate)).
1175    user_bitrate: Bitrate,
1176    /// C `st->bitrate_bps`: the bitrate the current packet is coded at. It
1177    /// is the rate of `user_bitrate`, or the rate the output buffer stands
1178    /// for when that is lower (libopus `user_bitrate_to_bitrate`). With a
1179    /// constant bitrate it is the rate of the whole bytes the packet takes.
1180    /// Each part of a packet made of several frames keeps the packet's
1181    /// value.
1182    packet_bitrate_bps: i32,
1183    /// C `st->silk_mode.complexity`: 0 to 10
1184    /// ([`set_complexity`](Self::set_complexity)).
1185    complexity: i32,
1186    /// C `!st->use_vbr`: every packet has the size the bitrate gives it
1187    /// ([`set_vbr`](Self::set_vbr)).
1188    use_cbr: bool,
1189    /// C `st->vbr_constraint`: with a variable bitrate, CELT-only packets
1190    /// stay close to the bitrate
1191    /// ([`set_vbr_constraint`](Self::set_vbr_constraint)).
1192    vbr_constraint: bool,
1193    /// C `st->fec_config`, and `st->silk_mode.useInBandFEC` when it is not
1194    /// `Off` ([`set_inband_fec`](Self::set_inband_fec)).
1195    fec_config: InbandFec,
1196    /// C `st->silk_mode.packetLossPercentage`: 0 to 100
1197    /// ([`set_packet_loss_perc`](Self::set_packet_loss_perc)).
1198    packet_loss_perc: i32,
1199    /// C `st->prev_framesize`: the duration in samples of the last frame
1200    /// that was coded, 0 before the first one. [`bitrate`](Self::bitrate)
1201    /// reads it.
1202    prev_frame_size: usize,
1203    /// C `silk_mode.reducedDependency` (`OPUS_SET_PREDICTION_DISABLED`):
1204    /// every frame is coded without prediction from the frames before it.
1205    prediction_disabled: bool,
1206    /// C `st->variable_duration` (`OPUS_SET_EXPERT_FRAME_DURATION`): the
1207    /// frame duration the caller set, or `Argument` when the `frame_size`
1208    /// of each encode call decides it.
1209    variable_duration: FrameDuration,
1210    /// The 2.5 ms that the CELT encoder codes, and throws away, after a
1211    /// reset for a change of mode (C `tmp_prefill`), interleaved.
1212    #[cfg(not(feature = "heap"))]
1213    celt_prefill: [f32; CELT_PREFILL],
1214    #[cfg(feature = "heap")]
1215    celt_prefill: Box<[f32; CELT_PREFILL]>,
1216    /// C `st->mode`: the mode decided for the last packet that was coded.
1217    /// Hybrid before the first one, as `opus_encoder_init` sets it. Only a
1218    /// packet too small to code anything reads it, for its first byte.
1219    mode: OpusMode,
1220    /// C `st->prev_mode`: the mode of the last frame that was coded, or
1221    /// CELT-only after a frame that announced the switch to it. `None`
1222    /// before the first frame.
1223    prev_enc_mode: Option<OpusMode>,
1224
1225    variable_hp_smth2_q15: i32,
1226    hp_mem: FixedVec<i32, OPUS_HP_MEM>,
1227    /// With `Voip` at 48 kHz, SILK reads the output of the integer
1228    /// `hp_cutoff`, as in the fixed-point build of libopus. Off by default:
1229    /// that filter's rounding adds a constant of about -9 to its output at
1230    /// 48 kHz and the 60 Hz cutoff (about -2 at 24 kHz, -0.5 at 16 kHz),
1231    /// and SILK codes it. Only tests that compare packets with the
1232    /// fixed-point build turn it on (`internals::silk_input`).
1233    integer_hp_at_48k: bool,
1234    /// Test control: SILK's quantization gains come from libopus's residual
1235    /// energies alone, as in the fixed-point build of libopus. Off by
1236    /// default: in a frame whose subframe gains differ a lot, those
1237    /// energies hold a large rounding error, and opus1 then takes the gain
1238    /// from the energies of the unscaled signal (see
1239    /// `silk_process_gains_fix`). Only tests that compare packets with the
1240    /// fixed-point build turn it on (`internals::silk_input`).
1241    fixed_point_res_nrg: bool,
1242
1243    #[cfg(not(feature = "heap"))]
1244    buf_filtered: FixedVec<i16, OPUS_MAX_FRAME>,
1245    #[cfg(feature = "heap")]
1246    buf_filtered: Box<FixedVec<i16, OPUS_MAX_FRAME>>,
1247    /// C `delay_buffer[MAX_ENCODER_BUFFER*2]`: delay-compensation ring feeding
1248    /// the CELT encoder (see `encoder_buffer` / `delay_compensation`).
1249    #[cfg(not(feature = "heap"))]
1250    delay_buffer: FixedVec<f32, OPUS_DELAY_BUF>,
1251    #[cfg(feature = "heap")]
1252    delay_buffer: Box<FixedVec<f32, OPUS_DELAY_BUF>>,
1253    /// Interleaved `pcm_buf` staging: `delay prefix + filtered frame` exactly
1254    /// like C `opus_encode_frame_native()` builds it before CELT encoding.
1255    #[cfg(not(feature = "heap"))]
1256    buf_celt_pcm: FixedVec<f32, OPUS_PCM_BUF>,
1257    #[cfg(feature = "heap")]
1258    buf_celt_pcm: Box<FixedVec<f32, OPUS_PCM_BUF>>,
1259    /// C `encoder_buffer` (= Fs/100): samples of ring history kept between
1260    /// frames (0 for the restricted applications,
1261    /// `Application::without_delay_buffer`).
1262    encoder_buffer: usize,
1263    /// The 4 ms lookahead prefix prepended to each CELT frame (= Fs/250):
1264    /// C `delay_compensation` as `opus_encode_frame_native` uses it, 0 for
1265    /// the restricted applications.
1266    delay_compensation: usize,
1267    /// Float filter state for `dc_reject_float` / `hp_cutoff_float`
1268    /// (C `st->hp_mem[4]`, opus_val32 in the float build).
1269    hp_mem_float: [f32; 4],
1270    /// C `prev_HB_gain`: the gain the previous frame applied to CELT's input.
1271    /// Hybrid attenuates the high band when it gets few bits.
1272    prev_hb_gain: f32,
1273
1274    /// C `st->analysis`: the speech and music analysis (libopus
1275    /// `src/analysis.c`).
1276    #[cfg(all(feature = "analysis", feature = "heap"))]
1277    analysis: Box<analysis::TonalityAnalysisState>,
1278    #[cfg(all(feature = "analysis", not(feature = "heap")))]
1279    analysis: analysis::TonalityAnalysisState,
1280    /// When the analysis runs (an internal control, see `AnalysisGate`).
1281    analysis_gate: AnalysisGate,
1282    /// C argument `float_api` of `opus_encode_native`, for the frame being
1283    /// coded: the input sum test of `encode_frame` runs only with it. It is
1284    /// true for every `OpusEncoder` call, and for multistream float input;
1285    /// libopus's multistream 16-bit and 24-bit calls pass 0.
1286    float_api: bool,
1287    /// The analysis the last frame went by, for the tests.
1288    last_analysis: AnalysisInfo,
1289    /// C `st->voice_ratio`: the speech probability of the last packet that
1290    /// was not digital silence, in percent, from the analysis. -1 when the
1291    /// analysis did not run. libopus keeps it across `OPUS_RESET_STATE`.
1292    voice_ratio: i32,
1293    /// C `st->signal_type` ([`set_signal`](Self::set_signal)).
1294    signal: Signal,
1295    /// C `st->lsb_depth` ([`set_lsb_depth`](Self::set_lsb_depth)): the
1296    /// precision of the input in bits, 8 to 24.
1297    lsb_depth: i32,
1298    /// C `st->peak_signal_energy`: a slowly decaying maximum of the energy
1299    /// of the active frames. A frame the analysis finds inactive still
1300    /// counts as active for SILK when it is within 25 dB of it.
1301    peak_signal_energy: f32,
1302    /// C `st->use_dtx` ([`set_dtx`](Self::set_dtx)): discontinuous
1303    /// transmission.
1304    use_dtx: bool,
1305    /// C `st->silk_mode.useDTX`: the current packet uses SILK's DTX. That
1306    /// is the case when DTX is on, the packet is not digital silence and
1307    /// the speech and music analysis has no valid result for it. Otherwise
1308    /// the Opus layer decides DTX itself, from the activity of each frame.
1309    silk_use_dtx: bool,
1310    /// C `st->silk_mode.nChannelsInternal`: the channels SILK coded last.
1311    silk_channels_internal: usize,
1312    /// C `st->nb_no_activity_ms_Q1`: how long the input has been inactive,
1313    /// in half milliseconds, for the DTX of the Opus layer.
1314    nb_no_activity_ms_q1: i32,
1315
1316    rc: RangeCoder,
1317
1318    /// Deep redundancy (DRED, cargo feature `dred`): the feature analysis,
1319    /// the RDOVAE encoder, the latent vectors of the last second and the
1320    /// DRED settings of libopus's `OpusEncoder`. Boxed with `heap`: it
1321    /// holds about 40 KB.
1322    #[cfg(all(feature = "dred", feature = "heap"))]
1323    dred: Box<dnn::dred::encoder::DredEncoder>,
1324    #[cfg(all(feature = "dred", not(feature = "heap")))]
1325    dred: dnn::dred::encoder::DredEncoder,
1326}
1327
1328/// libopus `gain_fade` (opus_encoder.c:581): scale an interleaved frame by a
1329/// gain that moves from `g1` to `g2` over CELT's overlap (2.5 ms), following
1330/// the squared CELT window, and stays at `g2` after it. The gain is
1331/// rounded as in `stereo_fade`.
1332fn gain_fade(pcm: &mut [f32], g1: f32, g2: f32, frame_size: usize, channels: usize, fs: i32) {
1333    let window = modes::default_mode().window;
1334    let inc = celt::resampling_factor(fs).unwrap_or(1);
1335    let overlap = (window.len() / inc).min(frame_size);
1336    for i in 0..overlap {
1337        let w = window[i * inc] * window[i * inc];
1338        let g = mac((1.0 - w) * g1, w, g2);
1339        for c in 0..channels {
1340            pcm[i * channels + c] *= g;
1341        }
1342    }
1343    for v in &mut pcm[overlap * channels..frame_size * channels] {
1344        *v *= g2;
1345    }
1346}
1347
1348/// libopus `compute_equiv_rate` (opus_encoder.c:1027): the bitrate a 20 ms
1349/// VBR frame at complexity 10 would need for the same quality. `mode` is
1350/// `None` while the mode is not decided yet.
1351fn compute_equiv_rate(
1352    bitrate: i32,
1353    channels: usize,
1354    frame_rate: i32,
1355    vbr: bool,
1356    mode: Option<OpusMode>,
1357    complexity: i32,
1358    loss: i32,
1359) -> i32 {
1360    let mut equiv = bitrate;
1361    // Take into account overhead from smaller frames.
1362    if frame_rate > 50 {
1363        equiv -= (40 * channels as i32 + 20) * (frame_rate - 50);
1364    }
1365    // CBR is about a 8% penalty for both SILK and CELT.
1366    if !vbr {
1367        equiv -= equiv / 12;
1368    }
1369    // Complexity makes about 10% difference (from 0 to 10) in general.
1370    equiv = equiv * (90 + complexity) / 100;
1371    match mode {
1372        Some(OpusMode::SilkOnly) | Some(OpusMode::Hybrid) => {
1373            // SILK complexity 0-1 uses the non-delayed-decision NSQ, which
1374            // costs about 20%.
1375            if complexity < 2 {
1376                equiv = equiv * 4 / 5;
1377            }
1378            equiv -= equiv * loss / (6 * loss + 10);
1379        }
1380        Some(OpusMode::CeltOnly) => {
1381            // CELT complexity 0-4 doesn't have the pitch filter, which costs
1382            // about 10%.
1383            if complexity < 5 {
1384                equiv = equiv * 9 / 10;
1385            }
1386        }
1387        // Mode not known yet: half the SILK loss.
1388        None => equiv -= equiv * loss / (12 * loss + 20),
1389    }
1390    equiv
1391}
1392
1393/// `mono_voice_bandwidth_thresholds` (opus_encoder.c:149): for each step
1394/// between two bandwidths, the equivalent bitrate at which speech moves to
1395/// the wider one, and the hysteresis around it. libopus 1.6 uses the same
1396/// numbers for stereo.
1397const VOICE_BANDWIDTH_THRESHOLDS: [i32; 8] = [
1398    9000, 700, // NB <-> MB
1399    9000, 700, // MB <-> WB
1400    13500, 1000, // WB <-> SWB
1401    14000, 2000, // SWB <-> FB
1402];
1403/// `mono_music_bandwidth_thresholds` (opus_encoder.c:155).
1404const MUSIC_BANDWIDTH_THRESHOLDS: [i32; 8] = [
1405    9000, 700, // NB <-> MB
1406    9000, 700, // MB <-> WB
1407    11000, 1000, // WB <-> SWB
1408    12000, 2000, // SWB <-> FB
1409];
1410
1411/// `fec_thresholds` (opus_encoder.c:160): LBRR rate threshold and hysteresis
1412/// per bandwidth, starting at narrowband.
1413const FEC_THRESHOLDS: [i32; 10] = [
1414    12000, 1000, // NB
1415    14000, 1000, // MB
1416    16000, 1000, // WB
1417    20000, 1000, // SWB
1418    22000, 1000, // FB
1419];
1420
1421fn bandwidth_fec_index(bw: Bandwidth) -> usize {
1422    match bw {
1423        Bandwidth::Narrowband => 0,
1424        Bandwidth::Mediumband => 1,
1425        Bandwidth::Wideband => 2,
1426        Bandwidth::Superwideband => 3,
1427        Bandwidth::Fullband => 4,
1428    }
1429}
1430
1431fn bandwidth_from_fec_index(idx: usize) -> Bandwidth {
1432    match idx {
1433        0 => Bandwidth::Narrowband,
1434        1 => Bandwidth::Mediumband,
1435        2 => Bandwidth::Wideband,
1436        3 => Bandwidth::Superwideband,
1437        _ => Bandwidth::Fullband,
1438    }
1439}
1440
1441/// Port of opus_encoder.c `decide_fec()`: gate in-band FEC on the packet loss
1442/// setting and on whether the equivalent rate can afford LBRR at the current
1443/// bandwidth. With loss > 5%, the bandwidth is reduced until FEC fits; the
1444/// caller's per-frame bandwidth is updated accordingly.
1445fn decide_fec(
1446    use_in_band_fec: i32,
1447    packet_loss_perc: i32,
1448    last_fec: i32,
1449    mode: OpusMode,
1450    bandwidth: &mut Bandwidth,
1451    rate: i32,
1452) -> i32 {
1453    if use_in_band_fec == 0 || packet_loss_perc == 0 || mode == OpusMode::CeltOnly {
1454        return 0;
1455    }
1456    let orig_bandwidth = *bandwidth;
1457    loop {
1458        let idx = bandwidth_fec_index(*bandwidth);
1459        let mut lbrr_rate_thres_bps = FEC_THRESHOLDS[2 * idx];
1460        let hysteresis = FEC_THRESHOLDS[2 * idx + 1];
1461        if last_fec == 1 {
1462            lbrr_rate_thres_bps -= hysteresis;
1463        }
1464        if last_fec == 0 {
1465            lbrr_rate_thres_bps += hysteresis;
1466        }
1467        // silk_SMULWB(threshold * (125 - min(loss, 25)), 0.01 in Q16)
1468        lbrr_rate_thres_bps = silk_smulwb(
1469            lbrr_rate_thres_bps * (125 - packet_loss_perc.min(25)),
1470            655,
1471        );
1472        // If loss <= 5%, we look at whether we have enough rate to enable FEC.
1473        // If loss > 5%, we decrease the bandwidth until we can enable FEC.
1474        if rate > lbrr_rate_thres_bps {
1475            return 1;
1476        } else if packet_loss_perc <= 5 {
1477            return 0;
1478        } else if bandwidth_fec_index(*bandwidth) > 0 {
1479            let lower = bandwidth_fec_index(*bandwidth) - 1;
1480            *bandwidth = bandwidth_from_fec_index(lower);
1481        } else {
1482            break;
1483        }
1484    }
1485    // Couldn't find any bandwidth to enable FEC, keep original bandwidth.
1486    *bandwidth = orig_bandwidth;
1487    0
1488}
1489
1490/// C `StereoWidthState` (opus_encoder.c): the running estimates behind
1491/// [`compute_stereo_width`].
1492#[derive(Clone, Copy, Default)]
1493struct StereoWidthState {
1494    /// Smoothed power of the left and of the right channel, and their
1495    /// smoothed product.
1496    xx: f32,
1497    xy: f32,
1498    yy: f32,
1499    smoothed_width: f32,
1500    max_follower: f32,
1501}
1502
1503/// libopus `compute_stereo_width` (opus_encoder.c:854, float build): how
1504/// far apart the two channels of stereo input are, from 0 (the same signal
1505/// in both) to 1.
1506///
1507/// The width of a frame is small when the channels are correlated or
1508/// equally loud. It is smoothed over one second, and the result follows its
1509/// peaks, which decay slowly.
1510fn compute_stereo_width(
1511    pcm: &[f32],
1512    frame_size: usize,
1513    fs: i32,
1514    mem: &mut StereoWidthState,
1515) -> f32 {
1516    let frame_rate = fs / frame_size as i32;
1517    let short_alpha = 25.0 / frame_rate.max(50) as f32;
1518    let (mut xx, mut xy, mut yy) = (0.0f32, 0.0f32, 0.0f32);
1519    // Four samples at a time, as in C. The frame size is a multiple of 4
1520    // except for 2.5 ms at 12 kHz, where the last two samples are left out.
1521    // The arithmetic is that of the float build on 64-bit ARM: clang fuses
1522    // `a + b*c` within one C statement (`mac`), and `a*b + c*d` with the
1523    // left product fused and the right one rounded. `MIN32` and `MAX32` are
1524    // the ternaries of celt/arch.h.
1525    let (min, max) = (|a: f32, b: f32| if a < b { a } else { b }, |a: f32, b: f32| if a > b { a } else { b });
1526    let mut i = 0;
1527    while i + 3 < frame_size {
1528        let (x, y) = (pcm[2 * i], pcm[2 * i + 1]);
1529        let (mut pxx, mut pxy, mut pyy) = (x * x, x * y, y * y);
1530        for k in 1..4 {
1531            let (x, y) = (pcm[2 * (i + k)], pcm[2 * (i + k) + 1]);
1532            pxx = mac(pxx, x, x);
1533            pxy = mac(pxy, x, y);
1534            pyy = mac(pyy, y, y);
1535        }
1536        xx += pxx;
1537        xy += pxy;
1538        yy += pyy;
1539        i += 4;
1540    }
1541    // C shape kept (`!(xx < 1e9f) || celt_isnan(xx)`): it also catches NaN.
1542    #[allow(clippy::neg_cmp_op_on_partial_ord)]
1543    if !(xx < 1e9) || xx.is_nan() || !(yy < 1e9) || yy.is_nan() {
1544        xx = 0.0;
1545        xy = 0.0;
1546        yy = 0.0;
1547    }
1548    mem.xx = mac(mem.xx, short_alpha, xx - mem.xx);
1549    // "Rewritten to avoid overflows on abrupt sign change."
1550    mem.xy = mac(short_alpha * xy, 1.0 - short_alpha, mem.xy);
1551    mem.yy = mac(mem.yy, short_alpha, yy - mem.yy);
1552    mem.xx = max(0.0, mem.xx);
1553    mem.xy = max(0.0, mem.xy);
1554    mem.yy = max(0.0, mem.yy);
1555    if max(mem.xx, mem.yy) > 8e-4 {
1556        let sqrt_xx = mem.xx.sqrt();
1557        let sqrt_yy = mem.yy.sqrt();
1558        let qrrt_xx = sqrt_xx.sqrt();
1559        let qrrt_yy = sqrt_yy.sqrt();
1560        // Inter-channel correlation.
1561        mem.xy = min(mem.xy, sqrt_xx * sqrt_yy);
1562        let corr = mem.xy / mac(1e-15, sqrt_xx, sqrt_yy);
1563        // Approximate loudness difference.
1564        let ldiff = (qrrt_xx - qrrt_yy).abs() / (1e-15 + qrrt_xx + qrrt_yy);
1565        let width = min(1.0, mac(1.0, -corr, corr).sqrt()) * ldiff;
1566        // Smoothing over one second.
1567        mem.smoothed_width += (width - mem.smoothed_width) / frame_rate as f32;
1568        // Peak follower.
1569        mem.max_follower = max(mem.max_follower - 0.02 / frame_rate as f32, mem.smoothed_width);
1570    }
1571    min(1.0, 20.0 * mem.max_follower)
1572}
1573
1574/// The equivalent bitrate from which the automatic choice takes CELT-only
1575/// instead of SILK (opus_encoder.c:1492-1511).
1576///
1577/// `stereo_width` is 0 for mono input and what [`compute_stereo_width`]
1578/// gives for stereo input. Wide stereo moves the threshold for speech from
1579/// 64 to 44 kb/s (C `mode_thresholds`).
1580fn compute_mode_threshold(
1581    application: Application,
1582    stereo_width: f32,
1583    prev_was_celt: bool,
1584    has_prev_mode: bool,
1585    voice_est: i32,
1586) -> i32 {
1587    // "Interpolate based on stereo width", with the float arithmetic of C.
1588    let mode_voice = ((1.0 - stereo_width) * 64000.0 + stereo_width * 44000.0) as i32;
1589    let mode_music = ((1.0 - stereo_width) * 10000.0 + stereo_width * 10000.0) as i32;
1590
1591    let diff = mode_voice - mode_music;
1592    let offset = (voice_est * voice_est * diff) >> 14;
1593    let mut threshold = mode_music + offset;
1594
1595    if application == Application::Voip {
1596        threshold += 8000;
1597    }
1598
1599    if has_prev_mode {
1600        if prev_was_celt {
1601            threshold -= 4000;
1602        } else {
1603            threshold += 4000;
1604        }
1605    }
1606
1607    if application == Application::RestrictedLowDelay {
1608        threshold = 0;
1609    }
1610
1611    threshold
1612}
1613
1614/// libopus `OPUS_AUTO`: the encoder picks the value itself. As a bitrate,
1615/// the encoder picks it from the sampling rate and the channel count.
1616pub(crate) const OPUS_AUTO: i32 = -1000;
1617
1618/// libopus `OPUS_BITRATE_MAX`: no bitrate limit. The frame fills the bytes
1619/// it is given.
1620pub(crate) const OPUS_BITRATE_MAX: i32 = -1;
1621
1622/// Six times the number of frames per second, the divisor of
1623/// `bitrate_to_bits` and `bits_to_bitrate`. With six times the rate, 60 ms
1624/// frames (16.67 per second) round as in libopus. A frame size above the
1625/// `i32` range counts as `i32::MAX`.
1626///
1627/// The frame must be shorter than 6 seconds and `frame_size` must not be 0:
1628/// otherwise the conversions divide by 0.
1629#[inline]
1630fn frame_rate_x6(fs: i32, frame_size: usize) -> i64 {
1631    6 * fs as i64 / frame_size.min(i32::MAX as usize) as i64
1632}
1633
1634/// libopus `bitrate_to_bits`: bits per second to bits per frame. The
1635/// arithmetic is 64 bits wide; a result outside the `i32` range is clamped.
1636#[inline]
1637pub(crate) fn bitrate_to_bits(bitrate: i32, fs: i32, frame_size: usize) -> i32 {
1638    let bits = bitrate as i64 * 6 / frame_rate_x6(fs, frame_size);
1639    bits.clamp(i32::MIN as i64, i32::MAX as i64) as i32
1640}
1641
1642/// libopus `bits_to_bitrate`: bits per frame to bits per second. The
1643/// arithmetic is 64 bits wide; a result outside the `i32` range is clamped.
1644#[inline]
1645pub(crate) fn bits_to_bitrate(bits: i32, fs: i32, frame_size: usize) -> i32 {
1646    let bitrate = (bits as i64).saturating_mul(frame_rate_x6(fs, frame_size)) / 6;
1647    bitrate.clamp(i32::MIN as i64, i32::MAX as i64) as i32
1648}
1649
1650/// SILK's share of a Hybrid packet's `rate_bps`: libopus
1651/// `compute_silk_rate_for_hybrid` (opus_encoder.c:973). The rate is
1652/// allocated per channel, since stereo codes the side with SILK too.
1653fn compute_silk_rate_for_hybrid(
1654    rate_bps: i32,
1655    bandwidth: Bandwidth,
1656    frame20ms: bool,
1657    vbr: bool,
1658    fec: bool,
1659    channels: usize,
1660) -> i32 {
1661    //  total |  SILK, no FEC  |   SILK, FEC    |
1662    //        | 10 ms   20 ms  | 10 ms   20 ms  |
1663    const RATE_TABLE: [[i32; 5]; 7] = [
1664        [0, 0, 0, 0, 0],
1665        [12000, 10000, 10000, 11000, 11000],
1666        [16000, 13500, 13500, 15000, 15000],
1667        [20000, 16000, 16000, 18000, 18000],
1668        [24000, 18000, 18000, 21000, 21000],
1669        [32000, 22000, 22000, 28000, 28000],
1670        [64000, 38000, 38000, 50000, 50000],
1671    ];
1672    let channels = channels as i32;
1673    // Do the allocation per channel.
1674    let rate = rate_bps / channels;
1675    let entry = 1 + frame20ms as usize + 2 * fec as usize;
1676    let n = RATE_TABLE.len();
1677    let mut i = 1;
1678    while i < n && RATE_TABLE[i][0] <= rate {
1679        i += 1;
1680    }
1681    let mut silk_rate = if i == n {
1682        // Above the table, SILK gets half of the extra bits.
1683        RATE_TABLE[n - 1][entry] + (rate - RATE_TABLE[n - 1][0]) / 2
1684    } else {
1685        let (lo, hi) = (RATE_TABLE[i - 1][entry], RATE_TABLE[i][entry]);
1686        let (x0, x1) = (RATE_TABLE[i - 1][0], RATE_TABLE[i][0]);
1687        (lo * (x1 - rate) + hi * (rate - x0)) / (x1 - x0)
1688    };
1689    if !vbr {
1690        // Tiny boost to SILK for CBR.
1691        silk_rate += 100;
1692    }
1693    if bandwidth == Bandwidth::Superwideband {
1694        silk_rate += 300;
1695    }
1696    silk_rate *= channels;
1697    // Small adjustment for stereo (libopus: "calibrated for 32 kb/s").
1698    if channels == 2 && rate >= 12000 {
1699        silk_rate -= 1000;
1700    }
1701    silk_rate
1702}
1703
1704#[cfg(all(test, feature = "std"))]
1705mod silk_rate_tests {
1706    use super::{Bandwidth, compute_silk_rate_for_hybrid};
1707
1708    /// Fullband, 20 ms, VBR, no FEC: the plain table.
1709    fn plain(rate: i32, channels: usize) -> i32 {
1710        compute_silk_rate_for_hybrid(rate, Bandwidth::Fullband, true, true, false, channels)
1711    }
1712
1713    #[test]
1714    fn test_reference_table_exact_entries() {
1715        assert_eq!(plain(12000, 1), 10000);
1716        assert_eq!(plain(16000, 1), 13500);
1717        assert_eq!(plain(20000, 1), 16000);
1718        assert_eq!(plain(24000, 1), 18000);
1719        assert_eq!(plain(32000, 1), 22000);
1720        assert_eq!(plain(64000, 1), 38000);
1721    }
1722
1723    #[test]
1724    fn test_interpolation_between_table_entries() {
1725        assert_eq!(plain(18000, 1), 14750);
1726    }
1727
1728    #[test]
1729    fn test_above_table_max_gives_half_extra() {
1730        assert_eq!(plain(72000, 1), 38000 + (72000 - 64000) / 2);
1731    }
1732
1733    /// Stereo looks the rate up per channel, doubles it and, from 12 kb/s per
1734    /// channel, takes 1 kb/s off (libopus opus_encoder.c).
1735    #[test]
1736    fn test_stereo_allocates_per_channel() {
1737        assert_eq!(plain(32000, 2), 2 * 13500 - 1000);
1738        assert_eq!(plain(24000, 2), 2 * 10000 - 1000);
1739        assert_eq!(plain(20000, 2), 2 * 8333);
1740        assert_eq!(plain(64000, 2), 2 * 22000 - 1000);
1741    }
1742
1743    /// Super-wideband adds 300 b/s, CBR 100 b/s, and FEC uses its own column.
1744    #[test]
1745    fn test_boosts_and_fec_column() {
1746        let swb = Bandwidth::Superwideband;
1747        let fb = Bandwidth::Fullband;
1748        assert_eq!(compute_silk_rate_for_hybrid(24000, swb, true, true, false, 1), 18300);
1749        assert_eq!(compute_silk_rate_for_hybrid(24000, fb, true, false, false, 1), 18100);
1750        assert_eq!(compute_silk_rate_for_hybrid(24000, swb, true, false, false, 1), 18400);
1751        assert_eq!(compute_silk_rate_for_hybrid(24000, fb, true, true, true, 1), 21000);
1752        assert_eq!(compute_silk_rate_for_hybrid(32000, swb, true, true, true, 1), 28300);
1753        // Stereo: the boosts are per channel, before the 1 kb/s adjustment.
1754        assert_eq!(
1755            compute_silk_rate_for_hybrid(32000, swb, true, true, false, 2),
1756            2 * (13500 + 300) - 1000
1757        );
1758    }
1759}
1760
1761/// Mutably borrow a codec-state field that is a `Box<T>` under the `heap`
1762/// feature and a plain `T` otherwise, so call sites don't need `#[cfg]` on
1763/// every `&mut self.field`.
1764///
1765/// Under `heap` the field is a `Box<...>`, so `T: DerefMut` resolves to the
1766/// box itself and the `Target` is the inner type. Without `heap` the field is
1767/// the inner type directly; `?Sized` lets `&mut [i16]`-style coercion choose
1768/// the slice target.
1769#[cfg(feature = "heap")]
1770#[inline(always)]
1771fn state_mut<T: core::ops::DerefMut>(b: &mut T) -> &mut T::Target {
1772    b
1773}
1774#[cfg(not(feature = "heap"))]
1775#[inline(always)]
1776fn state_mut<T: ?Sized>(b: &mut T) -> &mut T {
1777    b
1778}
1779
1780impl core::fmt::Debug for OpusEncoder {
1781    /// The main settings, as their getters return them. The state of the
1782    /// codec and its buffers are left out.
1783    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1784        let mut d = f.debug_struct("OpusEncoder");
1785        d.field("sampling_rate", &self.sampling_rate())
1786            .field("channels", &self.channels())
1787            .field("application", &self.application)
1788            .field("bitrate_setting", &self.user_bitrate)
1789            .field("complexity", &self.complexity())
1790            .field("vbr", &self.vbr())
1791            .field("vbr_constraint", &self.vbr_constraint)
1792            .field("bandwidth_setting", &self.user_bandwidth)
1793            .field("max_bandwidth", &self.max_bandwidth)
1794            .field("force_mode", &self.force_mode())
1795            .field("force_channels", &self.force_channels())
1796            .field("signal", &self.signal)
1797            .field("inband_fec", &self.fec_config)
1798            .field("packet_loss_perc", &self.packet_loss_perc())
1799            .field("dtx", &self.use_dtx)
1800            .field("lsb_depth", &self.lsb_depth())
1801            .field("expert_frame_duration", &self.variable_duration);
1802        #[cfg(feature = "dred")]
1803        d.field("dred_duration", &self.dred_duration());
1804        d.finish_non_exhaustive()
1805    }
1806}
1807
1808/// Defines [`KeptOnReset`] from a list of `OpusEncoder` fields.
1809macro_rules! kept_on_reset {
1810    ($( $(#[$doc:meta])* $field:ident: $ty:ty, )*) => {
1811        /// What [`OpusEncoder::reset_state`] keeps of an encoder: the
1812        /// settings, and the values that libopus keeps because they lie
1813        /// before `OPUS_ENCODER_RESET_START` in its `OpusEncoder`
1814        /// (opus_encoder.c:3243-3271). Each field is the field of the same
1815        /// name in `OpusEncoder`.
1816        struct KeptOnReset {
1817            $( $(#[$doc])* $field: $ty, )*
1818            /// C: `disable_inv` lies before the part of the CELT encoder that a
1819            /// reset clears.
1820            phase_inversion_disabled: bool,
1821        }
1822
1823        impl KeptOnReset {
1824            /// The values of `enc`.
1825            fn of(enc: &OpusEncoder) -> Self {
1826                Self {
1827                    $( $field: enc.$field, )*
1828                    phase_inversion_disabled: enc.celt_enc.phase_inversion_disabled(),
1829                }
1830            }
1831
1832            /// Puts the values back into `enc`.
1833            fn restore(self, enc: &mut OpusEncoder) {
1834                $( enc.$field = self.$field; )*
1835                enc.celt_enc.set_phase_inversion_disabled(self.phase_inversion_disabled);
1836            }
1837        }
1838    };
1839}
1840
1841kept_on_reset! {
1842    user_bitrate: Bitrate,
1843    complexity: i32,
1844    use_cbr: bool,
1845    vbr_constraint: bool,
1846    fec_config: InbandFec,
1847    packet_loss_perc: i32,
1848    user_forced_mode: Option<OpusMode>,
1849    user_bandwidth: Option<Bandwidth>,
1850    max_bandwidth: Bandwidth,
1851    lfe: bool,
1852    prediction_disabled: bool,
1853    variable_duration: FrameDuration,
1854    /// C `force_channels` and `silk_mode.toMono` lie before
1855    /// `OPUS_ENCODER_RESET_START` too.
1856    force_channels: Option<usize>,
1857    silk_to_mono: bool,
1858    /// The SILK control structure `silk_mode` lies before
1859    /// `OPUS_ENCODER_RESET_START`, so what SILK reported for the last
1860    /// packet stays. The first of these values shows after a reset: it is
1861    /// the hysteresis of the next FEC decision.
1862    silk_lbrr_coded: i32,
1863    silk_allow_bandwidth_switch: bool,
1864    silk_in_wb_mode_without_variable_lp: bool,
1865    /// Test controls, not codec state.
1866    integer_hp_at_48k: bool,
1867    fixed_point_res_nrg: bool,
1868    /// C `signal_type`, `voice_ratio` and `lsb_depth` lie before
1869    /// `OPUS_ENCODER_RESET_START` too. The analysis state lies before it as
1870    /// well, but `tonality_analysis_reset` clears it, which `write_new`
1871    /// does.
1872    signal: Signal,
1873    voice_ratio: i32,
1874    lsb_depth: i32,
1875    analysis_gate: AnalysisGate,
1876    /// C `use_dtx` lies before `OPUS_ENCODER_RESET_START`, and
1877    /// `silk_mode.useDTX` and `silk_mode.nChannelsInternal` are part of
1878    /// `silk_mode`. The time without activity is cleared.
1879    use_dtx: bool,
1880    silk_use_dtx: bool,
1881    silk_channels_internal: usize,
1882}
1883
1884/// Runs `$body` with `$p` bound to the deep PLC argument of the SILK and
1885/// CELT decoders: `Some(&mut DeepPlcArgs)` with this `OpusDecoder`'s deep
1886/// PLC state, models and kernel variant, or `None` in a build without the
1887/// feature `deep-plc`. `$body` may borrow other fields of `$self`.
1888macro_rules! with_deep_plc {
1889    ($self:ident, |$p:ident| $body:expr) => {{
1890        #[cfg(feature = "deep-plc")]
1891        let mut args = crate::deep_plc::DeepPlcArgs {
1892            state: state_mut(&mut $self.deep_plc),
1893            models: $self.dnn.deep_plc(),
1894            arch: $self.dnn.arch(),
1895        };
1896        #[cfg(feature = "deep-plc")]
1897        let $p = Some(&mut args);
1898        #[cfg(not(feature = "deep-plc"))]
1899        let $p: Option<&mut crate::deep_plc::DeepPlcArgs> = None;
1900        $body
1901    }};
1902}
1903
1904impl OpusEncoder {
1905    /// libopus `opus_encoder_create`: a new encoder for audio at
1906    /// `sampling_rate` with `channels` channels, tuned for `application`.
1907    /// The settings start at the defaults of libopus, for example
1908    /// [`Bitrate::Auto`] and complexity 9.
1909    ///
1910    /// It cannot fail at present: the `Result` leaves room for checks that
1911    /// a later release may need.
1912    ///
1913    /// Without the `heap` feature the encoder is returned through the
1914    /// stack, which needs more than 256 KB of stack. [`init`](Self::init)
1915    /// builds it in place instead.
1916    pub fn new(
1917        sampling_rate: SampleRate,
1918        channels: Channels,
1919        application: Application,
1920    ) -> Result<Self, Error> {
1921        let mut enc = MaybeUninit::<Self>::uninit();
1922        Self::init(&mut enc, sampling_rate, channels, application)?;
1923        // SAFETY: `init` succeeded, so it initialized `enc`.
1924        Ok(unsafe { enc.assume_init() })
1925    }
1926
1927    /// Builds an encoder in `slot`, memory that the caller provides, and
1928    /// returns it. The encoder is the same as the one of [`new`](Self::new).
1929    /// Like `new`, it cannot fail at present.
1930    ///
1931    /// Without the `heap` feature an encoder holds all of its state inline:
1932    /// about 150 KB, and 210 KB with the `dred` feature. `new` returns it
1933    /// through the stack, which needs more than 256 KB. `init` writes the
1934    /// encoder straight into `slot`, so building it needs only a little
1935    /// stack (less than 16 KB). With `heap` it writes the large parts
1936    /// straight into their heap memory.
1937    ///
1938    /// The intended use is memory that lives as long as the program, such
1939    /// as a `static`: build the encoder there once and never drop it.
1940    ///
1941    /// ```
1942    /// use core::mem::MaybeUninit;
1943    /// use opus1::{Application, Channels, OpusEncoder, SampleRate};
1944    ///
1945    /// static mut ENCODER: MaybeUninit<OpusEncoder> = MaybeUninit::uninit();
1946    ///
1947    /// // Run once at start-up.
1948    /// let slot = &raw mut ENCODER;
1949    /// // SAFETY: nothing else uses `ENCODER` at the same time.
1950    /// let encoder: &'static mut OpusEncoder =
1951    ///     OpusEncoder::init(unsafe { &mut *slot }, SampleRate::Hz16000, Channels::Mono, Application::Voip)?;
1952    ///
1953    /// let mut packet = [0u8; 1275];
1954    /// let len = encoder.encode(&[0.0f32; 320], 320, &mut packet)?;
1955    /// assert!(len > 0);
1956    /// # Ok::<(), opus1::Error>(())
1957    /// ```
1958    ///
1959    /// `init` does not drop what `slot` holds. With the `heap` feature an
1960    /// encoder owns heap memory, so a second `init` on the same slot leaks
1961    /// the memory of the first encoder. To free an encoder built with
1962    /// `init`, call [`MaybeUninit::assume_init_drop`] on `slot` when it is
1963    /// no longer used. Without `heap` an encoder owns no other memory, so
1964    /// nothing leaks and nothing needs to be dropped.
1965    ///
1966    /// [`reset_state`](Self::reset_state) also writes the new state in
1967    /// place, so it needs only a little stack too.
1968    pub fn init(
1969        slot: &mut MaybeUninit<Self>,
1970        sampling_rate: SampleRate,
1971        channels: Channels,
1972        application: Application,
1973    ) -> Result<&mut Self, Error> {
1974        // SAFETY: `slot` is valid for writes of `Self`, and `write_new`
1975        // initializes every field, so `slot` holds an encoder afterwards.
1976        unsafe {
1977            Self::write_new(
1978                slot.as_mut_ptr(),
1979                sampling_rate.hz() as i32,
1980                channels.count(),
1981                application,
1982                HeapMemory::Allocate,
1983            );
1984            Ok(slot.assume_init_mut())
1985        }
1986    }
1987
1988    /// Writes a new encoder to `this` field by field (see
1989    /// `crate::in_place`). The arguments must be valid. With
1990    /// [`HeapMemory::Allocate`] `this` may be uninitialized memory. With
1991    /// [`HeapMemory::Reuse`] it holds an encoder with the same channel
1992    /// count, and the new encoder keeps the heap memory of that one (feature
1993    /// `heap`): [`reset_state`](Self::reset_state).
1994    ///
1995    /// # Safety
1996    /// `this` must be valid for writes of `Self`, and with `Reuse` it must
1997    /// hold a valid encoder.
1998    unsafe fn write_new(
1999        this: *mut Self,
2000        sampling_rate: i32,
2001        channels: usize,
2002        application: Application,
2003        memory: HeapMemory,
2004    ) {
2005        let mode = modes::default_mode();
2006        // C `opus_encoder_init`: `st->mode = MODE_HYBRID` and
2007        // `st->bandwidth = OPUS_BANDWIDTH_FULLBAND`, whatever the application
2008        // and the sampling rate. Both are decided again for the first packet
2009        // that is coded.
2010        let (opus_mode, bw) = (OpusMode::Hybrid, Bandwidth::Fullband);
2011        // The restricted applications code without the lookahead that
2012        // aligns CELT with SILK, and keep no delay buffer.
2013        let low_delay = application.without_delay_buffer();
2014
2015        // SAFETY: the caller guarantees that `this` is valid for writes.
2016        // Each closure below writes the whole field it is given.
2017        unsafe {
2018            write_fields!(this, {
2019                #[cfg(not(feature = "heap"))]
2020                celt_enc = |p| CeltEncoder::write_new(p, mode, channels, sampling_rate),
2021                #[cfg(feature = "heap")]
2022                celt_enc = |p: *mut Box<CeltEncoder>| {
2023                    let celt = |q| CeltEncoder::write_new(q, mode, channels, sampling_rate);
2024                    in_place::write_box(p, memory, celt)
2025                },
2026                silk = |p| SilkEncoder::write_new(p, sampling_rate, channels, memory),
2027                application: application,
2028                sampling_rate: sampling_rate,
2029                channels: channels,
2030                bandwidth: bw,
2031                auto_bandwidth: bw,
2032                user_bandwidth: None,
2033                max_bandwidth: Bandwidth::Fullband,
2034                user_forced_mode: None,
2035                lfe: false,
2036                energy_mask: None,
2037                range_final: 0,
2038                first: true,
2039                silk_allow_bandwidth_switch: false,
2040                silk_in_wb_mode_without_variable_lp: false,
2041                silk_opus_can_switch: false,
2042                silk_lbrr_coded: 0,
2043                nonfinal_frame: false,
2044                stream_channels: channels,
2045                force_channels: None,
2046                prev_channels: 0,
2047                silk_to_mono: false,
2048                silk_bw_switch: false,
2049                // C `opus_encoder_init`: `hybrid_stereo_width_Q14 = 1 << 14`.
2050                hybrid_stereo_width_q14: 1 << 14,
2051                silk_stereo_width_q14: 1 << 14,
2052                width_mem: StereoWidthState::default(),
2053                stereo_width: 0.0,
2054                // C `opus_encoder_init`: `user_bitrate_bps = OPUS_AUTO` and
2055                // `bitrate_bps = 3000 + Fs * channels`. Each packet sets the
2056                // second again before it is read.
2057                user_bitrate: Bitrate::Auto,
2058                packet_bitrate_bps: 3000 + sampling_rate * channels as i32,
2059                complexity: 9,
2060                use_cbr: false,
2061                vbr_constraint: true,
2062                fec_config: InbandFec::Off,
2063                packet_loss_perc: 0,
2064                prev_frame_size: 0,
2065                prediction_disabled: false,
2066                variable_duration: FrameDuration::Argument,
2067                #[cfg(not(feature = "heap"))]
2068                celt_prefill = |p| in_place::write_zero(p),
2069                #[cfg(feature = "heap")]
2070                celt_prefill = |p: *mut Box<[f32; CELT_PREFILL]>| {
2071                    in_place::write_box(p, memory, |q| in_place::write_zero(q))
2072                },
2073                mode: opus_mode,
2074                prev_enc_mode: None,
2075                variable_hp_smth2_q15: silk_lin2log(60) << 8,
2076                hp_mem = |p| FixedVec::write_from_value(p, 0, channels * 2),
2077                integer_hp_at_48k: false,
2078                fixed_point_res_nrg: false,
2079
2080                #[cfg(not(feature = "heap"))]
2081                buf_filtered = |p| FixedVec::write_new(p),
2082                #[cfg(feature = "heap")]
2083                buf_filtered = |p: *mut Box<FixedVec<i16, OPUS_MAX_FRAME>>| {
2084                    in_place::write_box(p, memory, |q| FixedVec::write_new(q))
2085                },
2086                #[cfg(not(feature = "heap"))]
2087                delay_buffer = |p| FixedVec::write_from_value(p, 0.0, OPUS_DELAY_BUF),
2088                #[cfg(feature = "heap")]
2089                delay_buffer = |p: *mut Box<FixedVec<f32, OPUS_DELAY_BUF>>| {
2090                    in_place::write_box(p, memory, |q| FixedVec::write_from_value(q, 0.0, OPUS_DELAY_BUF))
2091                },
2092                #[cfg(not(feature = "heap"))]
2093                buf_celt_pcm = |p| FixedVec::write_new(p),
2094                #[cfg(feature = "heap")]
2095                buf_celt_pcm = |p: *mut Box<FixedVec<f32, OPUS_PCM_BUF>>| {
2096                    in_place::write_box(p, memory, |q| FixedVec::write_new(q))
2097                },
2098                encoder_buffer: if low_delay { 0 } else { (sampling_rate / 100) as usize },
2099                delay_compensation: if low_delay { 0 } else { (sampling_rate / 250) as usize },
2100                hp_mem_float: [0.0; 4],
2101                prev_hb_gain: 1.0,
2102                #[cfg(all(feature = "analysis", not(feature = "heap")))]
2103                analysis = |p| analysis::TonalityAnalysisState::write_new(p, sampling_rate),
2104                #[cfg(all(feature = "analysis", feature = "heap"))]
2105                analysis = |p: *mut Box<analysis::TonalityAnalysisState>| {
2106                    let state = |q| analysis::TonalityAnalysisState::write_new(q, sampling_rate);
2107                    in_place::write_box(p, memory, state)
2108                },
2109                analysis_gate: AnalysisGate::FloatBuild,
2110                float_api: true,
2111                last_analysis: AnalysisInfo::default(),
2112                // C `opus_encoder_init`: `voice_ratio = -1`, `signal_type =
2113                // OPUS_AUTO`, `lsb_depth = 24`.
2114                voice_ratio: -1,
2115                signal: Signal::Auto,
2116                lsb_depth: 24,
2117                peak_signal_energy: 0.0,
2118                use_dtx: false,
2119                silk_use_dtx: false,
2120                silk_channels_internal: channels,
2121                nb_no_activity_ms_q1: 0,
2122                rc: RangeCoder::new_encoder(1),
2123                #[cfg(all(feature = "dred", not(feature = "heap")))]
2124                dred = |p| dnn::dred::encoder::DredEncoder::write_new(p, sampling_rate, channels),
2125                #[cfg(all(feature = "dred", feature = "heap"))]
2126                dred = |p: *mut Box<dnn::dred::encoder::DredEncoder>| {
2127                    let dred = |q| dnn::dred::encoder::DredEncoder::write_new(q, sampling_rate, channels);
2128                    in_place::write_box(p, memory, dred)
2129                },
2130            });
2131        }
2132    }
2133
2134    /// The decisions libopus's `opus_encode_native` makes for a packet
2135    /// (opus_encoder.c:1408-1695): the mode, the audio bandwidth, whether
2136    /// the packet carries in-band FEC, and whether a redundant CELT frame
2137    /// goes with a change of mode. `n_bytes` is the largest packet allowed.
2138    /// `detected_bandwidth` is the bandwidth the speech and music analysis
2139    /// found in the input (C `st->detected_bandwidth`), `None` when it did
2140    /// not run.
2141    fn decide_mode_and_bandwidth(
2142        &mut self,
2143        frame_size: usize,
2144        frame_rate: i32,
2145        n_bytes: usize,
2146        detected_bandwidth: Option<Bandwidth>,
2147    ) -> FrameDecisions {
2148        // C 1325-1334, `st->bitrate_bps`: the bitrate asked for, or what the
2149        // output buffer can hold when that is less. CBR codes whole bytes,
2150        // so its bitrate is the packet's.
2151        let bitrate = self.packet_bitrate_bps;
2152        // C 1407: the rate the largest packet allowed stands for.
2153        let max_rate = bits_to_bitrate(8 * n_bytes as i32, self.sampling_rate, frame_size);
2154        // C 1413-1426: how likely the input is speech, in Q7 (0 to 127): set
2155        // by the caller, or from the analysis of the last packet that was
2156        // not silent, or from the application.
2157        let voice_est = match self.signal {
2158            Signal::Voice => 127,
2159            Signal::Music => 0,
2160            Signal::Auto if self.voice_ratio >= 0 => {
2161                let v = (self.voice_ratio * 327) >> 8;
2162                // "For AUDIO, never be more than 90% confident of having
2163                // speech".
2164                if self.application == Application::Audio { v.min(115) } else { v }
2165            }
2166            Signal::Auto if self.application == Application::Voip => 115,
2167            Signal::Auto => 48,
2168        };
2169
2170        // C 1428-1456: the channels the packet codes, then the rate the
2171        // decisions go by for that many channels.
2172        self.decide_stream_channels(bitrate, frame_rate, voice_est);
2173
2174        // --- Mode: SILK or CELT (C 1466-1539) ---
2175        let mut mode = if self.application == Application::RestrictedSilk {
2176            OpusMode::SilkOnly
2177        } else if matches!(self.application, Application::RestrictedLowDelay | Application::RestrictedCelt) {
2178            OpusMode::CeltOnly
2179        } else if let Some(forced) = self.user_forced_mode {
2180            // C 1528-1530: the mode the caller asked for. The rules below
2181            // can still change it: frames under 10 ms are CELT-only, SILK
2182            // above wideband is Hybrid, Hybrid at wideband or below is SILK.
2183            forced
2184        } else {
2185            let equiv = compute_equiv_rate(
2186                bitrate,
2187                self.stream_channels,
2188                frame_rate,
2189                !self.use_cbr,
2190                None,
2191                self.complexity,
2192                self.packet_loss_perc,
2193            );
2194            let threshold = compute_mode_threshold(
2195                self.application,
2196                self.stereo_width,
2197                self.prev_enc_mode == Some(OpusMode::CeltOnly),
2198                self.prev_enc_mode.is_some(),
2199                voice_est,
2200            );
2201            // C 1513, at every input rate: 8, 12 and 16 kHz input is coded
2202            // by CELT too when the bitrate is high for speech.
2203            let mut mode = if equiv >= threshold {
2204                OpusMode::CeltOnly
2205            } else {
2206                OpusMode::SilkOnly
2207            };
2208            // C 1515-1518: with FEC on and enough packet loss, use SILK: only
2209            // SILK carries the FEC. "Unless the FEC is set to 2, in which
2210            // case we don't switch to SILK if we're confident we have
2211            // music."
2212            if self.fec_config != InbandFec::Off
2213                && self.packet_loss_perc > (128 - voice_est) >> 4
2214                && (self.fec_config != InbandFec::OnUnlessMusic || voice_est > 25)
2215            {
2216                mode = OpusMode::SilkOnly;
2217            }
2218            // C 1519-1522: "When encoding voice and DTX is enabled but the
2219            // generalized DTX cannot be used, use SILK in order to make use
2220            // of its DTX."
2221            if self.silk_use_dtx && voice_est > 100 {
2222                mode = OpusMode::SilkOnly;
2223            }
2224            // C 1525-1527: a budget representing less than 6 kb/s (9 kb/s for
2225            // frames shorter than 20 ms) cannot carry SILK. CELT-only codes
2226            // it as a small valid packet instead.
2227            let tiny_budget_rate = if frame_rate > 50 { 9000 } else { 6000 };
2228            if (n_bytes as i32) < bitrate_to_bits(tiny_budget_rate, self.sampling_rate, frame_size) / 8 {
2229                mode = OpusMode::CeltOnly;
2230            }
2231            mode
2232        };
2233        // C 1532-1537: SILK frames are 10 ms or longer; 2.5 and 5 ms frames
2234        // are CELT-only. `RestrictedSilk` never gets here with such a
2235        // frame: `frame_size_select` refuses it.
2236        if mode != OpusMode::CeltOnly && frame_size < self.sampling_rate as usize / 100 {
2237            mode = OpusMode::CeltOnly;
2238        }
2239        // C 1538-1539: a low-frequency-effects channel is coded by CELT,
2240        // except by an encoder that has only SILK.
2241        if self.lfe && self.application != Application::RestrictedSilk {
2242            mode = OpusMode::CeltOnly;
2243        }
2244
2245        // C 1541-1558: a switch between CELT-only and SILK-only or Hybrid
2246        // is bridged by a redundant 5 ms CELT frame.
2247        //
2248        // - Leaving CELT-only: the frame goes in front of the first packet
2249        //   of the new mode.
2250        // - Entering CELT-only: this packet stays in the old mode and gets
2251        //   the frame at its end; the next packet is CELT-only. A packet
2252        //   shorter than 10 ms cannot stay, so it switches at once, without
2253        //   the frame.
2254        let (mut redundancy, mut celt_to_silk, mut to_celt) = (false, false, false);
2255        if let Some(prev) = self.prev_enc_mode {
2256            let (is_celt, was_celt) = (mode == OpusMode::CeltOnly, prev == OpusMode::CeltOnly);
2257            if is_celt != was_celt {
2258                redundancy = true;
2259                celt_to_silk = !is_celt;
2260                if !celt_to_silk {
2261                    if frame_size >= self.sampling_rate as usize / 100 {
2262                        mode = prev;
2263                        to_celt = true;
2264                    } else {
2265                        redundancy = false;
2266                    }
2267                }
2268            }
2269        }
2270        // C 1560-1571: "Delay stereo->mono transition by two frames so that
2271        // SILK can do a smooth downmix". The last packet before mono still
2272        // codes two channels, with SILK's side signal faded out. Not around
2273        // CELT-only packets, which change the channel count at once.
2274        if self.stream_channels == 1
2275            && self.prev_channels == 2
2276            && !self.silk_to_mono
2277            && mode != OpusMode::CeltOnly
2278            && self.prev_enc_mode != Some(OpusMode::CeltOnly)
2279        {
2280            self.silk_to_mono = true;
2281            self.stream_channels = 2;
2282        } else {
2283            self.silk_to_mono = false;
2284        }
2285
2286        // C 1576-1581: SILK starts afresh after CELT-only packets.
2287        let prefill =
2288            mode != OpusMode::CeltOnly && self.prev_enc_mode == Some(OpusMode::CeltOnly);
2289
2290        // C 1573: the rate the next decisions go by counts the mode.
2291        let equiv_rate = compute_equiv_rate(
2292            bitrate,
2293            self.stream_channels,
2294            frame_rate,
2295            !self.use_cbr,
2296            Some(mode),
2297            self.complexity,
2298            self.packet_loss_perc,
2299        );
2300
2301        // --- Bandwidth from the rate (C 1583-1627) ---
2302        // SILK and Hybrid only reconsider it when SILK allows a switch, which
2303        // is in a pause or after 5 s at the latest.
2304        if mode == OpusMode::CeltOnly || self.first || self.silk_allow_bandwidth_switch {
2305            // Indices: 0 narrowband .. 4 fullband.
2306            let mut bandwidth = 4usize;
2307            loop {
2308                // Thresholds between this bandwidth and the next lower one,
2309                // interpolated between music and voice by `voice_est`.
2310                let entry = 2 * (bandwidth - 1);
2311                let interpolate = |i: usize| {
2312                    MUSIC_BANDWIDTH_THRESHOLDS[i]
2313                        + ((voice_est
2314                            * voice_est
2315                            * (VOICE_BANDWIDTH_THRESHOLDS[i] - MUSIC_BANDWIDTH_THRESHOLDS[i]))
2316                            >> 14)
2317                };
2318                let (mut threshold, hysteresis) = (interpolate(entry), interpolate(entry + 1));
2319                if !self.first {
2320                    if bandwidth_fec_index(self.auto_bandwidth) >= bandwidth {
2321                        threshold -= hysteresis;
2322                    } else {
2323                        threshold += hysteresis;
2324                    }
2325                }
2326                if equiv_rate >= threshold {
2327                    break;
2328                }
2329                bandwidth -= 1;
2330                if bandwidth == 0 {
2331                    break;
2332                }
2333            }
2334            // Mediumband is only used on request or during transitions.
2335            if bandwidth == 1 {
2336                bandwidth = 2;
2337            }
2338            self.auto_bandwidth = bandwidth_from_fec_index(bandwidth);
2339            self.bandwidth = self.auto_bandwidth;
2340            // No switch above wideband until SILK itself runs at wideband.
2341            if !self.first
2342                && mode != OpusMode::CeltOnly
2343                && !self.silk_in_wb_mode_without_variable_lp
2344                && bandwidth > 2
2345            {
2346                self.bandwidth = Bandwidth::Wideband;
2347            }
2348        }
2349        // C 1629-1630: nothing above the maximum the caller set.
2350        if bandwidth_fec_index(self.bandwidth) > bandwidth_fec_index(self.max_bandwidth) {
2351            self.bandwidth = self.max_bandwidth;
2352        }
2353        // C 1632-1633: a bandwidth the caller asked for wins.
2354        if let Some(user) = self.user_bandwidth {
2355            self.bandwidth = user;
2356        }
2357        // C 1636-1639: no Hybrid when the packet cannot exceed 15 kb/s.
2358        if mode != OpusMode::CeltOnly
2359            && max_rate < 15000
2360            && bandwidth_fec_index(self.bandwidth) > 2
2361        {
2362            self.bandwidth = Bandwidth::Wideband;
2363        }
2364        // C 1643-1650: nothing above the input's Nyquist frequency.
2365        let nyquist_bandwidth = match self.sampling_rate {
2366            8000 => Bandwidth::Narrowband,
2367            12000 => Bandwidth::Mediumband,
2368            16000 => Bandwidth::Wideband,
2369            24000 => Bandwidth::Superwideband,
2370            _ => Bandwidth::Fullband,
2371        };
2372        if bandwidth_fec_index(self.bandwidth) > bandwidth_fec_index(nyquist_bandwidth) {
2373            self.bandwidth = nyquist_bandwidth;
2374        }
2375        // C 1651-1674: "Use detected bandwidth to reduce the encoded
2376        // bandwidth", unless the caller asked for one. Not below a
2377        // bandwidth that grows with the rate, "just in case the detector
2378        // gets it wrong", and in SILK and Hybrid not below wideband.
2379        if let (Some(detected), None) = (detected_bandwidth, self.user_bandwidth) {
2380            let sc = self.stream_channels as i32;
2381            let celt = mode == OpusMode::CeltOnly;
2382            let min_detected = if equiv_rate <= 18000 * sc && celt {
2383                Bandwidth::Narrowband
2384            } else if equiv_rate <= 24000 * sc && celt {
2385                Bandwidth::Mediumband
2386            } else if equiv_rate <= 30000 * sc {
2387                Bandwidth::Wideband
2388            } else if equiv_rate <= 44000 * sc {
2389                Bandwidth::Superwideband
2390            } else {
2391                Bandwidth::Fullband
2392            };
2393            let detected = detected.max_by_index(min_detected);
2394            if bandwidth_fec_index(self.bandwidth) > bandwidth_fec_index(detected) {
2395                self.bandwidth = detected;
2396            }
2397        }
2398
2399        // --- In-band FEC (C 1675) ---
2400        // decide_fec can lower the bandwidth when a high loss rate asks for
2401        // FEC at any cost.
2402        let lbrr_coded = decide_fec(
2403            (self.fec_config != InbandFec::Off) as i32,
2404            self.packet_loss_perc,
2405            self.silk_lbrr_coded,
2406            mode,
2407            &mut self.bandwidth,
2408            equiv_rate,
2409        );
2410        self.silk_lbrr_coded = lbrr_coded;
2411
2412        // C 1680-1695, after decide_fec: CELT has no mediumband; SILK above
2413        // wideband is Hybrid; Hybrid at wideband or below is SILK-only.
2414        // Running this before decide_fec left Hybrid with a wideband frame
2415        // when FEC lowered the bandwidth: CELT then had no band to code and
2416        // divided by zero.
2417        if mode == OpusMode::CeltOnly && self.bandwidth == Bandwidth::Mediumband {
2418            self.bandwidth = Bandwidth::Wideband;
2419        }
2420        // C 1683-1684: a low-frequency-effects channel is narrowband,
2421        // whatever was asked for.
2422        if self.lfe {
2423            self.bandwidth = Bandwidth::Narrowband;
2424        }
2425        // C 1688-1689: SILK alone codes at most wideband.
2426        if self.application == Application::RestrictedSilk && bandwidth_fec_index(self.bandwidth) > 2 {
2427            self.bandwidth = Bandwidth::Wideband;
2428        }
2429        let above_wideband = bandwidth_fec_index(self.bandwidth) > 2;
2430        if mode == OpusMode::SilkOnly && above_wideband {
2431            mode = OpusMode::Hybrid;
2432        }
2433        if mode == OpusMode::Hybrid && !above_wideband {
2434            mode = OpusMode::SilkOnly;
2435        }
2436        // C `st->mode`.
2437        self.mode = mode;
2438        FrameDecisions {
2439            mode,
2440            bandwidth: self.bandwidth,
2441            lbrr_coded,
2442            redundancy,
2443            celt_to_silk,
2444            to_celt,
2445            prefill,
2446            equiv_rate,
2447        }
2448    }
2449
2450    /// libopus's choice of the channels a packet codes
2451    /// (opus_encoder.c:1408-1451): `stream_channels`.
2452    ///
2453    /// - A forced count wins for stereo input.
2454    /// - Otherwise stereo input is coded in stereo when the equivalent rate
2455    ///   for two channels is above a threshold between 17 kb/s (music) and
2456    ///   19 kb/s (speech), with 1 kb/s of hysteresis.
2457    /// - Mono input is coded in mono.
2458    fn decide_stream_channels(&mut self, bitrate: i32, frame_rate: i32, voice_est: i32) {
2459        // C `stereo_voice_threshold` and `stereo_music_threshold`.
2460        const STEREO_VOICE_THRESHOLD: i32 = 19000;
2461        const STEREO_MUSIC_THRESHOLD: i32 = 17000;
2462        if let (Some(forced), 2) = (self.force_channels, self.channels) {
2463            self.stream_channels = forced;
2464        } else if self.channels == 2 {
2465            // C 1409: the rate for the input's channels, before the mode is
2466            // known.
2467            let equiv_rate = compute_equiv_rate(
2468                bitrate,
2469                self.channels,
2470                frame_rate,
2471                !self.use_cbr,
2472                None,
2473                self.complexity,
2474                self.packet_loss_perc,
2475            );
2476            let mut threshold = STEREO_MUSIC_THRESHOLD
2477                + ((voice_est * voice_est * (STEREO_VOICE_THRESHOLD - STEREO_MUSIC_THRESHOLD))
2478                    >> 14);
2479            if self.stream_channels == 2 {
2480                threshold -= 1000;
2481            } else {
2482                threshold += 1000;
2483            }
2484            self.stream_channels = if equiv_rate > threshold { 2 } else { 1 };
2485        } else {
2486            self.stream_channels = self.channels;
2487        }
2488    }
2489
2490    /// libopus `OPUS_SET_BITRATE`: the bitrate of the packets, for all
2491    /// channels together. The default is [`Bitrate::Auto`], as in libopus:
2492    /// `60 * rate / frame_size + rate * channels` b/s, for example
2493    /// 19,000 b/s for 16 kHz mono in 20 ms frames.
2494    ///
2495    /// As in libopus, an explicit bitrate is raised to at least 500 bits
2496    /// per second and limited to at most 750,000 bits per second per
2497    /// channel. The length of the output buffer of each
2498    /// [`encode`](Self::encode) call can lower it further.
2499    pub fn set_bitrate(&mut self, bitrate: Bitrate) {
2500        self.user_bitrate = match bitrate {
2501            Bitrate::BitsPerSecond(bps) => Bitrate::within_limits(
2502                Bitrate::bps_to_i32(bps).clamp(500, 750_000 * self.channels as i32),
2503            ),
2504            other => other,
2505        };
2506    }
2507
2508    /// The bitrate that was set, after its limits were applied.
2509    pub fn bitrate_setting(&self) -> Bitrate {
2510        self.user_bitrate
2511    }
2512
2513    /// libopus `OPUS_GET_BITRATE`: the bitrate in bits per second that the
2514    /// setting stands for. [`Bitrate::Auto`] and [`Bitrate::Max`] depend
2515    /// on the duration of the last frame that was coded (2.5 ms before the
2516    /// first one), and every setting counts with at most what a 1276-byte
2517    /// packet per frame carries.
2518    pub fn bitrate(&self) -> i32 {
2519        self.user_bitrate_to_bitrate(self.prev_frame_size, OPUS_MAX_PACKET_BYTES)
2520    }
2521
2522    /// libopus `user_bitrate_to_bitrate` (opus_encoder.c:733): the bitrate
2523    /// of the setting for frames of `frame_size` samples (0 counts as
2524    /// 2.5 ms), at most what `max_data_bytes` bytes per frame carry.
2525    fn user_bitrate_to_bitrate(&self, frame_size: usize, max_data_bytes: usize) -> i32 {
2526        let fs = self.sampling_rate;
2527        let frame_size = if frame_size == 0 { fs as usize / 400 } else { frame_size };
2528        let max_bitrate = bits_to_bitrate(8 * max_data_bytes as i32, fs, frame_size);
2529        let user_bitrate = match self.user_bitrate {
2530            Bitrate::Auto => 60 * fs / frame_size as i32 + fs * self.channels as i32,
2531            Bitrate::Max => 1_500_000,
2532            Bitrate::BitsPerSecond(bps) => Bitrate::bps_to_i32(bps),
2533        };
2534        user_bitrate.min(max_bitrate)
2535    }
2536
2537    /// libopus `OPUS_SET_COMPLEXITY`: 0 to 10. Higher values spend more
2538    /// processor time for better quality. The default is 9. A value above
2539    /// 10 is refused with [`BadArg`](crate::ErrorKind::BadArg), and the
2540    /// setting stays.
2541    pub fn set_complexity(&mut self, complexity: u8) -> Result<(), Error> {
2542        if complexity > 10 {
2543            return Err(Error::INVALID_COMPLEXITY);
2544        }
2545        self.complexity = i32::from(complexity);
2546        Ok(())
2547    }
2548
2549    /// The complexity set with [`set_complexity`](Self::set_complexity).
2550    pub fn complexity(&self) -> u8 {
2551        self.complexity as u8
2552    }
2553
2554    /// libopus `OPUS_SET_VBR`: a variable bitrate (`true`, the default) or a
2555    /// constant one (`false`). With a constant bitrate every packet of the
2556    /// same duration has the same size.
2557    pub fn set_vbr(&mut self, vbr: bool) {
2558        self.use_cbr = !vbr;
2559    }
2560
2561    /// Whether the bitrate is variable ([`set_vbr`](Self::set_vbr)).
2562    pub fn vbr(&self) -> bool {
2563        !self.use_cbr
2564    }
2565
2566    /// libopus `OPUS_SET_VBR_CONSTRAINT`: with a variable bitrate, keep
2567    /// CELT-only packets close to the bitrate (`true`, the default). Without
2568    /// the constraint a CELT-only packet can take more bytes for a hard
2569    /// frame and fewer for an easy one. It has no effect with a constant
2570    /// bitrate. Hybrid packets are never constrained, as in libopus.
2571    pub fn set_vbr_constraint(&mut self, constrained: bool) {
2572        self.vbr_constraint = constrained;
2573    }
2574
2575    /// Whether the variable bitrate is constrained
2576    /// ([`set_vbr_constraint`](Self::set_vbr_constraint)).
2577    pub fn vbr_constraint(&self) -> bool {
2578        self.vbr_constraint
2579    }
2580
2581    /// libopus `OPUS_SET_INBAND_FEC`: let SILK and Hybrid packets carry a
2582    /// low-bitrate copy of the frame before them (in-band forward error
2583    /// correction, FEC), so that a decoder can rebuild a lost packet. The
2584    /// copy is coded only when
2585    /// [`set_packet_loss_perc`](Self::set_packet_loss_perc) is above 0 and
2586    /// the bitrate leaves room for it. [`InbandFec::Off`] by default.
2587    ///
2588    /// With [`InbandFec::On`] the encoder moves to SILK for the FEC when
2589    /// the packet loss is high enough. With [`InbandFec::OnUnlessMusic`] it
2590    /// does not do so when it is confident that the input is music.
2591    pub fn set_inband_fec(&mut self, fec: InbandFec) {
2592        self.fec_config = fec;
2593    }
2594
2595    /// The in-band FEC setting (libopus `OPUS_GET_INBAND_FEC`).
2596    pub fn inband_fec(&self) -> InbandFec {
2597        self.fec_config
2598    }
2599
2600    /// libopus `OPUS_SET_SIGNAL`: what the input is. The default is
2601    /// [`Signal::Auto`].
2602    ///
2603    /// `Voice` and `Music` set the speech probability that the choice of
2604    /// mode, bandwidth and channels goes by: 127 or 0 in 127. With `Auto`
2605    /// the encoder estimates it with its speech and music analysis from
2606    /// complexity 7 on, and takes a value of the application below.
2607    pub fn set_signal(&mut self, signal: Signal) {
2608        self.signal = signal;
2609    }
2610
2611    /// The signal type set with [`set_signal`](Self::set_signal).
2612    pub fn signal(&self) -> Signal {
2613        self.signal
2614    }
2615
2616    /// libopus `OPUS_SET_LSB_DEPTH`: the precision of the input in bits, 8
2617    /// to 24. The default is 24. Any other value is refused with
2618    /// [`BadArg`](crate::ErrorKind::BadArg), and the setting stays.
2619    ///
2620    /// Samples below `2^-depth` count as digital silence, and the noise
2621    /// floor of the analysis and of CELT's allocation follows it.
2622    /// [`encode_i16`](Self::encode_i16) codes with at most 16 bits, as
2623    /// libopus `opus_encode` does.
2624    pub fn set_lsb_depth(&mut self, depth: u8) -> Result<(), Error> {
2625        if !(8..=24).contains(&depth) {
2626            return Err(Error::INVALID_LSB_DEPTH);
2627        }
2628        self.lsb_depth = i32::from(depth);
2629        Ok(())
2630    }
2631
2632    /// The input precision set with [`set_lsb_depth`](Self::set_lsb_depth).
2633    pub fn lsb_depth(&self) -> u8 {
2634        self.lsb_depth as u8
2635    }
2636
2637    /// libopus `OPUS_SET_DTX`: discontinuous transmission (DTX). Off by
2638    /// default.
2639    ///
2640    /// With DTX the encoder sends packets of 1 byte, a TOC byte without
2641    /// audio, while the input is inactive. The first 200 ms without
2642    /// activity are still coded. Then up to 400 ms are left out, after
2643    /// which one frame is coded again. A decoder conceals a 1-byte packet
2644    /// like a lost one; after SILK frames it fills the gap with comfort
2645    /// noise.
2646    ///
2647    /// Who decides that a frame is inactive, as in libopus:
2648    ///
2649    /// - Digital silence is always inactive.
2650    /// - When the speech and music analysis has a result (from complexity
2651    ///   7 on, at 16 to 48 kHz), a frame is inactive when its activity
2652    ///   probability is below 0.1 and its energy is more than 25 dB below
2653    ///   the peak energy of the active frames. This works in every mode.
2654    /// - Otherwise SILK's voice activity detector decides, and only SILK
2655    ///   and Hybrid frames are left out. The encoder then codes speech
2656    ///   with SILK (an estimated speech probability above 100 in 127).
2657    ///   CELT-only frames are left out only when they are digital silence.
2658    ///
2659    /// With a constant bitrate the 1-byte packets are not padded.
2660    pub fn set_dtx(&mut self, enabled: bool) {
2661        self.use_dtx = enabled;
2662    }
2663
2664    /// Whether DTX is on ([`set_dtx`](Self::set_dtx), libopus
2665    /// `OPUS_GET_DTX`).
2666    pub fn dtx(&self) -> bool {
2667        self.use_dtx
2668    }
2669
2670    /// libopus `OPUS_GET_IN_DTX`: whether the encoder is in a DTX pause
2671    /// after the last packet. The input has then been inactive for at
2672    /// least 200 ms (10 frames of 20 ms), and the last packet was left
2673    /// out or is one of the frames coded during the pause.
2674    ///
2675    /// When the last packet used SILK's DTX and the last frame coded was
2676    /// SILK or Hybrid, this reads SILK's count of frames without speech:
2677    /// of the mid channel, and also of the side channel when the last
2678    /// frame coded it. Otherwise, with DTX on, it reads the time without
2679    /// activity of the Opus layer. With DTX off it is `false`.
2680    pub fn in_dtx(&self) -> bool {
2681        use silk::define::NB_SPEECH_FRAMES_BEFORE_DTX;
2682        let silk_frame = matches!(self.prev_enc_mode, Some(OpusMode::SilkOnly | OpusMode::Hybrid));
2683        if self.silk_use_dtx && silk_frame {
2684            let mid = self.silk.mid();
2685            let mut in_dtx = mid.s_cmn.no_speech_counter >= NB_SPEECH_FRAMES_BEFORE_DTX;
2686            // "Stereo: check second channel unless only the middle channel
2687            // was encoded."
2688            if in_dtx && self.silk_channels_internal == 2 && mid.stereo.prev_decode_only_middle == 0 {
2689                in_dtx = self
2690                    .silk
2691                    .side()
2692                    .is_some_and(|side| side.s_cmn.no_speech_counter >= NB_SPEECH_FRAMES_BEFORE_DTX);
2693            }
2694            in_dtx
2695        } else {
2696            self.use_dtx && self.nb_no_activity_ms_q1 >= NB_SPEECH_FRAMES_BEFORE_DTX * 20 * 2
2697        }
2698    }
2699
2700    /// See `internals::analysis::set_analysis_gate`.
2701    #[cfg(feature = "__internals")]
2702    pub(crate) fn set_analysis_gate(&mut self, gate: AnalysisGate) {
2703        self.analysis_gate = gate;
2704    }
2705
2706    /// See `internals::analysis::analysis_gate`.
2707    #[cfg(feature = "__internals")]
2708    pub(crate) fn analysis_gate(&self) -> AnalysisGate {
2709        self.analysis_gate
2710    }
2711
2712    /// See `internals::analysis::last_analysis_info`.
2713    #[cfg(feature = "__internals")]
2714    pub(crate) fn last_analysis_info(&self) -> AnalysisInfo {
2715        self.last_analysis
2716    }
2717
2718    /// Whether the analysis runs for the next packet (C 1249-1253): the
2719    /// complexity reaches the gate, the input rate is 16 to 48 kHz, and the
2720    /// application is not `RestrictedSilk`.
2721    #[cfg(feature = "analysis")]
2722    fn analysis_runs(&self) -> bool {
2723        self.analysis_gate.min_complexity().is_some_and(|c| self.complexity >= c)
2724            && (16000..=48000).contains(&self.sampling_rate)
2725            && self.application != Application::RestrictedSilk
2726    }
2727
2728    /// libopus `OPUS_SET_PACKET_LOSS_PERC`: the packet loss the network is
2729    /// expected to have, 0 to 100 percent. The default is 0. Higher values
2730    /// make the packets more robust against loss, at the cost of quality
2731    /// without loss. A value above 100 is refused with
2732    /// [`BadArg`](crate::ErrorKind::BadArg), and the setting stays.
2733    pub fn set_packet_loss_perc(&mut self, percent: u8) -> Result<(), Error> {
2734        if percent > 100 {
2735            return Err(Error::INVALID_PACKET_LOSS);
2736        }
2737        self.packet_loss_perc = i32::from(percent);
2738        Ok(())
2739    }
2740
2741    /// The expected packet loss in percent
2742    /// ([`set_packet_loss_perc`](Self::set_packet_loss_perc)).
2743    pub fn packet_loss_perc(&self) -> u8 {
2744        self.packet_loss_perc as u8
2745    }
2746
2747    /// libopus `OPUS_SET_DRED_DURATION` (feature `dred`): how much audio
2748    /// before each packet the packet carries again as deep redundancy
2749    /// (DRED), in frames of 10 ms, 0 to 104. 0, the default, turns DRED
2750    /// off. A value above 104 is refused with
2751    /// [`BadArg`](crate::ErrorKind::BadArg), and the setting stays.
2752    ///
2753    /// DRED takes part of the bitrate, and only with an expected packet
2754    /// loss ([`set_packet_loss_perc`](Self::set_packet_loss_perc)) above
2755    /// 0. How much depends on the loss, on in-band FEC and on the
2756    /// bitrate; at too low a bitrate it takes nothing. The data goes into
2757    /// the padding of the packet, as the packet extension with ID 126, in
2758    /// the first frame that is coded. A decoder that knows nothing of DRED
2759    /// skips it. Decode it with [`OpusDredDecoder`] and
2760    /// [`OpusDecoder::dred_decode`].
2761    ///
2762    /// [`reset_state`](Self::reset_state) sets the duration back to 0, as
2763    /// libopus does.
2764    #[cfg(feature = "dred")]
2765    pub fn set_dred_duration(&mut self, frames: u8) -> Result<(), Error> {
2766        self.dred.set_duration(i32::from(frames))
2767    }
2768
2769    /// libopus `OPUS_GET_DRED_DURATION` (feature `dred`): the DRED duration
2770    /// in frames of 10 ms ([`set_dred_duration`](Self::set_dred_duration)).
2771    #[cfg(feature = "dred")]
2772    pub fn dred_duration(&self) -> u8 {
2773        self.dred.duration() as u8
2774    }
2775
2776    /// libopus `OPUS_SET_DNN_BLOB` on an encoder (feature `dred`): loads the
2777    /// models of the DRED encoder (the RDOVAE encoder and PitchDNN) from a blob
2778    /// in the libopus format, and returns the group it loaded,
2779    /// [`DnnModels::DRED_ENCODER`]. When the blob does not hold all of their
2780    /// arrays, returns [`BadArg`](crate::ErrorKind::BadArg) and keeps the
2781    /// models it had. [`DnnBlob::builtin`] brings back the built-in weights.
2782    /// Without the models the encoder writes no DRED data.
2783    ///
2784    /// libopus offers the request only when built with `USE_WEIGHTS_FILE`
2785    /// and returns `OPUS_BAD_ARG` on a failure.
2786    #[cfg(feature = "dred")]
2787    pub fn set_dnn_blob(&mut self, blob: &DnnBlob) -> Result<DnnModels, Error> {
2788        self.dred.load(blob)
2789    }
2790
2791    /// libopus `OPUS_SET_FORCE_MODE`: ask for a coding mode instead of the
2792    /// automatic choice. `None` gives the choice back to the encoder.
2793    ///
2794    /// The mode is a request, as in libopus. The rules that keep a packet
2795    /// valid still apply, in this order:
2796    ///
2797    /// - A `RestrictedLowDelay` or `RestrictedCelt` encoder codes CELT-only
2798    ///   whatever is asked, and a `RestrictedSilk` encoder SILK-only.
2799    /// - Frames shorter than 10 ms are CELT-only.
2800    /// - A low-frequency-effects encoder ([`set_lfe`](Self::set_lfe)) codes
2801    ///   CELT-only, unless it is a `RestrictedSilk` encoder.
2802    /// - SILK-only above wideband becomes Hybrid, and Hybrid at wideband or
2803    ///   below becomes SILK-only. To get SILK-only from 24 or 48 kHz input,
2804    ///   also limit the bandwidth with
2805    ///   [`set_bandwidth`](Self::set_bandwidth) or
2806    ///   [`set_max_bandwidth`](Self::set_max_bandwidth).
2807    pub fn set_force_mode(&mut self, mode: Option<ForcedMode>) {
2808        self.user_forced_mode = mode.map(|mode| match mode {
2809            ForcedMode::SilkOnly => OpusMode::SilkOnly,
2810            ForcedMode::Hybrid => OpusMode::Hybrid,
2811            ForcedMode::CeltOnly => OpusMode::CeltOnly,
2812        });
2813    }
2814
2815    /// The mode set with [`set_force_mode`](Self::set_force_mode): `None`
2816    /// when the encoder chooses the mode itself. libopus has no request to
2817    /// read it.
2818    pub fn force_mode(&self) -> Option<ForcedMode> {
2819        self.user_forced_mode.map(|mode| match mode {
2820            OpusMode::SilkOnly => ForcedMode::SilkOnly,
2821            OpusMode::Hybrid => ForcedMode::Hybrid,
2822            OpusMode::CeltOnly => ForcedMode::CeltOnly,
2823        })
2824    }
2825
2826    /// libopus `OPUS_SET_BANDWIDTH`: code this audio bandwidth instead of
2827    /// the one the bitrate calls for. `None`, the default, gives the choice
2828    /// back to the encoder (libopus `OPUS_AUTO`).
2829    ///
2830    /// The bandwidth never exceeds what the input sampling rate can carry.
2831    /// CELT has no mediumband and codes wideband instead. SILK codes at the
2832    /// internal rate of the bandwidth (8, 12 or 16 kHz); a running SILK
2833    /// encoder moves there one step at a time, when the signal lets it. A
2834    /// [`RestrictedSilk`](Application::RestrictedSilk) encoder codes at most
2835    /// wideband.
2836    pub fn set_bandwidth(&mut self, bandwidth: Option<Bandwidth>) {
2837        self.user_bandwidth = bandwidth;
2838    }
2839
2840    /// The value set with [`set_bandwidth`](Self::set_bandwidth): `None`
2841    /// when the encoder chooses the bandwidth itself. This is not libopus
2842    /// `OPUS_GET_BANDWIDTH`, which [`bandwidth`](Self::bandwidth) answers.
2843    pub fn bandwidth_setting(&self) -> Option<Bandwidth> {
2844        self.user_bandwidth
2845    }
2846
2847    /// libopus `OPUS_GET_BANDWIDTH` of the encoder: the audio bandwidth of
2848    /// the last packet that was coded, whether the encoder chose it or it
2849    /// was set. Before the first packet and after
2850    /// [`reset_state`](Self::reset_state) it is [`Bandwidth::Fullband`], the
2851    /// value libopus starts with.
2852    ///
2853    /// For a packet too small to code any audio, libopus decides no
2854    /// bandwidth, so the value stays that of the packet before. (The first
2855    /// byte of such a packet can name another bandwidth.) The setting
2856    /// itself is [`bandwidth_setting`](Self::bandwidth_setting).
2857    pub fn bandwidth(&self) -> Bandwidth {
2858        self.bandwidth
2859    }
2860
2861    /// libopus `OPUS_SET_MAX_BANDWIDTH`: the widest audio bandwidth the
2862    /// automatic choice may take. The default is
2863    /// [`Bandwidth::Fullband`]. A bandwidth set with
2864    /// [`set_bandwidth`](Self::set_bandwidth) is not limited by it.
2865    pub fn set_max_bandwidth(&mut self, bandwidth: Bandwidth) {
2866        self.max_bandwidth = bandwidth;
2867    }
2868
2869    /// The value set with [`set_max_bandwidth`](Self::set_max_bandwidth)
2870    /// (libopus `OPUS_GET_MAX_BANDWIDTH`).
2871    pub fn max_bandwidth(&self) -> Bandwidth {
2872        self.max_bandwidth
2873    }
2874
2875    /// libopus `OPUS_SET_LFE`: this encoder codes the low-frequency-effects
2876    /// channel of a surround stream. Its packets are CELT-only and
2877    /// narrowband, whatever mode and bandwidth are set. A
2878    /// [`RestrictedSilk`](Application::RestrictedSilk) encoder codes them
2879    /// SILK-only and narrowband.
2880    pub fn set_lfe(&mut self, lfe: bool) {
2881        self.lfe = lfe;
2882    }
2883
2884    /// Whether [`set_lfe`](Self::set_lfe) is on.
2885    pub fn lfe(&self) -> bool {
2886        self.lfe
2887    }
2888
2889    /// libopus `OPUS_SET_PREDICTION_DISABLED`: code every frame so that a
2890    /// decoder can start with it, at the cost of quality.
2891    ///
2892    /// - SILK codes every frame as the first one after a reset
2893    ///   (enc_API.c:172-177).
2894    /// - CELT runs without its pitch pre-filter and codes the coarse band
2895    ///   energies without prediction from the frame before
2896    ///   (`CELT_SET_PREDICTION(0)`, opus_encoder.c:2288-2294).
2897    pub fn set_prediction_disabled(&mut self, disabled: bool) {
2898        self.prediction_disabled = disabled;
2899    }
2900
2901    /// Whether [`set_prediction_disabled`](Self::set_prediction_disabled)
2902    /// is on.
2903    pub fn prediction_disabled(&self) -> bool {
2904        self.prediction_disabled
2905    }
2906
2907    /// libopus `OPUS_SET_PHASE_INVERSION_DISABLED`: with `true`, CELT's
2908    /// intensity stereo never inverts the sign of the second channel. The
2909    /// default is `false`.
2910    ///
2911    /// libopus documents the trade: disabling phase inversion makes a mono
2912    /// downmix of the decoded stereo sound better, and lowers stereo
2913    /// quality a little. It changes CELT-only and Hybrid packets of stereo
2914    /// streams, at bitrates where CELT codes high bands as intensity
2915    /// stereo. [`reset_state`](Self::reset_state) keeps the value.
2916    ///
2917    /// A [`RestrictedSilk`](Application::RestrictedSilk) encoder codes no
2918    /// CELT. As in libopus, it accepts the call and ignores it, and
2919    /// [`phase_inversion_disabled`](Self::phase_inversion_disabled) stays
2920    /// `false`.
2921    pub fn set_phase_inversion_disabled(&mut self, disabled: bool) {
2922        // C opus_encoder.c:3181-3182.
2923        if self.application != Application::RestrictedSilk {
2924            self.celt_enc.set_phase_inversion_disabled(disabled);
2925        }
2926    }
2927
2928    /// The value set with
2929    /// [`set_phase_inversion_disabled`](Self::set_phase_inversion_disabled)
2930    /// (`OPUS_GET_PHASE_INVERSION_DISABLED`). Always `false` for a
2931    /// [`RestrictedSilk`](Application::RestrictedSilk) encoder, as in
2932    /// libopus.
2933    pub fn phase_inversion_disabled(&self) -> bool {
2934        // C opus_encoder.c:3192-3195.
2935        self.application != Application::RestrictedSilk && self.celt_enc.phase_inversion_disabled()
2936    }
2937
2938    /// The test control of `internals::silk_input`: with `true`, SILK reads
2939    /// the output of the integer `hp_cutoff` with `Voip` at 48 kHz too.
2940    #[cfg(feature = "__internals")]
2941    pub(crate) fn set_integer_hp_at_48k(&mut self, on: bool) {
2942        self.integer_hp_at_48k = on;
2943    }
2944
2945    /// The test control of `internals::silk_input`: with `true`, SILK's
2946    /// quantization gains come from libopus's residual energies alone.
2947    #[cfg(feature = "__internals")]
2948    pub(crate) fn set_fixed_point_res_nrg(&mut self, on: bool) {
2949        self.fixed_point_res_nrg = on;
2950    }
2951
2952    /// libopus `OPUS_SET_EXPERT_FRAME_DURATION`: the duration of the frames
2953    /// the encoder codes.
2954    ///
2955    /// - [`FrameDuration::Argument`], the default: the `frame_size` of each
2956    ///   [`encode`](Self::encode) call is the frame.
2957    /// - Any other value: each call codes a frame of that duration. Its
2958    ///   `frame_size` must be at least that long, and `input` must still
2959    ///   hold `frame_size * channels` samples. Only the first frame of
2960    ///   them is coded. A shorter `frame_size` is refused.
2961    ///
2962    /// The setting itself is always accepted, as in libopus. On a
2963    /// [`RestrictedSilk`](Application::RestrictedSilk) encoder, 2.5 and 5 ms
2964    /// make every encode call fail.
2965    ///
2966    /// libopus calls this "variable duration": the encoder may code less
2967    /// audio than the call passes. The caller learns how much from the
2968    /// packet ([`packet::nb_samples`]) and passes the rest again in the
2969    /// next call. libopus 1.6 makes no choice of its own here; the
2970    /// duration is the one that was set.
2971    ///
2972    /// From complexity 7 on, the speech and music analysis reads all
2973    /// `frame_size` samples of a call, as libopus's does. It takes the
2974    /// samples after the coded frame as the start of the next call's input
2975    /// and does not analyse them again. A caller that does not pass them
2976    /// again gives the analysis a signal with a gap, in libopus as here.
2977    ///
2978    /// The setting stays across [`reset_state`](Self::reset_state), as in
2979    /// libopus.
2980    pub fn set_expert_frame_duration(&mut self, duration: FrameDuration) {
2981        self.variable_duration = duration;
2982    }
2983
2984    /// libopus `OPUS_GET_EXPERT_FRAME_DURATION`: the value set with
2985    /// [`set_expert_frame_duration`](Self::set_expert_frame_duration).
2986    pub fn expert_frame_duration(&self) -> FrameDuration {
2987        self.variable_duration
2988    }
2989
2990    /// libopus `OPUS_SET_FORCE_CHANNELS`: code `Some(Channels::Mono)` or
2991    /// `Some(Channels::Stereo)`, or let the bitrate decide with `None`.
2992    ///
2993    /// A mono encoder codes mono whatever is set. libopus refuses
2994    /// `Some(Stereo)` on a mono encoder with `OPUS_BAD_ARG`; opus1 keeps the
2995    /// value, and it has no effect.
2996    ///
2997    /// Without a forced count, stereo input is coded as mono below about
2998    /// 17 kb/s for music and 19 kb/s for speech, with 1 kb/s of hysteresis
2999    /// (opus_encoder.c:1428-1451).
3000    ///
3001    /// As in libopus, a packet made of several frames (40 to 120 ms of
3002    /// CELT or Hybrid, 80 to 120 ms of SILK) that would lead over to mono
3003    /// sets this to `Some(Channels::Mono)` itself (opus_encoder.c:1763-1765).
3004    /// The stream then stays mono until the caller sets the count again.
3005    pub fn set_force_channels(&mut self, channels: Option<Channels>) {
3006        self.force_channels = channels.map(Channels::count);
3007    }
3008
3009    /// libopus `OPUS_GET_FORCE_CHANNELS`: the value set with
3010    /// [`set_force_channels`](Self::set_force_channels), or set by the
3011    /// encoder itself as that method describes.
3012    pub fn force_channels(&self) -> Option<Channels> {
3013        self.force_channels.map(Channels::from_valid_count)
3014    }
3015
3016    /// libopus `OPUS_SET_APPLICATION`: changes the application given to
3017    /// [`new`](Self::new), before the first frame is coded.
3018    ///
3019    /// Once a frame is coded, only the current application is accepted;
3020    /// another one is an error and changes nothing, as in libopus.
3021    /// [`reset_state`](Self::reset_state) allows a change again. An
3022    /// encoder whose application is changed before the first frame codes
3023    /// as one created with the new application.
3024    ///
3025    /// [`RestrictedSilk`](Application::RestrictedSilk) and
3026    /// [`RestrictedCelt`](Application::RestrictedCelt) can only be chosen
3027    /// when the encoder is created, as in libopus 1.6. A change to one of
3028    /// them is refused with [`BadArg`](crate::ErrorKind::BadArg), and so is
3029    /// any call on an encoder created with one of them, even with the same
3030    /// application.
3031    pub fn set_application(&mut self, application: Application) -> Result<(), Error> {
3032        // C opus_encoder.c:2789-2798.
3033        if self.application.only_at_creation() || application.only_at_creation() {
3034            return Err(Error::bad_arg("application can only be chosen when the encoder is created"));
3035        }
3036        if !self.first && application != self.application {
3037            return Err(Error::bad_arg("application cannot change after the first frame"));
3038        }
3039        self.application = application;
3040        // What `new` derives from the application. Before the first frame
3041        // the delay buffer holds only zeros, so its length can change.
3042        let restricted = application.without_delay_buffer();
3043        let fs = self.sampling_rate as usize;
3044        self.encoder_buffer = if restricted { 0 } else { fs / 100 };
3045        self.delay_compensation = if restricted { 0 } else { fs / 250 };
3046        Ok(())
3047    }
3048
3049    /// The application (`OPUS_GET_APPLICATION`).
3050    pub fn application(&self) -> Application {
3051        self.application
3052    }
3053
3054    /// libopus `OPUS_SET_VOICE_RATIO`: the probability that the input is
3055    /// speech, in percent (0 to 100), or `None` when it is not known
3056    /// (libopus -1). A value above 100 is refused with
3057    /// [`BadArg`](crate::ErrorKind::BadArg) and changes nothing.
3058    ///
3059    /// The encoder replaces the value itself: with every frame that is not
3060    /// digital silence it goes back to `None`, and when the speech and
3061    /// music analysis gives a result and the signal type is automatic, it
3062    /// becomes the analysis's estimate. While it is known and the signal
3063    /// type is automatic, it steers the choice between SILK and CELT. The
3064    /// start value is `None`.
3065    pub fn set_voice_ratio(&mut self, ratio: Option<u8>) -> Result<(), Error> {
3066        self.voice_ratio = match ratio {
3067            None => -1,
3068            Some(percent) if percent <= 100 => i32::from(percent),
3069            Some(_) => return Err(Error::bad_arg("invalid voice ratio")),
3070        };
3071        Ok(())
3072    }
3073
3074    /// libopus `OPUS_GET_VOICE_RATIO`: the value of
3075    /// [`set_voice_ratio`](Self::set_voice_ratio), or the encoder's own
3076    /// estimate from the last frame, in percent, or `None` (libopus -1).
3077    pub fn voice_ratio(&self) -> Option<u8> {
3078        u8::try_from(self.voice_ratio).ok()
3079    }
3080
3081    /// libopus `OPUS_SET_ENERGY_MASK`: how far each band of each channel
3082    /// lies above what the other channels of a surround stream mask. A
3083    /// multistream encoder computes it for every frame.
3084    ///
3085    /// `mask` holds 21 values per channel of this encoder, the first
3086    /// channel first, in units of 6 dB (log2 of an amplitude ratio). A
3087    /// negative value says the band is masked. `None` clears the mask. A
3088    /// slice of another length is refused with
3089    /// [`BadArg`](crate::ErrorKind::BadArg), and the mask stays. libopus
3090    /// keeps a pointer to the caller's array; this function copies the
3091    /// values, so call it again when they change.
3092    ///
3093    /// What the encoder does with a mask, as libopus does:
3094    ///
3095    /// - CELT-only packets: the CELT encoder spends fewer bits on masked
3096    ///   bands and, with a variable bitrate, on the whole frame.
3097    /// - SILK-only and Hybrid packets with a variable bitrate: the SILK
3098    ///   bitrate goes down with the average depth of the mask over SILK's
3099    ///   bands, by at most two thirds. A mask of all zeros raises it a
3100    ///   little.
3101    /// - Hybrid packets: the band above 8 kHz is not attenuated at low
3102    ///   bitrates.
3103    /// - With a constant bitrate, and for a low-frequency-effects encoder,
3104    ///   the mask changes no packet size.
3105    ///
3106    /// One difference from libopus, on purpose. In a Hybrid packet the CELT
3107    /// layer's bitrate is what the SILK bitrate leaves of the total. When a
3108    /// mask raises the SILK bitrate to within 500 b/s of the total, libopus
3109    /// fails to set the CELT bitrate and the CELT layer runs at its maximum:
3110    /// a 10 kb/s stream comes out at about 500 kb/s. This encoder gives the
3111    /// CELT layer the lowest bitrate it takes instead (501 b/s).
3112    pub fn set_energy_mask(&mut self, mask: Option<&[f32]>) -> Result<(), Error> {
3113        let n = 21 * self.channels;
3114        self.energy_mask = match mask {
3115            None => None,
3116            Some(m) if m.len() == n => {
3117                let mut values = [0.0; 21 * OPUS_MAX_CHANNELS];
3118                values[..n].copy_from_slice(m);
3119                Some(values)
3120            }
3121            Some(_) => return Err(Error::bad_arg("invalid energy mask length")),
3122        };
3123        Ok(())
3124    }
3125
3126    /// The mask set with [`set_energy_mask`](Self::set_energy_mask): 21
3127    /// values per channel, or `None` when there is none.
3128    pub fn energy_mask(&self) -> Option<&[f32]> {
3129        self.energy_mask.as_ref().map(|m| &m[..21 * self.channels])
3130    }
3131
3132    /// libopus `OPUS_GET_FINAL_RANGE`: the state of the range coder after
3133    /// the last frame of the last packet. A decoder that reads the packet
3134    /// correctly ends in the same state
3135    /// ([`OpusDecoder::final_range`]). The value is 0 for a packet that
3136    /// carries no range-coded data: one too small to code anything, or one
3137    /// whose frame did not fit and was replaced by an empty frame.
3138    pub fn final_range(&self) -> u32 {
3139        self.range_final
3140    }
3141
3142    /// libopus `OPUS_RESET_STATE`: forget the signal coded so far. The
3143    /// encoder then behaves like a new one with the same settings.
3144    ///
3145    /// The settings that stay are the bitrate, the complexity, CBR or VBR
3146    /// and the VBR constraint, in-band FEC, the packet loss percentage, the
3147    /// forced mode, the bandwidth and maximum bandwidth, the forced channel
3148    /// count, the prediction switch, the expert frame duration, the LFE
3149    /// flag, the signal type, the LSB depth and DTX. The energy mask is
3150    /// cleared, as in libopus. The speech and music analysis starts again,
3151    /// and so does the count of frames without activity for DTX.
3152    ///
3153    /// As in libopus, the speech probability of the last packet the
3154    /// analysis judged also stays (C `voice_ratio`): it steers the first
3155    /// packets after the reset until the analysis has a new estimate.
3156    ///
3157    /// As in libopus, three things SILK reported for the last packet also
3158    /// stay: whether the packet was to carry FEC, whether SILK allowed a
3159    /// bandwidth switch, and whether it ran at wideband. With FEC on and
3160    /// more than 5 % loss, the first packets after a reset can therefore
3161    /// have another bandwidth than those of a new encoder.
3162    ///
3163    /// With the feature `dred`, a reset also turns DRED off, as in libopus:
3164    /// `dred_duration` is 0 afterwards. The DRED models stay, also those
3165    /// loaded with `set_dnn_blob`. (These methods exist only with the
3166    /// feature, so they are not linked here.)
3167    ///
3168    /// The new state is written in place, as [`init`](Self::init) writes
3169    /// it, so a reset needs only a little stack, also without `heap`. With
3170    /// `heap` it goes into the heap memory the encoder already has: like
3171    /// libopus `OPUS_RESET_STATE`, a reset allocates nothing.
3172    pub fn reset_state(&mut self) {
3173        let kept = KeptOnReset::of(self);
3174        // The DRED fields of libopus's encoder lie after
3175        // `OPUS_ENCODER_RESET_START`, `dred_duration` included, so a reset
3176        // turns DRED off. `dred_encoder_reset` keeps the models. The DRED
3177        // state left behind holds the built-in models, which own no heap
3178        // memory.
3179        #[cfg(feature = "dred")]
3180        let models = self.dred.take_models();
3181        let (sampling_rate, channels, application) = (self.sampling_rate, self.channels, self.application);
3182        // A second encoder would need 150 KB of stack without `heap`, and
3183        // new heap memory with it. So the new encoder is written over the
3184        // old one. Without `heap` such an encoder owns no other memory, so
3185        // the old one needs no drop, and each field is written with a valid
3186        // value, so the encoder stays valid at every step. With `heap`
3187        // (`HeapMemory::Reuse`), each box keeps its memory and only its
3188        // contents are written anew, the boxes of the SILK encoder too. The
3189        // other fields own no memory.
3190        #[cfg(not(feature = "heap"))]
3191        const { assert!(!core::mem::needs_drop::<Self>()) };
3192        // SAFETY: `self` is a valid encoder, and the arguments are those of
3193        // this encoder, which were valid.
3194        unsafe { Self::write_new(self, sampling_rate, channels, application, HeapMemory::Reuse) };
3195        kept.restore(self);
3196        #[cfg(feature = "dred")]
3197        self.dred.set_models(models);
3198    }
3199
3200    /// The sampling rate of the input (`OPUS_GET_SAMPLE_RATE`).
3201    pub fn sampling_rate(&self) -> SampleRate {
3202        SampleRate::from_valid_hz(self.sampling_rate)
3203    }
3204
3205    /// The number of input channels.
3206    pub fn channels(&self) -> Channels {
3207        Channels::from_valid_count(self.channels)
3208    }
3209
3210    /// libopus `OPUS_GET_LOOKAHEAD`: the delay the encoder adds, in samples
3211    /// per channel at the input sampling rate. A decoder's output lags the
3212    /// encoder's input by this much. An Ogg Opus file stores it, scaled to
3213    /// 48 kHz, as the pre-skip.
3214    ///
3215    /// It is 2.5 ms for [`RestrictedLowDelay`](Application::RestrictedLowDelay)
3216    /// and [`RestrictedCelt`](Application::RestrictedCelt), and 6.5 ms for
3217    /// the other applications.
3218    pub fn lookahead(&self) -> usize {
3219        // C opus_encoder.c:3082-3092: 2.5 ms of CELT overlap, and the 4 ms
3220        // that align CELT with SILK. `RestrictedSilk` codes no CELT and
3221        // keeps no `delay_compensation`, but libopus counts the 4 ms for it
3222        // as for `Voip` and `Audio`.
3223        let fs = self.sampling_rate as usize;
3224        match self.application {
3225            Application::RestrictedLowDelay | Application::RestrictedCelt => fs / 400,
3226            _ => fs / 400 + fs / 250,
3227        }
3228    }
3229
3230    /// Encode a frame of interleaved f32 PCM (scale ยฑ1.0; C `opus_encode_float`
3231    /// convention where 1.0 maps to PCM16 32768). `input` must hold
3232    /// `frame_size * channels` samples.
3233    ///
3234    /// `frame_size` is in samples per channel: 2.5, 5, 10, 20, 40, 60, 80,
3235    /// 100 or 120 ms. A [`RestrictedSilk`](Application::RestrictedSilk)
3236    /// encoder refuses 2.5 and 5 ms. With an expert frame duration set
3237    /// ([`set_expert_frame_duration`](Self::set_expert_frame_duration)),
3238    /// only the first frame of that duration is coded, and `frame_size`
3239    /// must be at least that long. The speech and music analysis still
3240    /// reads all `frame_size` samples, as in libopus: it takes the samples
3241    /// after the coded frame as the start of the next call's input.
3242    ///
3243    /// The packet never exceeds `output`. As in libopus, the length of
3244    /// `output` also counts as a limit on the bitrate: when it holds less
3245    /// than the bitrate gives the frame, the encoder chooses mode and
3246    /// bandwidth for the lower rate. Pass a buffer of 1276 bytes per 20 ms
3247    /// or more when the bitrate alone should decide.
3248    pub fn encode(
3249        &mut self,
3250        input: &[f32],
3251        frame_size: usize,
3252        output: &mut [u8],
3253    ) -> Result<usize, Error> {
3254        let analysis_frame_size = frame_size;
3255        let frame_size = self.select_frame_size(input.len(), frame_size)?;
3256        // libopus `opus_encode_float`: the analysis reads the caller's
3257        // whole buffer, all channels (`c1` 0, `c2` -2), at 24 bits.
3258        let analysis_pcm = AnalysisPcm {
3259            pcm: PcmRef::F32(input),
3260            channels: self.channels,
3261            c1: 0,
3262            c2: SecondChannel::AllOthers,
3263            frame_size: analysis_frame_size,
3264        };
3265        self.encode_impl(input, frame_size, output, analysis_pcm, 24, true)
3266    }
3267
3268    /// Encode a frame of interleaved 16-bit PCM (libopus `opus_encode`).
3269    ///
3270    /// Each sample is converted to `sample as f32 / 32768.0`, and the input
3271    /// counts as 16 bits deep, as in libopus: the LSB depth is at most 16
3272    /// ([`set_lsb_depth`](Self::set_lsb_depth)). The packets are therefore
3273    /// those of [`encode`](Self::encode) of the converted samples with an
3274    /// LSB depth of 16, not 24. The depth sets the noise floor of the
3275    /// speech and music analysis and of CELT's bit allocation, and the
3276    /// level below which CELT codes a frame as silence.
3277    pub fn encode_i16(
3278        &mut self,
3279        input: &[i16],
3280        frame_size: usize,
3281        output: &mut [u8],
3282    ) -> Result<usize, Error> {
3283        let analysis_frame_size = frame_size;
3284        let frame_size = self.select_frame_size(input.len(), frame_size)?;
3285        // libopus `INT16TORES`, over the frame that is coded. The
3286        // conversion is exact, and the 16-bit high-pass filter of the
3287        // `Voip` application rounds the float samples back to the same
3288        // 16-bit values.
3289        let n = frame_size * self.channels;
3290        let mut pcm: FixedVec<f32, OPUS_PCM_PACKET> = FixedVec::new();
3291        pcm.extend_map(&input[..n], int16_to_res);
3292        // The analysis reads the caller's 16-bit samples (`downmix_int`).
3293        let analysis_pcm = AnalysisPcm {
3294            pcm: PcmRef::I16(input),
3295            channels: self.channels,
3296            c1: 0,
3297            c2: SecondChannel::AllOthers,
3298            frame_size: analysis_frame_size,
3299        };
3300        self.encode_impl(&pcm, frame_size, output, analysis_pcm, 16, true)
3301    }
3302
3303    /// Encode one frame of interleaved 24-bit samples held in 32-bit
3304    /// integers: libopus `opus_encode24` in the float build.
3305    ///
3306    /// Full scale is 2^23 (ยฑ8388608). Each sample is divided by 2^23 to a
3307    /// float (libopus `INT24TORES`), and the frame is then coded as
3308    /// [`encode`](Self::encode) codes float input, with 24 bits of
3309    /// precision. Values beyond 24 bits are accepted and are not limited,
3310    /// as in libopus. The speech and music analysis reads the integers
3311    /// (libopus `downmix_int24`). `frame_size` and the errors are those of
3312    /// [`encode`](Self::encode).
3313    pub fn encode24(
3314        &mut self,
3315        input: &[i32],
3316        frame_size: usize,
3317        output: &mut [u8],
3318    ) -> Result<usize, Error> {
3319        let analysis_frame_size = frame_size;
3320        let frame_size = self.select_frame_size(input.len(), frame_size)?;
3321        let n = frame_size * self.channels;
3322        let mut pcm: FixedVec<f32, OPUS_PCM_PACKET> = FixedVec::new();
3323        pcm.extend_map(&input[..n], int24_to_res);
3324        let analysis_pcm = AnalysisPcm {
3325            pcm: PcmRef::I32(input),
3326            channels: self.channels,
3327            c1: 0,
3328            c2: SecondChannel::AllOthers,
3329            frame_size: analysis_frame_size,
3330        };
3331        self.encode_impl(&pcm, frame_size, output, analysis_pcm, 24, true)
3332    }
3333
3334    /// The frame an encode call codes: libopus `frame_size_select`, which
3335    /// `opus_encode` and `opus_encode_float` call first. `frame_size` is
3336    /// the caller's (C `analysis_frame_size`), and `input_len` the number
3337    /// of samples the caller passed. Returns the frame size in samples per
3338    /// channel.
3339    fn select_frame_size(&self, input_len: usize, frame_size: usize) -> Result<usize, Error> {
3340        let selected =
3341            frame_size_select(self.application, frame_size, self.variable_duration, self.sampling_rate)
3342                .ok_or(Error::INVALID_FRAME_SIZE)?;
3343        // The caller passes `frame_size` samples per channel, as libopus
3344        // reads them. Short input is rejected here, so that it cannot
3345        // panic inside the high-pass filter or the conversion loops.
3346        if input_len < frame_size.saturating_mul(self.channels) {
3347            return Err(Error::INPUT_TOO_SHORT);
3348        }
3349        Ok(selected)
3350    }
3351
3352    /// One packet: libopus `opus_encode_native` (opus_encoder.c:1182-1853).
3353    /// `frame_size` is the frame [`select_frame_size`](Self::select_frame_size)
3354    /// chose. The multistream encoder calls this directly, as libopus
3355    /// calls `opus_encode_native`, so the expert frame duration of a
3356    /// stream encoder plays no part there.
3357    ///
3358    /// `analysis_pcm` is what libopus hands to `run_analysis`: the caller's
3359    /// whole buffer, which can be longer than the frame, and the channels
3360    /// of it this encoder codes. `lsb_depth` is the precision of the input
3361    /// type, 24 for float and 16 for 16-bit samples.
3362    ///
3363    /// What this function, [`decide_mode_and_bandwidth`](Self::decide_mode_and_bandwidth)
3364    /// and [`encode_frame`](Self::encode_frame) still do differently from
3365    /// libopus:
3366    ///
3367    /// 1. SILK's input with the `Voip` application at 8 to 24 kHz. The
3368    ///    float build of libopus feeds SILK the float `pcm_buf`, filtered
3369    ///    by `hp_cutoff` and rounded to 16 bits. Here SILK gets the output
3370    ///    of the integer `hp_cutoff` of the fixed-point build. That filter
3371    ///    has its own state and runs on every frame, as in that build. At
3372    ///    48 kHz, and with the other applications, SILK follows the float
3373    ///    build.
3374    /// 2. Packets made of several frames (CELT and Hybrid at 40 to 120 ms,
3375    ///    SILK-only at 80 to 120 ms) with a variable bitrate: the limit of
3376    ///    each frame to its share of the bitrate (C 1785) is left out on
3377    ///    purpose, see `encode_multiframe`.
3378    /// 3. The Hybrid CELT bitrate has a floor of 501 b/s, on purpose.
3379    /// 4. On purpose: a frame that announces the switch to CELT-only
3380    ///    without room for the redundant frame still resets the CELT
3381    ///    encoder. The decoder starts the CELT-only packets from the reset
3382    ///    state then; libopus's encoder goes on from its last CELT frame.
3383    /// 5. The energy mask is copied. After a CELT reset libopus has lost
3384    ///    its pointer to the mask until the caller sets it again; here the
3385    ///    copy is applied again on the next frame.
3386    pub(crate) fn encode_impl(
3387        &mut self,
3388        input: &[f32],
3389        frame_size: usize,
3390        output: &mut [u8],
3391        analysis_pcm: AnalysisPcm<'_>,
3392        lsb_depth: i32,
3393        float_api: bool,
3394    ) -> Result<usize, Error> {
3395        self.float_api = float_api;
3396        // C 1223: no final range until a frame is coded.
3397        self.range_final = 0;
3398        let out_data_bytes = output.len();
3399        // C 1221: "Just avoid insane packet sizes here, but the real bounds
3400        // are applied later on."
3401        let mut max_data_bytes = out_data_bytes.min(6 * OPUS_MAX_PACKET_BYTES);
3402        if max_data_bytes == 0 {
3403            return Err(Error::bad_arg("output buffer is empty"));
3404        }
3405
3406        let frame_rate = frame_rate_from_params(self.sampling_rate, frame_size)
3407            .ok_or(Error::INVALID_FRAME_SIZE)?;
3408        // C 1231-1236: "Cannot encode 100 ms in 1 byte". A 100 ms packet
3409        // without audio needs a frame count byte: it is five 20 ms frames.
3410        if max_data_bytes == 1 && frame_size * 10 == self.sampling_rate as usize {
3411            return Err(Error::BUFFER_TOO_SMALL);
3412        }
3413
3414        // The encoder consumes exactly frame_size * channels samples per call.
3415        // Short input is rejected here, so that it cannot panic inside the
3416        // high-pass filter or the float-to-integer conversion loops.
3417        if input.len() < frame_size * self.channels {
3418            return Err(Error::INPUT_TOO_SHORT);
3419        }
3420
3421        // C 1242-1320: the precision of the input, digital silence, the
3422        // speech and music analysis, and what the packet's decisions take
3423        // from it.
3424        let lsb_depth = lsb_depth.min(self.lsb_depth);
3425        let pcm = &input[..frame_size * self.channels];
3426        let is_silence = is_digital_silence(pcm, lsb_depth);
3427        let (analysis_info, analysis_cursor) = self.run_analysis(analysis_pcm, frame_size, lsb_depth);
3428        // "Reset voice_ratio if this frame is not silent or if analysis is
3429        // disabled. Otherwise, preserve voice_ratio from the last
3430        // non-silent frame".
3431        if !is_silence {
3432            self.voice_ratio = -1;
3433        }
3434        let mut detected_bandwidth = None;
3435        if analysis_info.valid {
3436            if self.signal == Signal::Auto {
3437                // The music probability that fits the mode of the last
3438                // frame: the plain one at the start, the threshold for a
3439                // switch away from CELT after CELT-only frames, and the one
3440                // for a switch to CELT otherwise.
3441                let prob = match self.prev_enc_mode {
3442                    None => analysis_info.music_prob,
3443                    Some(OpusMode::CeltOnly) => analysis_info.music_prob_max,
3444                    Some(_) => analysis_info.music_prob_min,
3445                };
3446                // C `(int)floor(.5+100*(1-prob))`: the product in float,
3447                // the rest in double precision.
3448                self.voice_ratio = (0.5 + (100.0 * (1.0 - prob)) as f64).floor() as i32;
3449            }
3450            detected_bandwidth = Some(match analysis_info.bandwidth {
3451                ..=12 => Bandwidth::Narrowband,
3452                13..=14 => Bandwidth::Mediumband,
3453                15..=16 => Bandwidth::Wideband,
3454                17..=18 => Bandwidth::Superwideband,
3455                _ => Bandwidth::Fullband,
3456            });
3457        }
3458        // C 1307-1320: "Track the peak signal energy", over the frames
3459        // that are not silent and that the analysis does not find inactive.
3460        // `MAX32` is a ternary.
3461        if (!analysis_info.valid || analysis_info.activity_probability > DTX_ACTIVITY_THRESHOLD)
3462            && !is_silence
3463        {
3464            let decayed = 0.999 * self.peak_signal_energy;
3465            let energy = frame_energy(pcm);
3466            self.peak_signal_energy = if decayed > energy { decayed } else { energy };
3467        }
3468
3469        // C 1321-1324: the stereo width of the input, once per packet,
3470        // whatever is done with the packet. Not when the caller asks for
3471        // mono packets.
3472        self.stereo_width = if self.channels == 2 && self.force_channels != Some(1) {
3473            compute_stereo_width(input, frame_size, self.sampling_rate, &mut self.width_mem)
3474        } else {
3475            0.0
3476        };
3477
3478        // C 1325-1334. `user_bitrate_to_bitrate`: the packet is coded at the
3479        // bitrate asked for, or at the rate the output buffer stands for
3480        // when that is lower. A constant bitrate codes whole bytes, and the
3481        // bitrate becomes the rate of those bytes.
3482        let fs = self.sampling_rate;
3483        let mut bitrate = self.user_bitrate_to_bitrate(frame_size, max_data_bytes);
3484        let mut cbr_bytes = 0usize;
3485        if self.use_cbr {
3486            let nominal = (bitrate_to_bits(bitrate, fs, frame_size) + 4) / 8;
3487            cbr_bytes = (nominal.max(0) as usize).min(max_data_bytes);
3488            bitrate = bits_to_bitrate(8 * cbr_bytes as i32, fs, frame_size);
3489            // "Make sure we provide at least one byte to avoid failing."
3490            max_data_bytes = cbr_bytes.max(1);
3491        }
3492        // C 1335-1339: "Allocate some of the bits to DRED if needed." The
3493        // rest of the packet goes by the bitrate that DRED leaves. With DRED
3494        // off the share is 0.
3495        #[cfg(feature = "dred")]
3496        {
3497            let fec = self.fec_config != InbandFec::Off;
3498            bitrate -= self.dred.compute_bitrate(bitrate, frame_size, fec, self.packet_loss_perc);
3499        }
3500        self.packet_bitrate_bps = bitrate;
3501
3502        // C 1340-1406: "If the space is too low to do something useful,
3503        // emit 'PLC' frames". This comes before every decision, and before
3504        // a frame of 40 ms or more is split into parts.
3505        if max_data_bytes < 3
3506            || bitrate < 3 * frame_rate * 8
3507            || (frame_rate < 50 && (max_data_bytes as i32 * frame_rate < 300 || bitrate < 2400))
3508        {
3509            return self.write_placeholder(frame_rate, max_data_bytes, output);
3510        }
3511
3512        // C 1458-1461: "Allow SILK DTX if DTX is enabled but the
3513        // generalized DTX cannot be used, e.g. because of the complexity
3514        // setting or sample rate." The DTX of the Opus layer needs the
3515        // activity of the analysis, or knows the packet is digital silence.
3516        self.silk_use_dtx = self.use_dtx && !(analysis_info.valid || is_silence);
3517
3518        let decisions = self.decide_mode_and_bandwidth(
3519            frame_size,
3520            frame_rate,
3521            max_data_bytes,
3522            detected_bandwidth,
3523        );
3524        let mode = decisions.mode;
3525        // C 1677: the CELT encoder codes with the precision of the input.
3526        // An encoder with only SILK has no CELT encoder in libopus.
3527        if self.application != Application::RestrictedSilk {
3528            self.celt_enc.set_lsb_depth(lsb_depth);
3529        }
3530
3531        // C 1697-1838: "Can't support higher than >60 ms frames, and
3532        // >20 ms when in Hybrid or CELT-only modes". Longer packets are
3533        // made of several frames.
3534        let fs_u = fs as usize;
3535        if (mode != OpusMode::SilkOnly && frame_size > fs_u / 50) || frame_size > 3 * fs_u / 50 {
3536            return self.encode_multiframe(
3537                input,
3538                frame_size,
3539                decisions,
3540                cbr_bytes,
3541                output,
3542                analysis_cursor,
3543                lsb_depth,
3544            );
3545        }
3546        let frame_analysis = FrameAnalysis {
3547            info: analysis_info,
3548            is_silence,
3549        };
3550        self.encode_frame(input, frame_size, &mut output[..max_data_bytes], decisions, frame_analysis, true)
3551    }
3552
3553    /// C 1247-1263: the speech and music analysis of the packet, when the
3554    /// complexity and the sampling rate let it run. Returns its result and
3555    /// the read position of the analysis before the call, which the frames
3556    /// of a packet of several frames start from (`None` when it did not
3557    /// run). When it does not run but ran before, it starts from scratch,
3558    /// so that a later run does not continue from old input.
3559    fn run_analysis(
3560        &mut self,
3561        pcm: AnalysisPcm<'_>,
3562        frame_size: usize,
3563        lsb_depth: i32,
3564    ) -> (AnalysisInfo, Option<(usize, i32)>) {
3565        #[cfg(feature = "analysis")]
3566        {
3567            if self.analysis_runs() {
3568                let cursor = self.analysis.read_cursor();
3569                let info = self.analysis.run(pcm, frame_size, lsb_depth);
3570                return (info, Some(cursor));
3571            }
3572            if self.analysis.initialized() {
3573                self.analysis.reset();
3574            }
3575        }
3576        #[cfg(not(feature = "analysis"))]
3577        let _ = (pcm, frame_size, lsb_depth);
3578        (AnalysisInfo::default(), None)
3579    }
3580
3581    /// C `tonality_get_info` for a frame of `len` samples of a packet of
3582    /// several frames, from the read position `cursor` on when it is the
3583    /// first frame (C 1727-1734, 1797-1800).
3584    fn frame_analysis_info(&mut self, cursor: Option<(usize, i32)>, len: usize) -> AnalysisInfo {
3585        #[cfg(feature = "analysis")]
3586        {
3587            if let Some(cursor) = cursor {
3588                self.analysis.set_read_cursor(cursor);
3589            }
3590            self.analysis.get_info(len)
3591        }
3592        #[cfg(not(feature = "analysis"))]
3593        {
3594            let _ = (cursor, len);
3595            AnalysisInfo::default()
3596        }
3597    }
3598
3599    /// One frame of a packet: libopus `opus_encode_frame_native`
3600    /// (opus_encoder.c:1855-2655).
3601    ///
3602    /// `output.len()` is the largest size the frame's packet may have (C
3603    /// `orig_max_data_bytes`). With a constant bitrate the packet is padded
3604    /// to exactly that size. `first_frame` is true for the first frame of a
3605    /// packet that is coded (not left out by DTX): its packet carries the
3606    /// DRED data.
3607    fn encode_frame(
3608        &mut self,
3609        input: &[f32],
3610        frame_size: usize,
3611        output: &mut [u8],
3612        d: FrameDecisions,
3613        analysis: FrameAnalysis,
3614        first_frame: bool,
3615    ) -> Result<usize, Error> {
3616        let orig_max_data_bytes = output.len();
3617        // C `max_data_bytes`: one frame takes 1275 bytes at most.
3618        let n_bytes = orig_max_data_bytes.min(OPUS_MAX_PACKET_BYTES);
3619        self.range_final = 0;
3620        // The range coder needs room. libopus never gets here with less:
3621        // `opus_encode_native` writes a packet without audio instead.
3622        if n_bytes < 3 {
3623            return Err(Error::BUFFER_TOO_SMALL);
3624        }
3625        let fs = self.sampling_rate;
3626        // C `st->channels` (the input's, SILK's `nChannelsAPI`) and
3627        // `st->stream_channels` (the packet's, SILK's `nChannelsInternal`).
3628        let ch = self.channels;
3629        let sch = self.stream_channels;
3630        let frame_rate = fs / frame_size as i32;
3631        let mode = d.mode;
3632        let frame_bandwidth = d.bandwidth;
3633        let lbrr_coded = d.lbrr_coded;
3634        // C 1888, 1909-1930: the activity of the frame, which SILK is told
3635        // about and the DTX of the Opus layer reads.
3636        //
3637        // - Digital silence (`is_digital_silence`, C 1246 and 1802): none
3638        //   (`VAD_NO_ACTIVITY`, 0).
3639        // - With a valid analysis: active when its activity probability is
3640        //   at least 0.1, or when the frame's energy is within 25 dB of the
3641        //   peak energy ("Mark as active if this noise frame is
3642        //   sufficiently loud").
3643        // - A CELT-only frame without the analysis: active when its energy
3644        //   is within 25 dB of the peak energy, with the frame's energy
3645        //   halved ("Boosting peak energy a bit because we didn't just
3646        //   average the active frames"). Only the DTX of the Opus layer and
3647        //   the deep redundancy (DRED) read this value, so it is computed
3648        //   only when one of them is in use.
3649        // - Otherwise `VAD_NO_DECISION` (-1): SILK decides by itself, and
3650        //   its decision becomes the frame's activity below.
3651        //
3652        // SILK acts only on 0: it then lowers its own speech activity below
3653        // the threshold of its voice activity flag.
3654        self.last_analysis = analysis.info;
3655        let mut activity = if analysis.is_silence {
3656            VAD_NO_ACTIVITY
3657        } else if analysis.info.valid {
3658            let active = analysis.info.activity_probability >= DTX_ACTIVITY_THRESHOLD
3659                || self.peak_signal_energy
3660                    < PSEUDO_SNR_THRESHOLD * frame_energy(&input[..frame_size * ch]);
3661            active as i32
3662        } else if d.mode == OpusMode::CeltOnly && ((self.use_dtx && !self.silk_use_dtx) || self.dred_on()) {
3663            let noise_energy = frame_energy(&input[..frame_size * ch]);
3664            (self.peak_signal_energy < PSEUDO_SNR_THRESHOLD * (0.5 * noise_energy)) as i32
3665        } else {
3666            VAD_NO_DECISION
3667        };
3668        let f2_5 = fs as usize / 400;
3669        let f5 = 2 * f2_5;
3670
3671        match (mode, frame_rate) {
3672            (OpusMode::CeltOnly, 400 | 200 | 100 | 50) => {}
3673            (OpusMode::CeltOnly, _) => {
3674                return Err(Error::internal("unsupported frame size for CELT-only mode"));
3675            }
3676            (OpusMode::Hybrid, 100 | 50) => {}
3677            (OpusMode::Hybrid, _) => {
3678                return Err(Error::internal("unsupported frame size for Hybrid mode"));
3679            }
3680            // 2.5/5 ms are CELT-only durations: SILK frames are 10 ms or
3681            // longer (libopus), and sub-10 ms frames break the SILK
3682            // analysis geometry (e.g. the VAD band split at 12 kHz).
3683            (OpusMode::SilkOnly, 100 | 50 | 25 | 16) => {}
3684            (OpusMode::SilkOnly, _) => {
3685                return Err(Error::internal("unsupported frame size for SILK-only mode"));
3686            }
3687        }
3688
3689        // C 1933-1954: what goes with a change of mode or of SILK's rate.
3690        let (mut redundancy, mut celt_to_silk) = (d.redundancy, d.celt_to_silk);
3691        // C `prefill`: 1 after CELT-only packets, 2 for the first frame at
3692        // a new SILK rate.
3693        let mut prefill = d.prefill as u8;
3694        if self.silk_bw_switch {
3695            redundancy = true;
3696            celt_to_silk = true;
3697            self.silk_bw_switch = false;
3698            // "Do a prefill without resetting the sampling rate control."
3699            // After CELT-only packets SILK has no rate to keep.
3700            if prefill == 0 {
3701                prefill = 2;
3702            }
3703        }
3704        // "If we decided to go with CELT, make sure redundancy is off, no
3705        // matter what we decided earlier."
3706        if mode == OpusMode::CeltOnly {
3707            redundancy = false;
3708        }
3709        let mut redundancy_bytes = 0usize;
3710        if redundancy {
3711            redundancy_bytes = compute_redundancy_bytes(
3712                n_bytes,
3713                self.packet_bitrate_bps,
3714                frame_rate,
3715                self.stream_channels,
3716            );
3717            if redundancy_bytes == 0 {
3718                redundancy = false;
3719            }
3720        }
3721        // C 1953-1957: an encoder with only SILK codes no redundant CELT
3722        // frame.
3723        let silk_only_app = self.application == Application::RestrictedSilk;
3724        if silk_only_app {
3725            redundancy = false;
3726            redundancy_bytes = 0;
3727        }
3728
3729        self.rc.reset_for_encode((n_bytes - 1) as u32);
3730
3731        // Hybrid: SILK's base rate, and the gain on CELT's input (C `HB_gain`).
3732        let mut hybrid_silk_rate = 0i32;
3733        let mut hb_gain = 1.0f32;
3734
3735        // C opus_encode_frame_native: high-pass cutoff state is updated for ALL
3736        // modes (celt_encoder.c:1969-1977); the filtered signal is what feeds
3737        // both SILK (hybrid) and CELT. Compute it here so CELT-only frames also
3738        // keep `variable_hp_smth2_q15` in sync with libopus.
3739        let hp_freq_smth1 = if mode == OpusMode::CeltOnly {
3740            silk_lin2log(60) << 8
3741        } else {
3742            self.silk.mid().s_cmn.variable_hp_smth1_q15
3743        };
3744
3745        // SILK_FIX_CONST(VARIABLE_HP_SMTH_COEF2, 16) with 0.015: 983 (opus_encoder.c).
3746        const VARIABLE_HP_SMTH_COEF2_Q16: i32 = 983;
3747        self.variable_hp_smth2_q15 = silk_smlawb(
3748            self.variable_hp_smth2_q15,
3749            hp_freq_smth1 - self.variable_hp_smth2_q15,
3750            VARIABLE_HP_SMTH_COEF2_Q16,
3751        );
3752
3753        let cutoff_hz = silk_log2lin(silk_rshift(self.variable_hp_smth2_q15, 8));
3754
3755        let delay = self.delay_compensation;
3756        let ebuf = self.encoder_buffer;
3757
3758        // C 1966-2028, `pcm_buf`: the look-ahead taken from the delay
3759        // buffer, then the filtered frame. libopus builds it in every mode:
3760        // the CELT layer, the redundant CELT frames of a SILK-only packet
3761        // and the delay buffer read it. A `RestrictedLowDelay` encoder has
3762        // no look-ahead and no delay buffer (`delay` and `ebuf` are 0); its
3763        // frame is filtered all the same.
3764        let prefix = delay * ch;
3765        // The frame was not a sane signal and is coded as silence.
3766        let mut frame_cleared = false;
3767        {
3768            self.buf_celt_pcm.resize((delay + frame_size) * ch, 0.0);
3769            // 1. delay prefix from the ring (C: OPUS_COPY at 1967)
3770            let src_start = (ebuf - delay) * ch;
3771            self.buf_celt_pcm[..prefix]
3772                .copy_from_slice(&self.delay_buffer[src_start..src_start + prefix]);
3773            // 2. filter current frame into pcm_buf[delay..] (C: 2002-2010)
3774            let out = &mut self.buf_celt_pcm[prefix..];
3775            if self.application == Application::Voip {
3776                hp_cutoff_float(
3777                    input,
3778                    cutoff_hz,
3779                    out,
3780                    &mut self.hp_mem_float,
3781                    frame_size,
3782                    ch,
3783                    fs,
3784                );
3785            } else {
3786                dc_reject_float(input, 3, out, &mut self.hp_mem_float, frame_size, ch, fs);
3787            }
3788            // 3. float NaN guard (C: 2016-2028), for the float API only.
3789            if self.float_api && !input_is_sane(&self.buf_celt_pcm[prefix..]) {
3790                self.buf_celt_pcm[prefix..].fill(0.0);
3791                self.hp_mem_float = [0.0; 4];
3792                frame_cleared = true;
3793            }
3794        }
3795
3796        // C 2027-2040: "Compute the DRED features. Needs to be before SILK
3797        // because of DTX." DRED reads the filtered frame, and records the
3798        // frame's activity.
3799        #[cfg(feature = "dred")]
3800        self.dred.analyze_frame(&self.buf_celt_pcm[prefix..], frame_size, delay, activity);
3801
3802        // SILK's 16-bit input with `Voip` at 8 to 24 kHz, and at 48 kHz with
3803        // the test control `integer_hp_at_48k`: the integer `hp_cutoff` of
3804        // libopus's fixed-point build. As in that build (C 1980-1983), the
3805        // filter runs on every frame, CELT-only frames included. Its state
3806        // then follows the input when SILK starts again after CELT-only
3807        // frames. Run on SILK's frames only, the filter started such a frame
3808        // from the state of the last SILK frame, and SILK coded the step as
3809        // energy below 200 Hz.
3810        let integer_hp = self.application == Application::Voip
3811            && (self.sampling_rate != 48000 || self.integer_hp_at_48k);
3812        if integer_hp {
3813            let required_size = frame_size * ch;
3814            self.buf_filtered.resize(required_size, 0);
3815            if frame_cleared {
3816                // C 2023-2027: the frame is cleared for SILK as well, and
3817                // the filter starts again.
3818                state_mut(&mut self.buf_filtered)[..required_size].fill(0);
3819                self.hp_mem.fill(0);
3820            } else {
3821                hp_cutoff(
3822                    input,
3823                    cutoff_hz,
3824                    state_mut(&mut self.buf_filtered),
3825                    &mut self.hp_mem,
3826                    frame_size,
3827                    ch,
3828                    fs,
3829                );
3830            }
3831        }
3832
3833        // C `internalSampleRate` of the SILK encoder, 0 for CELT-only frames.
3834        let mut silk_fs_khz = 0;
3835        if mode == OpusMode::SilkOnly || mode == OpusMode::Hybrid {
3836            let frame_ms = (frame_size as i32 * 1000) / fs;
3837
3838            // C opus_encoder.c `bits_target` / `total_bitRate` (1.6): SILK
3839            // codes at the packet's bitrate, capped by the packet budget
3840            // without the redundant frame, less the TOC byte. Under VBR the
3841            // budget is the caller's output buffer, which must cap the
3842            // rate, not set it.
3843            let rate_bits = bitrate_to_bits(self.packet_bitrate_bps, fs, frame_size);
3844            let bits_target = (8 * (n_bytes - redundancy_bytes) as i32).min(rate_bits) - 8;
3845            let total_bitrate = bits_to_bitrate(bits_target, fs, frame_size);
3846
3847            let silk_bitrate = if mode == OpusMode::Hybrid {
3848                // C opus_encoder.c:2049: SILK's base rate out of the rate
3849                // the packet codes at.
3850                let rate = compute_silk_rate_for_hybrid(
3851                    total_bitrate,
3852                    frame_bandwidth,
3853                    frame_ms == 20,
3854                    !self.use_cbr,
3855                    lbrr_coded != 0,
3856                    self.stream_channels,
3857                );
3858                // C opus_encoder.c:2057-2062: the fewer bits the high band
3859                // gets, the more it is attenuated before CELT codes it. Not
3860                // in a surround stream (`if (!st->energy_masking)`).
3861                //
3862                // `HB_gain = Q15ONE - SHR32(celt_exp2(-celt_rate/1024), 1)`:
3863                // the shift turns the Q16 result of the fixed-point
3864                // `celt_exp2` into Q15. It is not a halving, and in the float
3865                // build it does nothing. The gain is 1 - 2^(-celt_rate/1024).
3866                if self.energy_mask.is_none() {
3867                    let celt_rate = total_bitrate - rate;
3868                    // `celt_exp2` of the float build with `FLOAT_APPROX`,
3869                    // a polynomial (`mathops::celt_exp2`), as in the CELT
3870                    // encoder. The exact `exp` gave a gain a few float
3871                    // steps away, which changed the redundant CELT frame
3872                    // of some switches from Hybrid to CELT-only.
3873                    let x = -celt_rate as f32 * (1.0 / 1024.0);
3874                    hb_gain = 1.0 - mathops::celt_exp2(x);
3875                }
3876                rate
3877            } else {
3878                // C: SILK gets all bits, at the requested rate.
3879                total_bitrate
3880            };
3881            // C opus_encoder.c:2068-2108, "Surround masking for SILK": with a
3882            // variable bitrate the SILK rate follows how deeply the other
3883            // channels mask this one, over the bands SILK codes.
3884            let silk_bitrate = if let Some(energy_mask) = &self.energy_mask
3885                && !self.use_cbr
3886                && !self.lfe
3887            {
3888                let (end, srate) = match frame_bandwidth {
3889                    Bandwidth::Narrowband => (13usize, 8000.0f32),
3890                    Bandwidth::Mediumband => (15, 12000.0),
3891                    _ => (17, 16000.0),
3892                };
3893                let mut mask_sum = 0.0f32;
3894                for c in 0..ch {
3895                    for i in 0..end {
3896                        // C `MAX16(MIN16(mask, .5f), -2.0f)`. Not `clamp`: a
3897                        // value that is not a number becomes 0.5 here, as in
3898                        // C, and `clamp` would pass it on.
3899                        #[allow(clippy::manual_clamp)]
3900                        let mut mask = energy_mask[21 * c + i].min(0.5).max(-2.0);
3901                        if mask > 0.0 {
3902                            mask *= 0.5;
3903                        }
3904                        mask_sum += mask;
3905                    }
3906                }
3907                // "Conservative rate reduction, we cut the masking in half".
3908                let mut masking_depth = mask_sum / end as f32 * ch as f32;
3909                masking_depth += 0.2;
3910                let rate_offset = ((srate * masking_depth) as i32).max(-2 * silk_bitrate / 3);
3911                // "Split the rate change between the SILK and CELT part for
3912                // hybrid."
3913                if matches!(frame_bandwidth, Bandwidth::Superwideband | Bandwidth::Fullband) {
3914                    silk_bitrate + 3 * rate_offset / 5
3915                } else {
3916                    silk_bitrate + rate_offset
3917                }
3918            } else {
3919                silk_bitrate
3920            };
3921            if mode == OpusMode::Hybrid {
3922                hybrid_silk_rate = silk_bitrate;
3923            }
3924
3925            // C 2154-2189, `silk_mode.maxBits`: "Max bits for SILK, counting
3926            // ToC, redundancy bytes, and optionally redundancy."
3927            let mut silk_max_bits = ((n_bytes - 1) * 8) as i32;
3928            if redundancy && redundancy_bytes >= 2 {
3929                // "Counting 1 bit for redundancy position and 20 bits for
3930                // flag+size (only for hybrid)."
3931                silk_max_bits -= redundancy_bytes as i32 * 8 + 1;
3932                if mode == OpusMode::Hybrid {
3933                    silk_max_bits -= 20;
3934                }
3935            }
3936            // "When we're in CBR mode, but we have non-SILK data to encode,
3937            // switch SILK to VBR with cap to save on complexity": a Hybrid
3938            // frame, and a frame with DRED data.
3939            let silk_vbr_with_cap = mode == OpusMode::Hybrid || self.dred_bitrate_bps() > 0;
3940            if self.use_cbr {
3941                if silk_vbr_with_cap {
3942                    // "Allow SILK to steal up to 25% of the remaining bits".
3943                    let silk_bits =
3944                        (silk_bitrate as i64 * frame_size as i64 / fs as i64) as i32;
3945                    let other_bits = 0i32.max(silk_max_bits - silk_bits);
3946                    silk_max_bits = 0i32.max(silk_max_bits - other_bits * 3 / 4);
3947                }
3948            } else if mode == OpusMode::Hybrid {
3949                // C opus_encoder.c:2176-2181: the SILK rate that goes with
3950                // the largest packet allowed.
3951                let max_bit_rate = compute_silk_rate_for_hybrid(
3952                    silk_max_bits * fs / frame_size as i32,
3953                    frame_bandwidth,
3954                    frame_ms == 20,
3955                    true,
3956                    lbrr_coded != 0,
3957                    self.stream_channels,
3958                );
3959                silk_max_bits = bitrate_to_bits(max_bit_rate, fs, frame_size);
3960            }
3961            // C 2112-2147: the internal rates SILK may choose from. Hybrid's
3962            // CELT layer starts at 8 kHz, so its SILK layer is wideband. A
3963            // SILK-only packet with few bytes limits the rate.
3964            let mut desired_khz = frame_bandwidth.silk_khz();
3965            let min_khz = if mode == OpusMode::Hybrid { 16 } else { 8 };
3966            let mut max_khz = 16;
3967            if mode == OpusMode::SilkOnly {
3968                let mut effective_max_rate = bits_to_bitrate(8 * n_bytes as i32, fs, frame_size);
3969                if frame_rate > 50 {
3970                    effective_max_rate = effective_max_rate * 2 / 3;
3971                }
3972                if effective_max_rate < 8000 {
3973                    max_khz = 12;
3974                    desired_khz = desired_khz.min(12);
3975                }
3976                if effective_max_rate < 7000 {
3977                    max_khz = 8;
3978                    desired_khz = desired_khz.min(8);
3979                }
3980            }
3981
3982            // SILK's input: the filtered frame.
3983            //
3984            // - VoIP at 8 to 24 kHz: the fixed-point build of libopus, whose
3985            //   `hp_cutoff` is an integer filter on the 16-bit input (run on
3986            //   every frame above). SILK-only VoIP packets are byte for byte
3987            //   those of that build (tests/silk_fixed_point_compare.rs).
3988            // - VoIP at 48 kHz, and the other applications: the float
3989            //   build. SILK reads the frame of `pcm_buf` that `hp_cutoff` or
3990            //   `dc_reject` filtered (opus_encoder.c:2211). At 48 kHz the
3991            //   integer filter adds a constant of about -9 (in 16-bit
3992            //   units) at its lowest cutoff of 60 Hz, which SILK codes and
3993            //   the decoder plays as low-frequency energy in quiet frames
3994            //   (see `integer_hp_at_48k`).
3995            // - With `Audio`, an offset in the input is then gone in SILK
3996            //   packets as it is in CELT ones, and the decoded signal does
3997            //   not step by the offset when the mode changes.
3998            let required_size = frame_size * ch;
3999            let silk_input = if integer_hp {
4000                SilkInput::Int16(&self.buf_filtered[..required_size])
4001            } else {
4002                SilkInput::Float(&self.buf_celt_pcm[prefix..prefix + required_size])
4003            };
4004
4005            // C 1576-1581, 2190-2208: SILK starts afresh.
4006            //
4007            // - After CELT-only packets (`prefill == 1`): everything is
4008            //   cleared, once per packet (`silk_InitEncoder`). The later
4009            //   parts of a packet made of several frames clear the
4010            //   channels again.
4011            // - For the first frame at a new SILK rate that follows a
4012            //   redundant frame (`prefill == 2`): the channels are cleared,
4013            //   the state of the input low-pass filter stays.
4014            //
4015            // The encoder is then fed the 10 ms in the delay buffer.
4016            // Everything before the last `delay_compensation + 2.5 ms` is
4017            // cleared, and the next 2.5 ms fade in, "to avoid the encoder
4018            // trying to encode a discontinuity".
4019            //
4020            // As in libopus, the fade and the clearing change the delay
4021            // buffer itself. A Hybrid frame after CELT-only frames reads
4022            // the faded 2.5 ms again: its CELT encoder starts from them
4023            // (`tmp_prefill`, C 2297-2302).
4024            //
4025            // An encoder with only SILK has no prefill (C 2191). It never
4026            // follows CELT-only packets or a redundant frame anyway.
4027            let mut silk_prefill = None;
4028            if prefill == 1 && self.prev_enc_mode == Some(OpusMode::CeltOnly) {
4029                self.silk.reset();
4030            }
4031            if prefill != 0 && !silk_only_app {
4032                let mut prefill_input = None;
4033                if ebuf > 0 && delay > 0 && ebuf >= delay + f2_5 {
4034                    let offset = ebuf - delay - f2_5;
4035                    let faded = &mut self.delay_buffer[..ebuf * ch];
4036                    gain_fade(&mut faded[offset * ch..], 0.0, 1.0, f2_5, ch, fs);
4037                    faded[..offset * ch].fill(0.0);
4038                    // The prefill reads the float delay buffer whatever the
4039                    // application, so it follows the float build.
4040                    prefill_input = Some(SilkInput::Float(&self.delay_buffer[..ebuf * ch]));
4041                }
4042                silk_prefill = Some(SilkPrefill { rate_switch: prefill == 2, input: prefill_input });
4043            }
4044
4045            // C 2112, `silk_mode.nChannelsInternal`.
4046            self.silk_channels_internal = sch;
4047            let mut silk_ctl = SilkControl {
4048                channels_internal: sch,
4049                payload_size_ms: frame_ms,
4050                min_khz,
4051                max_khz,
4052                desired_khz,
4053                bit_rate: silk_bitrate,
4054                max_bits: silk_max_bits,
4055                // C opus_encoder.c:2133-2177: SILK runs at a constant
4056                // bitrate only in SILK-only packets without DRED data. A
4057                // Hybrid packet with a constant bitrate codes SILK at a
4058                // variable one, with a cap, and CELT takes up the rest
4059                // ("switch SILK to VBR with cap"); with DRED, DRED does.
4060                use_cbr: self.use_cbr && !silk_vbr_with_cap,
4061                complexity: self.complexity,
4062                packet_loss_perc: self.packet_loss_perc,
4063                lbrr_coded: lbrr_coded != 0,
4064                activity,
4065                use_dtx: self.silk_use_dtx,
4066                to_mono: self.silk_to_mono,
4067                reduced_dependency: self.prediction_disabled,
4068                opus_can_switch: self.silk_opus_can_switch,
4069                allow_bandwidth_switch: self.silk_allow_bandwidth_switch,
4070                fixed_point_res_nrg: self.fixed_point_res_nrg,
4071                ..SilkControl::default()
4072            };
4073            let prefilled = silk_prefill.is_some();
4074            let result = self.silk.encode(&mut silk_ctl, silk_input, silk_prefill, &mut self.rc);
4075            // C 2207: "Prevent a second switch in the real encode call."
4076            // A restart for a rate switch has made that switch.
4077            if prefilled {
4078                self.silk_opus_can_switch = false;
4079            }
4080            result?;
4081
4082            // In a packet made of several frames only the last part leaves
4083            // its answer, as in libopus.
4084            self.silk_allow_bandwidth_switch = silk_ctl.allow_bandwidth_switch;
4085            self.silk_in_wb_mode_without_variable_lp = silk_ctl.in_wb_mode_without_variable_lp;
4086            silk_fs_khz = silk_ctl.internal_khz;
4087            // enc_API.c:584: the stereo width SILK settled on, 0 for the
4088            // packet that leads over to mono. The CELT layer of a stereo
4089            // Hybrid frame is narrowed to it below.
4090            if ch == 2 {
4091                self.silk_stereo_width_q14 = silk_ctl.stereo_width_q14;
4092            }
4093            // C opus_encoder.c:2233: a rate switch SILK is ready for happens
4094            // on the next packet, not in the middle of this one.
4095            self.silk_opus_can_switch = silk_ctl.switch_ready && !self.nonfinal_frame;
4096            // C 2235-2241: without a decision of its own the frame is active
4097            // when SILK found voice activity in it (in its last frame, for a
4098            // packet of 40 or 60 ms).
4099            if activity == VAD_NO_DECISION {
4100                activity = (self.silk.mid().s_cmn.indices.signal_type != TYPE_NO_VOICE_ACTIVITY as i8) as i32;
4101                #[cfg(feature = "dred")]
4102                self.dred.set_activity(frame_size, activity);
4103            }
4104            // C 2242-2249: SILK's DTX left the packet out. Only the TOC byte
4105            // is sent, without padding. The rest of the frame is skipped:
4106            // the redundant frame of a coming rate switch, the CELT layer,
4107            // the delay buffer, the high band gain, and what the next frame
4108            // learns of this one (its mode, channels and duration, and that
4109            // a frame was coded).
4110            if silk_ctl.zero_bytes {
4111                output[0] = gen_toc(
4112                    mode,
4113                    frame_rate,
4114                    toc_bandwidth(mode, silk_fs_khz, frame_bandwidth),
4115                    self.stream_channels,
4116                );
4117                return Ok(1);
4118            }
4119            // C 2250-2259: that packet starts with a redundant CELT frame
4120            // (`silk_bw_switch`), and this one ends with one, when it has
4121            // room for it.
4122            // An encoder with only SILK codes no such frame (C 2253), and
4123            // `silk_bw_switch` is cleared again below.
4124            if self.silk_opus_can_switch {
4125                if !silk_only_app {
4126                    redundancy_bytes = compute_redundancy_bytes(
4127                        n_bytes,
4128                        self.packet_bitrate_bps,
4129                        frame_rate,
4130                        self.stream_channels,
4131                    );
4132                    redundancy = redundancy_bytes != 0;
4133                }
4134                celt_to_silk = false;
4135                self.silk_bw_switch = true;
4136            }
4137        }
4138
4139        // C `curr_bandwidth`.
4140        let toc_bandwidth = toc_bandwidth(mode, silk_fs_khz, frame_bandwidth);
4141        let toc = gen_toc(mode, frame_rate, toc_bandwidth, self.stream_channels);
4142
4143        // C 2262-2283: settings the CELT encoder gets in every mode. A
4144        // SILK-only packet needs them for its redundant frame. An encoder
4145        // with only SILK sets none of them (C 2264): libopus has no CELT
4146        // encoder there, and the one here is never used.
4147        if !silk_only_app {
4148            self.celt_enc.complexity = self.complexity;
4149            // libopus `CELT_SET_END_BAND`: match the TOC bandwidth so the
4150            // decoder reads the same number of coded bands.
4151            self.celt_enc.set_end_band(toc_bandwidth.celt_end_band());
4152            // C 2285: the channels the packet codes. The value is 1 or the
4153            // input's channel count, which the CELT encoder accepts.
4154            let _ = self.celt_enc.set_stream_channels(self.stream_channels);
4155            // C 2288-2294: "We may still decide to disable prediction later".
4156            if mode != OpusMode::SilkOnly {
4157                let _ = self
4158                    .celt_enc
4159                    .set_prediction(if self.prediction_disabled { 0 } else { 2 });
4160            }
4161            // C 2979-2989: OPUS_SET_PACKET_LOSS_PERC goes to the CELT encoder
4162            // too. The value was clamped to 0..=100 above.
4163            let _ = self.celt_enc.set_packet_loss_perc(self.packet_loss_perc);
4164            // C opus_encoder.c:3283-3297: OPUS_SET_LFE and OPUS_SET_ENERGY_MASK
4165            // go to the CELT encoder as well. libopus hands the mask over as a
4166            // pointer; here the values are copied before every frame.
4167            self.celt_enc.set_lfe(self.lfe);
4168            let mask = self.energy_mask.as_ref().map(|m| &m[..21 * ch]);
4169            self.celt_enc.set_energy_mask(mask);
4170        }
4171
4172        // C 2297-2302: a CELT or Hybrid frame in another mode than the
4173        // frame before restarts its CELT encoder, which first codes the
4174        // 2.5 ms before the frame's look-ahead (below). They are taken from
4175        // the delay buffer before it moves on. libopus leaves this out for
4176        // `RestrictedCelt` (C 2299 and 2478), whose frames are all
4177        // CELT-only, so the mode never changes.
4178        let celt_restart = mode != OpusMode::SilkOnly
4179            && self.prev_enc_mode.is_some()
4180            && self.prev_enc_mode != Some(mode)
4181            && self.application != Application::RestrictedCelt;
4182        if celt_restart {
4183            // The restricted applications, which keep no delay buffer,
4184            // never get here: their mode never changes.
4185            let start = ebuf.saturating_sub(delay + f2_5) * ch;
4186            self.celt_prefill[..f2_5 * ch]
4187                .copy_from_slice(&self.delay_buffer[start..start + f2_5 * ch]);
4188        }
4189
4190        {
4191            // C 2300-2312: the delay buffer takes the end of `pcm_buf`.
4192            let keep = ebuf as i64 - (frame_size as i64 + delay as i64);
4193            if keep > 0 {
4194                let keep = keep as usize;
4195                self.delay_buffer
4196                    .copy_within(ch * frame_size..ch * (frame_size + keep), 0);
4197                let dst = ch * keep;
4198                let n = (frame_size + delay) * ch;
4199                self.delay_buffer[dst..dst + n].copy_from_slice(&self.buf_celt_pcm[..n]);
4200            } else {
4201                let n = ebuf * ch;
4202                let src = (frame_size + delay - ebuf) * ch;
4203                self.delay_buffer[..n].copy_from_slice(&self.buf_celt_pcm[src..src + n]);
4204            }
4205            // C 2313-2320: Hybrid attenuates the high band when it gets
4206            // few bits. The gain fades in over CELT's overlap. "gain_fade()
4207            // and stereo_fade() need to be after the buffer copying because
4208            // we don't want any of this to affect the SILK part". Not for
4209            // an encoder with only SILK, which has no CELT mode for the
4210            // window (C `celt_mode != NULL`).
4211            if (self.prev_hb_gain < 1.0 || hb_gain < 1.0) && !silk_only_app {
4212                gain_fade(
4213                    &mut self.buf_celt_pcm[..frame_size * ch],
4214                    self.prev_hb_gain,
4215                    hb_gain,
4216                    frame_size,
4217                    ch,
4218                    fs,
4219                );
4220            }
4221        }
4222        self.prev_hb_gain = hb_gain;
4223
4224        // C 2321-2329: the stereo width goes down with the bitrate, from
4225        // full width at 32 kb/s to none at 16 kb/s. A stereo Hybrid frame
4226        // takes the width SILK settled on instead.
4227        if mode != OpusMode::Hybrid || self.stream_channels == 1 {
4228            self.silk_stereo_width_q14 = if d.equiv_rate > 32000 {
4229                16384
4230            } else if d.equiv_rate < 16000 {
4231                0
4232            } else {
4233                16384 - 2048 * (32000 - d.equiv_rate) / (d.equiv_rate - 14000)
4234            };
4235        }
4236        // C 2330-2349: "Apply stereo width reduction (at low bitrates)",
4237        // not in a surround stream.
4238        if self.energy_mask.is_none()
4239            && ch == 2
4240            && (self.hybrid_stereo_width_q14 < (1 << 14) || self.silk_stereo_width_q14 < (1 << 14))
4241        {
4242            let g1 = self.hybrid_stereo_width_q14 as f32 * (1.0 / 16384.0);
4243            let g2 = self.silk_stereo_width_q14 as f32 * (1.0 / 16384.0);
4244            // C `celt_mode != NULL`: not for an encoder with only SILK.
4245            if !silk_only_app {
4246                stereo_fade(&mut self.buf_celt_pcm, g1, g2, frame_size, fs);
4247            }
4248            self.hybrid_stereo_width_q14 = self.silk_stereo_width_q14;
4249        }
4250
4251        // C 2351-2378: say whether a redundant CELT frame follows, where it
4252        // lies and how long it is.
4253        //
4254        // - A Hybrid packet has a flag for it, but only when it has room
4255        //   for the flag and for the smallest frame that could follow
4256        //   (37 bits). The decoder makes the same test
4257        //   (opus_decoder.c:509-514).
4258        // - In a SILK-only packet the bytes after the SILK data are the
4259        //   redundant frame, so nothing but its position is written.
4260        if mode != OpusMode::CeltOnly
4261            && self.rc.tell() + 17 + 20 * (mode == OpusMode::Hybrid) as i32
4262                <= 8 * (n_bytes as i32 - 1)
4263        {
4264            if mode == OpusMode::Hybrid {
4265                self.rc.encode_bit_logp(redundancy, 12);
4266            }
4267            if redundancy {
4268                self.rc.encode_bit_logp(celt_to_silk, 1);
4269                let max_redundancy = if mode == OpusMode::Hybrid {
4270                    // "Reserve the 8 bits needed for the redundancy length,
4271                    // and at least a few bits for CELT if possible".
4272                    (n_bytes as i32 - 1) - ((self.rc.tell() + 8 + 3 + 7) >> 3)
4273                } else {
4274                    (n_bytes as i32 - 1) - ((self.rc.tell() + 7) >> 3)
4275                };
4276                // "Target the same bit-rate for redundancy as for the rest,
4277                // up to a max of 257 bytes".
4278                let bytes = (redundancy_bytes as i32).min(max_redundancy);
4279                redundancy_bytes = bytes.clamp(2, 257) as usize;
4280                if mode == OpusMode::Hybrid {
4281                    self.rc.enc_uint(redundancy_bytes as u32 - 2, 256);
4282                }
4283            }
4284        } else {
4285            redundancy = false;
4286        }
4287        if !redundancy {
4288            self.silk_bw_switch = false;
4289            redundancy_bytes = 0;
4290        }
4291        // C 2386-2413: the bytes of the main frame.
4292        let mut nb_compr_bytes = if mode == OpusMode::SilkOnly {
4293            // Only the first ceil(tell/8) bytes go into the packet, and
4294            // `done` below writes no byte past them. So the coder ends
4295            // there, and `done` does not clear the unused rest of the
4296            // buffer, about 1.2 kB, which libopus clears (C 2389).
4297            let used = ((self.rc.tell() + 7) >> 3).max(0) as u32;
4298            if used < self.rc.storage {
4299                self.rc.shrink(used);
4300            }
4301            (used as usize).min(n_bytes - 1 - redundancy_bytes)
4302        } else {
4303            #[allow(unused_mut)]
4304            let mut nb = n_bytes - 1 - redundancy_bytes;
4305            // C 2399-2411: the CELT part leaves room for the DRED data.
4306            #[cfg(feature = "dred")]
4307            if self.dred.duration() > 0 {
4308                let dred_bytes = bitrate_to_bits(self.dred.bitrate_bps(), fs, frame_size) / 8;
4309                // "Allow CELT to steal up to 25% of the remaining bits."
4310                let max_celt_bytes = nb as i32 - dred_bytes * 3 / 4;
4311                // "But try to give CELT at least 5 bytes to prevent a
4312                // mismatch with the redundancy signaling."
4313                let max_celt_bytes = max_celt_bytes.max((self.rc.tell() + 7) / 8 + 5);
4314                // "Subject to the original max."
4315                nb = nb.min(max_celt_bytes as usize);
4316            }
4317            self.rc.shrink(nb as u32);
4318            nb
4319        };
4320        // "If false, we already busted the budget and we'll end up with a
4321        // 'PLC frame'" (C 2484).
4322        let fits = self.rc.error == 0 && self.rc.tell() <= 8 * nb_compr_bytes as i32;
4323
4324        // The redundant frame's bytes and final range.
4325        let mut redundant = [0u8; 257];
4326        let mut redundant_rng = 0u32;
4327
4328        // C 2416-2418 (CELT_SET_ANALYSIS): the CELT encoder codes the
4329        // redundant frame and the CELT part with the analysis of the frame.
4330        // A reset of the CELT encoder below makes it invalid again, as in
4331        // libopus: the first CELT frame after a change of mode, and the
4332        // redundant frame of a switch to CELT-only, are coded without it.
4333        if redundancy || mode != OpusMode::SilkOnly {
4334            self.celt_enc.set_analysis(&analysis.info);
4335        }
4336
4337        // C 2419-2425 (CELT_SET_SILK_INFO): the SILK frame's signal type and
4338        // quantization offset steer CELT's bit target and its handling of
4339        // transients. A reset of the CELT encoder below clears them again,
4340        // as in libopus: the first Hybrid frame after a reset is coded with
4341        // signal type 0 and offset 0.
4342        if mode == OpusMode::Hybrid {
4343            const QUANTIZATION_OFFSETS_Q10: [[i32; 2]; 2] = [[100, 240], [32, 100]];
4344            let indices = &self.silk.mid().s_cmn.indices;
4345            self.celt_enc.set_silk_info(
4346                indices.signal_type as i32,
4347                QUANTIZATION_OFFSETS_Q10[(indices.signal_type >> 1) as usize & 1]
4348                    [indices.quant_offset_type as usize & 1],
4349            );
4350        }
4351
4352        // C 2427-2441: "5 ms redundant frame for CELT->SILK". It continues
4353        // the CELT stream of the packets before, so it is coded first, from
4354        // the start of `pcm_buf`. Then the CELT encoder forgets that stream.
4355        if redundancy && celt_to_silk && fits {
4356            redundant_rng = encode_celt_redundancy(
4357                state_mut(&mut self.celt_enc),
4358                &self.buf_celt_pcm[..f5 * ch],
4359                f5,
4360                &mut redundant[..redundancy_bytes],
4361            )?;
4362            self.celt_enc.reset_state();
4363        }
4364
4365        if mode != OpusMode::SilkOnly {
4366            let start_band = if mode == OpusMode::Hybrid { HYBRID_START_BAND } else { 0 };
4367            // C `st->bitrate_bps` (opus_encoder.c:2454, 2462): CELT's
4368            // variable bitrate goes by the packet's bitrate, which the
4369            // output buffer can lower. In Hybrid it is what SILK's rate
4370            // leaves of the bitrate. With a constant bitrate libopus leaves
4371            // CELT at `OPUS_BITRATE_MAX` (C 2286): CELT fills the bytes it
4372            // is given, and its decisions go by the rate of the whole
4373            // packet.
4374            //
4375            // CELT takes no bitrate under 501 b/s. In libopus such a
4376            // request fails, and CELT keeps `OPUS_BITRATE_MAX`: the packet
4377            // grows to whatever the buffer holds. opus1 gives CELT 501 b/s
4378            // instead, a difference from libopus on purpose. In Hybrid an
4379            // energy mask can bring this about, because it can raise the
4380            // SILK rate above the total (C 2105). A CELT-only packet has a
4381            // bitrate of at least 500 b/s, and CELT codes the same frames at
4382            // 500 and 501 b/s.
4383            let celt_bitrate = if self.use_cbr {
4384                OPUS_BITRATE_MAX
4385            } else if mode == OpusMode::Hybrid {
4386                (self.packet_bitrate_bps - hybrid_silk_rate).max(501)
4387            } else {
4388                self.packet_bitrate_bps.max(501)
4389            };
4390            // The value is accepted: it is `OPUS_BITRATE_MAX` or above 500.
4391            let _ = self.celt_enc.set_bitrate(celt_bitrate);
4392            self.celt_enc.set_vbr(!self.use_cbr);
4393            // C 2453-2462: Hybrid VBR is unconstrained (CELT can take bits
4394            // SILK left), CELT-only VBR follows the setting.
4395            self.celt_enc
4396                .set_constrained_vbr(mode == OpusMode::CeltOnly && self.vbr_constraint);
4397            // C 2465-2476: "When Using DRED CBR, we can actually make the
4398            // CELT part VBR and have DRED pick up the slack." CELT gets what
4399            // the bitrate leaves after DRED (and SILK). A rate under 501 b/s
4400            // is refused, as in libopus, and CELT keeps `OPUS_BITRATE_MAX`.
4401            #[cfg(feature = "dred")]
4402            if self.use_cbr && self.dred.duration() > 0 {
4403                let mut celt_bitrate = self.packet_bitrate_bps;
4404                if mode == OpusMode::Hybrid {
4405                    celt_bitrate -= hybrid_silk_rate;
4406                }
4407                self.celt_enc.set_vbr(true);
4408                self.celt_enc.set_constrained_vbr(false);
4409                let _ = self.celt_enc.set_bitrate(celt_bitrate);
4410            }
4411            // C `CELT_SET_START_BAND`; 0 and 17 are both valid.
4412            let _ = self.celt_enc.set_start_band(start_band);
4413
4414            // C 2478-2486: the CELT state of another mode is of no use, and
4415            // the decoder resets its CELT state at the same place. The
4416            // encoder starts again, codes the 2.5 ms before the frame into
4417            // 2 bytes that are thrown away ("Prefilling"), and codes the
4418            // frame without prediction from them.
4419            if celt_restart {
4420                self.celt_enc.reset_state();
4421                let mut prefill_rc = RangeCoder::new_encoder(2);
4422                self.celt_enc
4423                    .encode(&self.celt_prefill[..f2_5 * ch], f2_5, &mut prefill_rc);
4424                let _ = self.celt_enc.set_prediction(0);
4425            }
4426
4427            // C 2493: CELT codes the start of `pcm_buf`. The range coder
4428            // holds `nb_compr_bytes`.
4429            if fits {
4430                self.celt_enc
4431                    .encode(&self.buf_celt_pcm[..frame_size * ch], frame_size, &mut self.rc);
4432            }
4433        }
4434
4435        self.rc.done();
4436
4437        // C 2555-2560: every coded frame leaves its mode behind for the
4438        // next one. After a frame that announced the switch to CELT-only,
4439        // that mode is CELT-only.
4440        self.prev_enc_mode = Some(if d.to_celt { OpusMode::CeltOnly } else { mode });
4441        self.prev_channels = sch;
4442        self.prev_frame_size = frame_size;
4443        // C 2562: from here on a frame is coded. The packets too small to
4444        // code anything leave `first` alone.
4445        self.first = false;
4446
4447        // C 2564-2577: the DTX of the Opus layer, when SILK's DTX is not in
4448        // use for the packet. After 200 ms without activity the frame is
4449        // replaced by its TOC byte, for up to 400 ms. The encoders went on
4450        // as for a coded frame, without padding.
4451        if self.use_dtx && !self.silk_use_dtx {
4452            let frame_ms_q1 = 2 * 1000 * frame_size as i32 / fs;
4453            if decide_dtx_mode(activity, &mut self.nb_no_activity_ms_q1, frame_ms_q1) {
4454                // libopus has coded the redundant frame of a switch to
4455                // CELT-only before this point (C 2513-2538): the CELT-only
4456                // packets that follow continue from it.
4457                if redundancy && !celt_to_silk {
4458                    let mut redundant = [0u8; 257];
4459                    self.encode_silk_to_celt_redundancy(frame_size, &mut redundant[..redundancy_bytes])?;
4460                } else if d.to_celt {
4461                    self.celt_enc.reset_state();
4462                }
4463                self.range_final = 0;
4464                output[0] = toc;
4465                return Ok(1);
4466            }
4467        } else {
4468            self.nb_no_activity_ms_q1 = 0;
4469        }
4470
4471        // C 2582-2594: "In the unlikely case that the SILK encoder busted
4472        // its target, tell the decoder to call the PLC". The packet holds
4473        // one frame of one zero byte, which a decoder conceals. With FEC the
4474        // LBRR section can squeeze the main frame below what even the
4475        // damage-control re-encode fits, which is the case this exists for.
4476        if !fits || self.rc.error != 0 || self.rc.tell() > 8 * nb_compr_bytes as i32 {
4477            output[0] = toc;
4478            output[1] = 0;
4479            // No redundant frame goes with it, in libopus neither: a frame
4480            // this full has no room for the 17 bits (37 for Hybrid) that
4481            // the redundancy needs (C 2351), so `redundancy` is off and
4482            // C 2379-2383 clear `silk_bw_switch`.
4483            self.silk_bw_switch = false;
4484            if d.to_celt {
4485                self.celt_enc.reset_state();
4486            }
4487            // libopus goes on to the DRED data and the padding.
4488            return self.finish_frame(output, 2, first_frame);
4489        }
4490
4491        // C 2509-2511: the state of the range coder once the frame is
4492        // coded. `done` above does not change it.
4493        self.range_final = self.rc.rng;
4494
4495        if mode == OpusMode::SilkOnly {
4496            if !redundancy {
4497                // C 2595-2603: "it's perfectly reasonable to strip off
4498                // trailing zero bytes as the required range decoder
4499                // behavior is to fill these in". Not with a redundant
4500                // frame behind: the decoder finds that by the length.
4501                while nb_compr_bytes > 2 && self.rc.buf[nb_compr_bytes - 1] == 0 {
4502                    nb_compr_bytes -= 1;
4503                }
4504            }
4505        } else {
4506            // CELT shrinks the range coder to what a variable bitrate used.
4507            nb_compr_bytes = (self.rc.storage as usize).min(nb_compr_bytes);
4508        }
4509
4510        // C 2513-2538: "5 ms redundant frame for SILK->CELT". The CELT-only
4511        // packets that follow continue from it. It is coded without
4512        // prediction; the next CELT-only frame sets it back to 2 (C
4513        // 2288-2294).
4514        //
4515        // A frame that announces the switch without a redundant frame (the
4516        // packet had no room) resets the CELT encoder all the same. The
4517        // decoder starts the CELT-only packets from the reset state then,
4518        // and libopus's encoder, which keeps the state of its last CELT
4519        // frame, predicts from energies the decoder does not have.
4520        if redundancy && !celt_to_silk {
4521            redundant_rng =
4522                self.encode_silk_to_celt_redundancy(frame_size, &mut redundant[..redundancy_bytes])?;
4523        } else if d.to_celt {
4524            self.celt_enc.reset_state();
4525        }
4526
4527        // C 2543-2546: the TOC byte, the main frame, the redundant frame.
4528        output[0] = toc;
4529        output[1..1 + nb_compr_bytes].copy_from_slice(&self.rc.buf[..nb_compr_bytes]);
4530        let mut ret = 1 + nb_compr_bytes;
4531        output[ret..ret + redundancy_bytes].copy_from_slice(&redundant[..redundancy_bytes]);
4532        ret += redundancy_bytes;
4533        self.range_final ^= redundant_rng;
4534        self.finish_frame(output, ret, first_frame)
4535    }
4536
4537    /// The end of a frame's packet (C 2602-2652). `output[..ret]` holds the
4538    /// packet; `output.len()` is the size it may take.
4539    ///
4540    /// - With DRED (feature `dred`), the DRED data of the first coded frame
4541    ///   of a packet goes into the padding, as the extension with ID 126
4542    ///   for frame 0. With a constant bitrate the padding fills the packet.
4543    /// - Otherwise a constant bitrate pads the packet to its full size.
4544    fn finish_frame(&mut self, output: &mut [u8], ret: usize, first_frame: bool) -> Result<usize, Error> {
4545        let orig_max_data_bytes = output.len();
4546        // C 2606: only with DRED on. The buffer below is 1,000 bytes that
4547        // would otherwise be set to zero for every packet.
4548        #[cfg(feature = "dred")]
4549        if first_frame && self.dred_on() {
4550            use crate::dnn::dred::{DRED_EXTENSION_ID, DRED_MAX_DATA_SIZE};
4551            let mut buf = [0u8; DRED_MAX_DATA_SIZE];
4552            // "Remaining space for DRED, accounting for cost the 3 extra
4553            // bytes for code 3, padding length, and extension number."
4554            let room = orig_max_data_bytes as i32 - ret as i32 - 3;
4555            let n = self.dred.write_extension(&mut self.rc, &mut buf, room, !self.use_cbr);
4556            if n > 0 {
4557                let ext = [extensions::Extension::new(DRED_EXTENSION_ID, 0, &buf[..n])];
4558                let padding = packet::Padding::from_flag(self.use_cbr);
4559                // C returns `OPUS_INTERNAL_ERROR` when this fails.
4560                return packet::pad_with_extensions(output, ret, orig_max_data_bytes, padding, &ext)
4561                    .map_err(|_| Error::INTERNAL_ERROR);
4562            }
4563        }
4564        #[cfg(not(feature = "dred"))]
4565        let _ = first_frame;
4566        // C 2643-2651: a constant bitrate pads the packet to its full size.
4567        if self.use_cbr {
4568            packet::pad(output, ret, orig_max_data_bytes)?;
4569            return Ok(orig_max_data_bytes);
4570        }
4571        Ok(ret)
4572    }
4573
4574    /// Whether DRED is on (feature `dred` and a duration above 0).
4575    #[inline]
4576    fn dred_on(&self) -> bool {
4577        #[cfg(feature = "dred")]
4578        {
4579            self.dred.duration() > 0
4580        }
4581        #[cfg(not(feature = "dred"))]
4582        false
4583    }
4584
4585    /// The bitrate DRED takes from the current packet, 0 without DRED.
4586    #[inline]
4587    fn dred_bitrate_bps(&self) -> i32 {
4588        #[cfg(feature = "dred")]
4589        {
4590            self.dred.bitrate_bps()
4591        }
4592        #[cfg(not(feature = "dred"))]
4593        0
4594    }
4595
4596    /// The 5 ms redundant CELT frame at the end of a frame that announces
4597    /// the switch to CELT-only (opus_encoder.c:2513-2538), coded into
4598    /// `out`. Returns its final range.
4599    ///
4600    /// It starts from a fresh CELT state, as the decoder does, and codes
4601    /// the last 5 ms of the frame in `buf_celt_pcm`. In front of it the
4602    /// 2.5 ms before those 5 ms are coded into 2 bytes that are thrown
4603    /// away, to fill the CELT encoder's overlap and pre-emphasis memories
4604    /// ("NOTE: We could speed this up slightly ... by just adding a
4605    /// function that prefills the buffer"). Both are coded without
4606    /// prediction.
4607    fn encode_silk_to_celt_redundancy(
4608        &mut self,
4609        frame_size: usize,
4610        out: &mut [u8],
4611    ) -> Result<u32, Error> {
4612        let ch = self.channels;
4613        let f2_5 = self.sampling_rate as usize / 400;
4614        let f5 = 2 * f2_5;
4615        self.celt_enc.reset_state();
4616        let _ = self.celt_enc.set_prediction(0);
4617        // Frames that announce a switch to CELT-only are 10 ms or longer,
4618        // so the 7.5 ms lie inside the frame.
4619        let warm_up = (frame_size - f5 - f2_5) * ch..(frame_size - f5) * ch;
4620        let mut dummy = [0u8; 2];
4621        // The 2 bytes are thrown away, and so is any error in them.
4622        let _ = encode_celt_redundancy(
4623            state_mut(&mut self.celt_enc),
4624            &self.buf_celt_pcm[warm_up],
4625            f2_5,
4626            &mut dummy,
4627        );
4628        encode_celt_redundancy(
4629            state_mut(&mut self.celt_enc),
4630            &self.buf_celt_pcm[(frame_size - f5) * ch..frame_size * ch],
4631            f5,
4632            out,
4633        )
4634    }
4635
4636    /// Write a packet that codes nothing: only its first byte, and a frame
4637    /// count when it holds three to six 20 ms frames (60 to 120 ms of CELT
4638    /// or Hybrid, 100 ms of SILK). A decoder conceals such a
4639    /// packet like a lost one. This is libopus `opus_encode_native`, "If the
4640    /// space is too low to do something useful, emit 'PLC' frames"
4641    /// (opus_encoder.c:1344-1405).
4642    ///
4643    /// The first byte names the mode and bandwidth of the last packet that
4644    /// was coded (C `st->mode`, `st->bandwidth`). With a constant bitrate
4645    /// the packet is padded to `max_data_bytes`, as `opus_packet_pad` does.
4646    /// Returns the packet length. No encoder state changes.
4647    fn write_placeholder(
4648        &self,
4649        frame_rate: i32,
4650        max_data_bytes: usize,
4651        output: &mut [u8],
4652    ) -> Result<usize, Error> {
4653        let mut toc_mode = self.mode;
4654        let mut bw = self.bandwidth;
4655        let mut frame_rate = frame_rate;
4656        let mut packet_code = 0u8;
4657        let mut num_multiframes = 0u8;
4658        if frame_rate > 100 {
4659            toc_mode = OpusMode::CeltOnly;
4660        }
4661        // 40 ms -> 2 x 20 ms if in CELT_ONLY or HYBRID mode.
4662        if frame_rate == 25 && toc_mode != OpusMode::SilkOnly {
4663            frame_rate = 50;
4664            packet_code = 1;
4665        }
4666        // ">= 60 ms frames": frame rates 16 (60 ms), 12 (80 ms), 10 (100 ms)
4667        // and 8 (120 ms).
4668        if frame_rate <= 16 {
4669            // "1 x 60 ms, 2 x 40 ms, 2 x 60 ms": SILK frames, as one frame or
4670            // two of equal size (code 1), which the first byte alone can
4671            // say. So can a buffer of one byte, whatever the mode. 100 ms
4672            // has no such form and never gets here with one byte
4673            // (`encode_impl` refuses it).
4674            if output.len() == 1 || (toc_mode == OpusMode::SilkOnly && frame_rate != 10) {
4675                toc_mode = OpusMode::SilkOnly;
4676                packet_code = (frame_rate <= 12) as u8;
4677                frame_rate = if frame_rate == 12 { 25 } else { 16 };
4678            } else {
4679                // 3, 4, 5 or 6 frames of 20 ms (code 3).
4680                num_multiframes = (50 / frame_rate) as u8;
4681                frame_rate = 50;
4682                packet_code = 3;
4683            }
4684        }
4685        let index = bandwidth_fec_index(bw);
4686        if toc_mode == OpusMode::SilkOnly && index > 2 {
4687            bw = Bandwidth::Wideband;
4688        } else if toc_mode == OpusMode::CeltOnly && bw == Bandwidth::Mediumband {
4689            bw = Bandwidth::Narrowband;
4690        } else if toc_mode == OpusMode::Hybrid && index <= 3 {
4691            bw = Bandwidth::Superwideband;
4692        }
4693        output[0] = gen_toc(toc_mode, frame_rate, bw, self.stream_channels) | packet_code;
4694        let mut ret = if packet_code <= 1 { 1 } else { 2 };
4695        let max_data_bytes = max_data_bytes.max(ret);
4696        if packet_code == 3 {
4697            output[1] = num_multiframes;
4698        }
4699        if self.use_cbr {
4700            packet::pad(output, ret, max_data_bytes)?;
4701            ret = max_data_bytes;
4702        }
4703        Ok(ret)
4704    }
4705
4706    /// A packet made of several frames (libopus `opus_encode_native`,
4707    /// opus_encoder.c:1697-1838):
4708    ///
4709    /// - CELT-only and Hybrid frames are 20 ms at most, so a packet of 40
4710    ///   to 120 ms is made of 2 to 6 frames of 20 ms.
4711    /// - SILK-only frames are 60 ms at most. 80 ms is coded as 2 frames of
4712    ///   40 ms, 100 ms as 5 frames of 20 ms, 120 ms as 2 frames of 60 ms.
4713    ///
4714    /// Every frame is coded with the packet's `decisions`, so the packet
4715    /// has one configuration. The frames are joined into one packet with
4716    /// frame count code 1, 2 or 3, as libopus's repacketizer does.
4717    ///
4718    /// `cbr_bytes` is the packet size a constant bitrate gives.
4719    /// `analysis_cursor` is the read position of the speech and music
4720    /// analysis before it ran for this packet, or `None` when it did not
4721    /// run. Each frame then reads the result for its own 20 ms (C
4722    /// 1727-1734, 1797-1800). `lsb_depth` is the precision of the input,
4723    /// for the test for digital silence of each frame.
4724    #[allow(clippy::too_many_arguments)]
4725    fn encode_multiframe(
4726        &mut self,
4727        input: &[f32],
4728        frame_size: usize,
4729        decisions: FrameDecisions,
4730        cbr_bytes: usize,
4731        output: &mut [u8],
4732        analysis_cursor: Option<(usize, i32)>,
4733        lsb_depth: i32,
4734    ) -> Result<usize, Error> {
4735        // Up to 120 ms of 20 ms frames.
4736        const MAX_SUB: usize = 6;
4737        let ch = self.channels;
4738        let fs = self.sampling_rate;
4739        let fs_u = fs as usize;
4740        // C 1712-1722: the duration of each frame.
4741        let enc_frame = if decisions.mode == OpusMode::SilkOnly {
4742            if frame_size == 2 * fs_u / 25 {
4743                // 80 ms -> 2 x 40 ms
4744                fs_u / 25
4745            } else if frame_size == 3 * fs_u / 25 {
4746                // 120 ms -> 2 x 60 ms
4747                3 * fs_u / 50
4748            } else {
4749                // 100 ms -> 5 x 20 ms
4750                fs_u / 50
4751            }
4752        } else {
4753            fs_u / 50
4754        };
4755        if enc_frame == 0 || !frame_size.is_multiple_of(enc_frame) {
4756            return Err(Error::internal("invalid multi-frame size"));
4757        }
4758        let nb = frame_size / enc_frame;
4759        if !(2..=MAX_SUB).contains(&nb) {
4760            return Err(Error::internal("unsupported multi-frame size"));
4761        }
4762
4763        // C 1735-1795: how large the packet and each of its frames may be.
4764        //
4765        // - The packet: the caller's buffer, or under CBR the constant size.
4766        // - A frame: its share of the packet once the worst-case header is
4767        //   taken off. Under CBR also never more than the bitrate gives
4768        //   one frame.
4769        //
4770        // Not ported on purpose: libopus 1.6 applies the "never more than
4771        // the bitrate gives one frame" limit under VBR too (`curr_max`,
4772        // opus_encoder.c:1785). That turns VBR into a hard cap per frame and
4773        // costs libopus itself up to 23 dB when in-band FEC is on (measured:
4774        // 24 kHz stereo Hybrid, 128 kb/s, 40 ms, FEC: 3.9 dB against 27.2 dB
4775        // for its own 20 ms packets). libopus 1.5 and earlier had no such
4776        // limit under VBR, and neither has opus1.
4777        let max_header_bytes = if nb == 2 { 3 } else { 2 + (nb - 1) * 2 };
4778        // C 1749: VBR, and CBR at the maximum bitrate, may fill the buffer.
4779        let repacketize_len = if self.use_cbr && self.user_bitrate != Bitrate::Max {
4780            cbr_bytes.min(output.len())
4781        } else {
4782            output.len()
4783        };
4784        let max_len_sum = (nb + repacketize_len).saturating_sub(max_header_bytes);
4785        let nominal_part =
4786            (bitrate_to_bits(self.packet_bitrate_bps, fs, enc_frame) / 8).max(0) as usize;
4787
4788        // C `tmp_data`: the frames one after the other. A frame may take
4789        // all of the room it is given (`curr_max`), beyond 1276 bytes: CBR
4790        // pads it to that size, and the first coded frame carries the DRED
4791        // data in its padding. `MULTIFRAME_BYTES` says why they fit. The
4792        // buffer grows, set to zero, as far as the rooms reach, so each
4793        // byte is cleared once. A room may start inside the room of the
4794        // frame before. That does not matter: a frame writes each byte of
4795        // the packet it returns before it reads it.
4796        let mut tmp: FixedVec<u8, MULTIFRAME_BYTES> = FixedVec::new();
4797        let mut lens = [0usize; MAX_SUB];
4798        let mut tot_size = 0usize;
4799        // C `dtx_count`: the frames DTX left out, which are 1 byte long.
4800        let mut dtx_count = 0usize;
4801        let mut result = Ok(());
4802        // C 1762-1767. A packet that leads over to mono is not coded so: its
4803        // frames code two channels without SILK's fade, and the
4804        // caller's channel setting becomes mono, so that the next packet is
4805        // mono at once. The setting stays (a libopus behavior, ported as it
4806        // is).
4807        let bak_to_mono = self.silk_to_mono;
4808        if bak_to_mono {
4809            self.force_channels = Some(1);
4810        } else {
4811            self.prev_channels = self.stream_channels;
4812        }
4813        for i in 0..nb {
4814            let start = i * enc_frame * ch;
4815            let end = start + enc_frame * ch;
4816            let sub_input = &input[start..end];
4817            // C 1727-1734 and 1796-1802: when the analysis ran for this
4818            // packet, each frame reads its own result. "Reset analysis
4819            // position to the beginning of the first frame so we can use it
4820            // one frame at a time."
4821            let info = match analysis_cursor {
4822                Some(cursor) => self.frame_analysis_info((i == 0).then_some(cursor), enc_frame),
4823                None => AnalysisInfo::default(),
4824            };
4825            let frame_analysis = FrameAnalysis {
4826                info,
4827                is_silence: is_digital_silence(sub_input, lsb_depth),
4828            };
4829            self.silk_to_mono = false;
4830            self.nonfinal_frame = i + 1 < nb;
4831            // C 1771-1773: "When switching from SILK/Hybrid to CELT, only
4832            // ask for a switch at the last frame". A redundant frame for
4833            // leaving CELT-only goes with the first frame.
4834            let frame_to_celt = decisions.to_celt && i == nb - 1;
4835            let frame_decisions = FrameDecisions {
4836                to_celt: frame_to_celt,
4837                redundancy: decisions.redundancy
4838                    && (frame_to_celt || (!decisions.to_celt && i == 0)),
4839                ..decisions
4840            };
4841            // C 1774-1776: "Attempt DRED encoding until we have a non-DTX
4842            // frame. In case of DTX refresh, that allows for DRED not to be
4843            // in the first frame."
4844            let first_frame = i == 0 || i == dtx_count;
4845            #[allow(unused_mut)]
4846            let mut curr_max = max_len_sum / nb;
4847            if self.use_cbr {
4848                curr_max = curr_max.min(nominal_part);
4849            }
4850            // C 1786-1789: the DRED bytes of the whole packet are taken from
4851            // every frame's share and given to the first coded frame, whose
4852            // packet carries the DRED data.
4853            #[cfg(feature = "dred")]
4854            {
4855                let dred_bytes = (bitrate_to_bits(self.dred.bitrate_bps(), fs, frame_size) / 8).max(0) as usize;
4856                curr_max = curr_max.min(max_len_sum.saturating_sub(dred_bytes) / nb);
4857                if first_frame {
4858                    curr_max += dred_bytes;
4859                }
4860            }
4861            let curr_max = curr_max.min(max_len_sum.saturating_sub(tot_size));
4862            // Under CBR the rooms add up to at most the CBR size, so the
4863            // limit below applies only with VBR (`MULTIFRAME_BYTES`). A CBR
4864            // room cut short would change the packet, so it is an error.
4865            let room = MULTIFRAME_BYTES - tot_size;
4866            if self.use_cbr && curr_max > room {
4867                result = Err(Error::internal("a CBR frame does not fit the multi-frame buffer"));
4868                break;
4869            }
4870            let curr_max = curr_max.min(room);
4871            if tmp.len() < tot_size + curr_max {
4872                tmp.resize(tot_size + curr_max, 0);
4873            }
4874            match self.encode_frame(
4875                sub_input,
4876                enc_frame,
4877                &mut tmp[tot_size..tot_size + curr_max],
4878                frame_decisions,
4879                frame_analysis,
4880                first_frame,
4881            ) {
4882                Ok(n) => {
4883                    lens[i] = n;
4884                    tot_size += n;
4885                    if n == 1 {
4886                        dtx_count += 1;
4887                    }
4888                }
4889                Err(e) => {
4890                    result = Err(e);
4891                    break;
4892                }
4893            }
4894        }
4895        self.nonfinal_frame = false;
4896        self.silk_to_mono = bak_to_mono;
4897        result?;
4898
4899        // C 1821-1831: the frames go into one packet (libopus's
4900        // repacketizer), with the extensions of their padding. A constant
4901        // bitrate pads it to its full size, unless DTX left out every frame.
4902        // As in libopus, a frame the repacketizer refuses, or a packet it
4903        // cannot write, is an internal error.
4904        let mut rp = packet::Repacketizer::new();
4905        let mut start = 0;
4906        for &len in lens.iter().take(nb) {
4907            let part = &tmp[start..start + len];
4908            start += len;
4909            if packet::nb_frames(part) != Ok(1) {
4910                return Err(Error::internal("unexpected frame count in a part of a packet"));
4911            }
4912            rp.cat(part).map_err(|_| Error::INTERNAL_ERROR)?;
4913        }
4914        rp.out_range_ext(
4915            0,
4916            nb,
4917            &mut output[..repacketize_len],
4918            packet::Framing::Normal,
4919            packet::Padding::from_flag(self.use_cbr && dtx_count != nb),
4920            &[],
4921        )
4922        .map_err(|_| Error::INTERNAL_ERROR)
4923    }
4924}
4925
4926use celt::PcmLayout;
4927#[cfg(feature = "osce-bwe")]
4928use dnn::osce::OsceExtMode;
4929
4930/// A decoder of one Opus stream to mono or stereo audio: libopus
4931/// `OpusDecoder`.
4932///
4933/// [`new`](Self::new) builds one for an output sampling rate and channel
4934/// count, which need not be those of the encoder. [`init`](Self::init)
4935/// builds the same decoder in memory that the caller provides. Each call of
4936/// [`decode`](Self::decode) (`f32` samples), [`decode_i16`](Self::decode_i16)
4937/// or [`decode24`](Self::decode24) decodes one packet, or conceals a lost
4938/// one, into interleaved audio.
4939///
4940/// ```
4941/// use opus1::{Channels, OpusDecoder, SampleRate};
4942///
4943/// let mut decoder = OpusDecoder::new(SampleRate::Hz48000, Channels::Stereo)?;
4944/// let mut pcm = [0.0f32; 960 * 2];
4945/// // A lost packet of 20 ms: the decoder conceals it.
4946/// let samples = decoder.decode(&[], 960, &mut pcm)?;
4947/// assert_eq!(samples, 960);
4948/// # Ok::<(), opus1::Error>(())
4949/// ```
4950///
4951/// Without the `heap` feature the decoder holds all of its state inline,
4952/// about 52 KB; see [`init`](Self::init).
4953pub struct OpusDecoder {
4954    #[cfg(not(feature = "heap"))]
4955    celt_dec: CeltDecoder,
4956    #[cfg(feature = "heap")]
4957    celt_dec: Box<CeltDecoder>,
4958    #[cfg(not(feature = "heap"))]
4959    silk_dec: silk::dec_api::SilkDecoder,
4960    #[cfg(feature = "heap")]
4961    silk_dec: Box<silk::dec_api::SilkDecoder>,
4962    sampling_rate: i32,
4963    channels: usize,
4964
4965    /// C `st->mode`: the mode of the last packet that was decoded, lost
4966    /// frames not counted. `None` before the first packet.
4967    mode: Option<OpusMode>,
4968    /// C `st->prev_mode`: the mode the last frame was decoded or concealed
4969    /// in.
4970    prev_mode: Option<OpusMode>,
4971    /// C `st->bandwidth`: the audio bandwidth of the last packet that was
4972    /// decoded, set with `mode`. `None` before the first packet (libopus 0).
4973    bandwidth: Option<Bandwidth>,
4974
4975    /// Whether the previous frame had redundancy (mode transition marker).
4976    prev_redundancy: bool,
4977    /// C `st->frame_size`: samples per channel in one frame of the last
4978    /// packet.
4979    frame_size: usize,
4980
4981    /// C `st->stream_channels`: the channel count the last packet codes,
4982    /// from its first byte. It may differ from `channels`. The CELT layer
4983    /// converts by itself once it is told (`CELT_SET_CHANNELS`).
4984    stream_channels: usize,
4985
4986    /// C `st->rangeFinal`: the state of the range decoder after the last
4987    /// frame, 0 after a lost frame.
4988    range_final: u32,
4989    /// C `st->last_packet_duration`: samples per channel of the last
4990    /// successful decode call, see
4991    /// [`last_packet_duration`](Self::last_packet_duration).
4992    last_packet_duration: usize,
4993    /// C `st->softclip_mem`: what the soft clipper of `decode_i16` carries
4994    /// from one packet to the next, per channel.
4995    softclip_mem: [f32; OPUS_MAX_CHANNELS],
4996
4997    /// C `st->DecControl.nChannelsInternal`: the channel count of the last
4998    /// SILK frame that carried data. A lost frame is concealed with it,
4999    /// whatever the packets in between said. 0 before the first SILK frame.
5000    silk_channels_internal: usize,
5001    /// C `st->DecControl.internalSampleRate`: the SILK rate in Hz of the
5002    /// last SILK frame that carried data, kept for concealment in the same
5003    /// way. 0 before the first SILK frame.
5004    silk_internal_rate: i32,
5005
5006    #[cfg(not(feature = "heap"))]
5007    w_pcm_i16: FixedVec<i16, OPUS_PCM_I16>,
5008    #[cfg(feature = "heap")]
5009    w_pcm_i16: Box<FixedVec<i16, OPUS_PCM_I16>>,
5010    /// Float output of one packet for `decode_i16`. It is allocated in
5011    /// `new`, so that no decode call allocates, and filled at first use.
5012    /// `None` while a call uses it.
5013    #[cfg(feature = "heap")]
5014    w_pcm_float: Option<Box<FixedVec<f32, OPUS_PCM_PACKET>>>,
5015
5016    /// C `st->complexity`: the decoder complexity, 0 to 10, set with
5017    /// `OPUS_SET_COMPLEXITY`. A reset keeps it, as in libopus.
5018    complexity: i32,
5019    /// C `st->decode_gain`: the output gain in 1/256 dB, set with
5020    /// `OPUS_SET_GAIN`. A reset keeps it, as in libopus.
5021    decode_gain: i32,
5022    /// C `st->DecControl.prevPitchLag`: the pitch lag of the last SILK
5023    /// frame, in samples at 48 kHz, or 0 when that frame was not voiced.
5024    /// `silk_Decode` sets it after each frame. A reset keeps it, as in
5025    /// libopus.
5026    silk_prev_pitch_lag: i32,
5027    /// C `st->DecControl.enable_osce_bwe`, set with `OPUS_SET_OSCE_BWE`. A
5028    /// reset keeps it, as in libopus.
5029    #[cfg(feature = "osce-bwe")]
5030    osce_bwe: bool,
5031    /// The neural network models of the decoder and the kernel variant
5032    /// they run on. A reset keeps them (libopus reloads PitchDNN).
5033    #[cfg(all(feature = "dnn", feature = "heap"))]
5034    dnn: Box<dnn::DecoderDnn>,
5035    #[cfg(all(feature = "dnn", not(feature = "heap")))]
5036    dnn: dnn::DecoderDnn,
5037    /// C `st->lpcnet`: the state of deep packet loss concealment, 42 KB.
5038    /// SILK appends every decoded 16 kHz frame to its history, at every
5039    /// complexity. From complexity 5 it conceals lost SILK wideband and
5040    /// CELT-only frames. `reset_state` clears it, except the state of the
5041    /// FARGAN vocoder, as libopus does.
5042    #[cfg(all(feature = "deep-plc", feature = "heap"))]
5043    deep_plc: Box<dnn::plc::DeepPlc>,
5044    #[cfg(all(feature = "deep-plc", not(feature = "heap")))]
5045    deep_plc: dnn::plc::DeepPlc,
5046}
5047
5048impl core::fmt::Debug for OpusDecoder {
5049    /// The main settings, as their getters return them. The state of the
5050    /// codec and its buffers are left out.
5051    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
5052        let mut d = f.debug_struct("OpusDecoder");
5053        d.field("sampling_rate", &self.sampling_rate())
5054            .field("channels", &self.channels())
5055            .field("complexity", &self.complexity())
5056            .field("gain", &self.gain())
5057            .field("phase_inversion_disabled", &self.phase_inversion_disabled());
5058        #[cfg(feature = "osce-bwe")]
5059        d.field("osce_bwe", &self.osce_bwe);
5060        d.finish_non_exhaustive()
5061    }
5062}
5063
5064impl OpusDecoder {
5065    /// libopus `opus_decoder_create`: a new decoder whose output has
5066    /// `sampling_rate` and `channels` channels. A packet coded at another
5067    /// rate or with another channel count is converted, as in libopus. The
5068    /// complexity starts at 0 and the gain at 0 dB.
5069    ///
5070    /// It cannot fail at present: the `Result` leaves room for checks that
5071    /// a later release may need.
5072    ///
5073    /// Without the `heap` feature the decoder is returned through the
5074    /// stack, which needs about 200 KB of stack (500 KB with the neural
5075    /// network features). [`init`](Self::init) builds it in place instead.
5076    pub fn new(sampling_rate: SampleRate, channels: Channels) -> Result<Self, Error> {
5077        let mut dec = MaybeUninit::<Self>::uninit();
5078        Self::init(&mut dec, sampling_rate, channels)?;
5079        // SAFETY: `init` succeeded, so it initialized `dec`.
5080        Ok(unsafe { dec.assume_init() })
5081    }
5082
5083    /// Builds a decoder in `slot`, memory that the caller provides, and
5084    /// returns it. The decoder is the same as the one of [`new`](Self::new).
5085    /// Like `new`, it cannot fail at present.
5086    ///
5087    /// Without the `heap` feature a decoder holds all of its state inline:
5088    /// about 52 KB, and 153 KB with the neural network features. `new`
5089    /// returns it through the stack, which needs about three times that.
5090    /// `init` writes the decoder straight into `slot`, so building it needs
5091    /// only a little stack. With `heap` it writes the large parts straight
5092    /// into their heap memory.
5093    ///
5094    /// The intended use is memory that lives as long as the program, such
5095    /// as a `static`: build the decoder there once and never drop it.
5096    ///
5097    /// ```
5098    /// use core::mem::MaybeUninit;
5099    /// use opus1::{Channels, OpusDecoder, SampleRate};
5100    ///
5101    /// static mut DECODER: MaybeUninit<OpusDecoder> = MaybeUninit::uninit();
5102    ///
5103    /// // Run once at start-up.
5104    /// let slot = &raw mut DECODER;
5105    /// // SAFETY: nothing else uses `DECODER` at the same time.
5106    /// let decoder: &'static mut OpusDecoder =
5107    ///     OpusDecoder::init(unsafe { &mut *slot }, SampleRate::Hz48000, Channels::Stereo)?;
5108    ///
5109    /// let mut pcm = [0.0f32; 960 * 2];
5110    /// decoder.decode(&[], 960, &mut pcm)?; // a lost frame
5111    /// # Ok::<(), opus1::Error>(())
5112    /// ```
5113    ///
5114    /// `init` does not drop what `slot` holds. With the `heap` feature a
5115    /// decoder owns heap memory, so a second `init` on the same slot leaks
5116    /// the memory of the first decoder. To free a decoder built with
5117    /// `init`, call [`MaybeUninit::assume_init_drop`] on `slot` when it is
5118    /// no longer used. Without `heap` a decoder owns no other memory, so
5119    /// nothing leaks and nothing needs to be dropped.
5120    pub fn init(
5121        slot: &mut MaybeUninit<Self>,
5122        sampling_rate: SampleRate,
5123        channels: Channels,
5124    ) -> Result<&mut Self, Error> {
5125        // SAFETY: `slot` is valid for writes of `Self`, and `write_new`
5126        // initializes every field, so `slot` holds a decoder afterwards.
5127        unsafe {
5128            Self::write_new(slot.as_mut_ptr(), sampling_rate.hz() as i32, channels.count());
5129            Ok(slot.assume_init_mut())
5130        }
5131    }
5132
5133    /// Writes a new decoder to `this` field by field (see
5134    /// `crate::in_place`). The arguments must be valid.
5135    ///
5136    /// # Safety
5137    /// `this` must be valid for writes of `Self`.
5138    unsafe fn write_new(this: *mut Self, sampling_rate: i32, channels: usize) {
5139        let mode = modes::default_mode();
5140        // SAFETY: the caller guarantees that `this` is valid for writes.
5141        // Each closure below writes the whole field it is given.
5142        unsafe {
5143            write_fields!(this, {
5144                #[cfg(not(feature = "heap"))]
5145                celt_dec = |p| CeltDecoder::write_new(p, mode, channels, sampling_rate),
5146                #[cfg(feature = "heap")]
5147                celt_dec = |p: *mut Box<CeltDecoder>| {
5148                    let celt = |q| CeltDecoder::write_new(q, mode, channels, sampling_rate);
5149                    p.write(in_place::boxed(celt))
5150                },
5151                // C `silk_InitDecoder`. The SILK decoder learns its rates and
5152                // channel counts with every frame (`SilkDecControl`).
5153                #[cfg(not(feature = "heap"))]
5154                silk_dec = |p| silk::dec_api::SilkDecoder::write_new(p),
5155                #[cfg(feature = "heap")]
5156                silk_dec = |p: *mut Box<silk::dec_api::SilkDecoder>| {
5157                    p.write(in_place::boxed(|q| silk::dec_api::SilkDecoder::write_new(q)))
5158                },
5159                sampling_rate: sampling_rate,
5160                channels: channels,
5161                mode: None,
5162                prev_mode: None,
5163                bandwidth: None,
5164                prev_redundancy: false,
5165                // C `opus_decoder_init`: `st->frame_size = Fs/400`.
5166                frame_size: sampling_rate as usize / 400,
5167                stream_channels: channels,
5168                range_final: 0,
5169                last_packet_duration: 0,
5170                softclip_mem: [0.0; OPUS_MAX_CHANNELS],
5171                silk_channels_internal: 0,
5172                silk_internal_rate: 0,
5173
5174                #[cfg(not(feature = "heap"))]
5175                w_pcm_i16 = |p| FixedVec::write_from_value(p, 0i16, 960 * channels),
5176                #[cfg(feature = "heap")]
5177                w_pcm_i16 = |p: *mut Box<FixedVec<i16, OPUS_PCM_I16>>| {
5178                    p.write(in_place::boxed(|q| FixedVec::write_from_value(q, 0i16, 960 * channels)))
5179                },
5180
5181                #[cfg(feature = "heap")]
5182                w_pcm_float: Some(in_place::boxed(|q| FixedVec::write_new(q))),
5183
5184                // C `opus_decoder_init`: `st->complexity = 0`.
5185                complexity: 0,
5186                decode_gain: 0,
5187                silk_prev_pitch_lag: 0,
5188                #[cfg(feature = "osce-bwe")]
5189                osce_bwe: false,
5190                #[cfg(all(feature = "dnn", not(feature = "heap")))]
5191                dnn = |p| dnn::DecoderDnn::write_new(p),
5192                #[cfg(all(feature = "dnn", feature = "heap"))]
5193                dnn = |p: *mut Box<dnn::DecoderDnn>| {
5194                    p.write(in_place::boxed(|q| dnn::DecoderDnn::write_new(q)))
5195                },
5196                // C `lpcnet_plc_init`.
5197                #[cfg(all(feature = "deep-plc", not(feature = "heap")))]
5198                deep_plc = |p| dnn::plc::DeepPlc::write_new(p),
5199                #[cfg(all(feature = "deep-plc", feature = "heap"))]
5200                deep_plc = |p: *mut Box<dnn::plc::DeepPlc>| {
5201                    p.write(in_place::boxed(|q| dnn::plc::DeepPlc::write_new(q)))
5202                },
5203            });
5204        }
5205    }
5206
5207    /// Decode one Opus packet into interleaved `f32` PCM, returning the
5208    /// number of samples per channel written.
5209    ///
5210    /// `frame_size` is the room in `output`, in samples per channel. The
5211    /// packet says how many samples it holds. Only the first
5212    /// `samples * channels` values of `output` are written, where `samples`
5213    /// is the result; the rest of `output` is left as it was, as in libopus.
5214    /// A `frame_size` of 0 is an error of kind
5215    /// [`BadArg`](ErrorKind::BadArg), checked before anything else, as in
5216    /// libopus. The other decode methods check it in the same way.
5217    ///
5218    /// The packet may code another channel count than the decoder has, as
5219    /// in libopus. A mono packet is written to both channels of a stereo
5220    /// decoder. A stereo packet is mixed down by a mono decoder. The count
5221    /// may change from one packet to the next.
5222    ///
5223    /// The output is not clipped: like libopus `opus_decode_float`, a loud
5224    /// signal comes back with peaks beyond ยฑ1.0. Use
5225    /// [`decode_i16`](Self::decode_i16) or [`pcm_soft_clip`] where the
5226    /// samples must stay in range.
5227    ///
5228    /// Packet loss follows libopus: pass an empty packet (`&[]`) to conceal
5229    /// `frame_size` samples (a multiple of 2.5 ms), or a ToC-only 1-byte
5230    /// packet to conceal the duration that ToC describes. Either way the
5231    /// frame is concealed in the previous packet's mode; the placeholder's
5232    /// mode, bandwidth and channel bits are ignored. A 1-byte packet whose
5233    /// frame count code is 2 or 3 lacks the bytes that code needs and is
5234    /// invalid, as in libopus.
5235    ///
5236    /// Inside a longer packet, a frame of 0 or 1 bytes stands for a lost
5237    /// frame and is concealed in the same way.
5238    pub fn decode(
5239        &mut self,
5240        input: &[u8],
5241        frame_size: usize,
5242        output: &mut [f32],
5243    ) -> Result<usize, Error> {
5244        let (samples, _) = self.decode_native(input, frame_size, output, false, false, false)?;
5245        Ok(samples)
5246    }
5247
5248    /// Rebuild a lost packet from the in-band forward error correction
5249    /// (FEC) data of the packet that follows it: libopus `opus_decode_float`
5250    /// with `decode_fec = 1`.
5251    ///
5252    /// `data` is the packet received after the lost one. `frame_size` is the
5253    /// duration that was lost, in samples per channel, a multiple of 2.5 ms.
5254    /// Exactly that many samples are written. Decode `data` itself with
5255    /// [`decode`](Self::decode) afterwards.
5256    ///
5257    /// A SILK-only or Hybrid packet can carry a low-bitrate copy of the
5258    /// frame before it. That copy fills the end of the lost duration, and
5259    /// anything before it is concealed. The whole duration is concealed
5260    /// when `data` cannot hold such a copy (it is CELT-only, the packet
5261    /// before the loss was CELT-only, or `frame_size` is shorter than a
5262    /// frame of `data`) or holds none. In a Hybrid stream the copy covers
5263    /// the band below 8 kHz; the band above is concealed.
5264    pub fn decode_fec(
5265        &mut self,
5266        data: &[u8],
5267        frame_size: usize,
5268        output: &mut [f32],
5269    ) -> Result<usize, Error> {
5270        self.decode_native(data, frame_size, output, true, false, false)
5271            .map(|(samples, _)| samples)
5272    }
5273
5274    /// Decode one Opus packet into interleaved 16-bit PCM: libopus
5275    /// `opus_decode` in the float build.
5276    ///
5277    /// The packet is decoded to floating point and soft-clipped, so that
5278    /// peaks beyond full scale are rounded off instead of cut
5279    /// ([`pcm_soft_clip`]). The result is rounded to 16 bits, to the
5280    /// nearest integer. A value halfway between two integers is rounded as
5281    /// libopus rounds it on the same processor: on ARM away from zero in
5282    /// blocks of 16 values and to the even integer for the values after the
5283    /// last whole block, elsewhere to the even integer. A lost packet is
5284    /// given as in [`decode`](Self::decode).
5285    pub fn decode_i16(
5286        &mut self,
5287        input: &[u8],
5288        frame_size: usize,
5289        output: &mut [i16],
5290    ) -> Result<usize, Error> {
5291        self.decode_i16_native(input, frame_size, output, false)
5292    }
5293
5294    /// [`decode_fec`](Self::decode_fec) with 16-bit output: libopus
5295    /// `opus_decode` with `decode_fec = 1`.
5296    pub fn decode_fec_i16(
5297        &mut self,
5298        data: &[u8],
5299        frame_size: usize,
5300        output: &mut [i16],
5301    ) -> Result<usize, Error> {
5302        self.decode_i16_native(data, frame_size, output, true)
5303    }
5304
5305    /// Decode one Opus packet into interleaved 24-bit samples held in
5306    /// 32-bit integers: libopus `opus_decode24` in the float build.
5307    ///
5308    /// Full scale is 2^23: each float sample is multiplied by 8388608 and
5309    /// rounded to the nearest integer, halfway values to the even one
5310    /// (libopus `RES2INT24`). Unlike [`decode_i16`](Self::decode_i16),
5311    /// there is no soft clipping and no limit to 24 bits, as in libopus:
5312    /// a loud signal comes back with values beyond ยฑ8388607. A value beyond
5313    /// the 32-bit range gives the nearest 32-bit value. A lost packet is
5314    /// given as in [`decode`](Self::decode).
5315    pub fn decode24(
5316        &mut self,
5317        input: &[u8],
5318        frame_size: usize,
5319        output: &mut [i32],
5320    ) -> Result<usize, Error> {
5321        self.decode_int_native(input, frame_size, output, false, false, res_to_int24)
5322    }
5323
5324    /// [`decode_fec`](Self::decode_fec) with 24-bit output: libopus
5325    /// `opus_decode24` with `decode_fec = 1`.
5326    pub fn decode_fec24(
5327        &mut self,
5328        data: &[u8],
5329        frame_size: usize,
5330        output: &mut [i32],
5331    ) -> Result<usize, Error> {
5332        self.decode_int_native(data, frame_size, output, true, false, res_to_int24)
5333    }
5334
5335    /// Conceal lost audio with deep redundancy (DRED) data into interleaved
5336    /// `f32` PCM: libopus `opus_decoder_dred_decode_float`. The names
5337    /// follow those of [`decode`](Self::decode):
5338    /// [`dred_decode_i16`](Self::dred_decode_i16) writes 16-bit samples
5339    /// (libopus `opus_decoder_dred_decode`) and
5340    /// [`dred_decode24`](Self::dred_decode24) 24-bit samples (libopus
5341    /// `opus_decoder_dred_decode24`).
5342    ///
5343    /// `dred` holds the processed DRED data of a packet received after the
5344    /// loss ([`OpusDredDecoder::parse`]). `dred_offset` is the position of
5345    /// the lost audio: the number of samples (at this decoder's rate)
5346    /// between the start of the lost audio and the start of that packet.
5347    /// `frame_size` samples per channel are concealed, a multiple of
5348    /// 2.5 ms, as for a lost packet. Returns `frame_size`.
5349    ///
5350    /// The DRED features that cover the lost audio go to deep PLC, which
5351    /// synthesizes the audio from them instead of predicting features.
5352    /// Where `dred` has no features for that time, or when it is not
5353    /// processed, the loss is concealed as without DRED.
5354    ///
5355    /// Errors: [`BadArg`](crate::ErrorKind::BadArg) when `frame_size` is 0, and
5356    /// those of a lost packet in [`decode`](Self::decode). These checks come
5357    /// before any change of the decoder.
5358    #[cfg(feature = "dred")]
5359    pub fn dred_decode(
5360        &mut self,
5361        dred: &OpusDred,
5362        dred_offset: i32,
5363        frame_size: usize,
5364        output: &mut [f32],
5365    ) -> Result<usize, Error> {
5366        self.check_dred_decode(frame_size, output.len())?;
5367        self.queue_dred_features(dred, dred_offset, frame_size);
5368        self.decode_native(&[], frame_size, output, false, false, false)
5369            .map(|(samples, _)| samples)
5370    }
5371
5372    /// [`dred_decode`](Self::dred_decode) with 16-bit output: libopus
5373    /// `opus_decoder_dred_decode`. Each sample is rounded to the nearest
5374    /// integer, halfway values to the even one, and limited to the 16-bit
5375    /// range, as libopus's `FLOAT2INT16` does.
5376    #[cfg(feature = "dred")]
5377    pub fn dred_decode_i16(
5378        &mut self,
5379        dred: &OpusDred,
5380        dred_offset: i32,
5381        frame_size: usize,
5382        output: &mut [i16],
5383    ) -> Result<usize, Error> {
5384        self.dred_decode_int(dred, dred_offset, frame_size, output, float2int16)
5385    }
5386
5387    /// [`dred_decode`](Self::dred_decode) with 24-bit output in
5388    /// 32-bit integers: libopus `opus_decoder_dred_decode24`. Each sample
5389    /// is scaled by 2^23 and rounded to the nearest integer, halfway values
5390    /// to the even one. There is no limit to 24 bits, as in libopus.
5391    #[cfg(feature = "dred")]
5392    pub fn dred_decode24(
5393        &mut self,
5394        dred: &OpusDred,
5395        dred_offset: i32,
5396        frame_size: usize,
5397        output: &mut [i32],
5398    ) -> Result<usize, Error> {
5399        self.dred_decode_int(dred, dred_offset, frame_size, output, float2int24)
5400    }
5401
5402    /// The checks of a DRED decode that come before any change of state:
5403    /// libopus's `frame_size <= 0` and 2.5 ms checks, and the room in the
5404    /// output.
5405    #[cfg(feature = "dred")]
5406    fn check_dred_decode(&self, frame_size: usize, output_len: usize) -> Result<(), Error> {
5407        if frame_size == 0 {
5408            return Err(Error::INVALID_FRAME_SIZE);
5409        }
5410        if !is_whole_2_5ms(frame_size, self.sampling_rate) {
5411            return Err(Error::LOST_FRAME_SIZE);
5412        }
5413        if frame_size.checked_mul(self.channels).is_none_or(|len| len > output_len) {
5414            return Err(Error::BUFFER_TOO_SMALL);
5415        }
5416        Ok(())
5417    }
5418
5419    /// The DRED step at the start of libopus `opus_decode_native`
5420    /// (`src/opus_decoder.c:735-758`): replaces the queue of deep PLC with
5421    /// the DRED features of the `frame_size` samples that start
5422    /// `dred_offset` samples before the DRED packet.
5423    ///
5424    /// One feature frame is queued per 10 ms of `frame_size` (at least
5425    /// one). When the last call of deep PLC was not a concealment (it
5426    /// appended decoded audio), two more frames come first, because deep PLC
5427    /// then needs two frames of history before it conceals. A frame that
5428    /// `dred` does not hold goes in as a gap, except before the newest
5429    /// DRED frame (a negative position), where nothing goes in.
5430    #[cfg(feature = "dred")]
5431    fn queue_dred_features(&mut self, dred: &OpusDred, dred_offset: i32, frame_size: usize) {
5432        use dnn::models::dred_rdovae_stats::DRED_NUM_FEATURES;
5433        if !dred.is_processed() {
5434            return;
5435        }
5436        let plc = &mut self.deep_plc;
5437        plc.fec_clear();
5438        let f10 = self.sampling_rate / 100;
5439        let init_frames: i32 = if plc.blend() { 0 } else { 2 };
5440        let features_per_frame = (frame_size / f10 as usize).max(1) as i32;
5441        let needed_feature_frames = init_frames + features_per_frame;
5442        // libopus: "We floor instead of rounding because 5-ms overlap
5443        // compensates for the missing 0.5 rounding offset."
5444        let newest = (dred_offset as f32 + (dred.dred_offset * f10 / 4) as f32) / f10 as f32;
5445        let newest = newest.floor() as i32;
5446        for i in 0..needed_feature_frames {
5447            let feature_offset = (init_frames - i - 2).wrapping_add(newest);
5448            if feature_offset >= 0 && feature_offset < 4 * dred.nb_latents {
5449                let start = feature_offset as usize * DRED_NUM_FEATURES;
5450                let features = dred.fec_features[start..start + DRED_NUM_FEATURES].try_into().ok();
5451                plc.fec_add(features);
5452            } else if feature_offset >= 0 {
5453                plc.fec_add(None);
5454            }
5455        }
5456    }
5457
5458    /// `dred_decode_i16` and `dred_decode24`: conceal into a float buffer, then
5459    /// convert each sample. The buffer holds 120 ms, as in
5460    /// `decode_i16_native`. A longer loss is concealed 60 ms at a time,
5461    /// which gives the same samples as one call; the DRED features are
5462    /// queued once, before the first piece, as libopus does for the whole
5463    /// call.
5464    #[cfg(feature = "dred")]
5465    fn dred_decode_int<T>(
5466        &mut self,
5467        dred: &OpusDred,
5468        dred_offset: i32,
5469        frame_size: usize,
5470        output: &mut [T],
5471        convert: fn(f32) -> T,
5472    ) -> Result<usize, Error> {
5473        self.check_dred_decode(frame_size, output.len())?;
5474        self.queue_dred_features(dred, dred_offset, frame_size);
5475        let saved_duration = self.last_packet_duration;
5476        let channels = self.channels;
5477        let max_samples = packet::max_packet_samples(self.sampling_rate);
5478        let step = max_samples / 2;
5479        #[cfg(feature = "heap")]
5480        let mut pcm = self.w_pcm_float.take().unwrap_or_default();
5481        #[cfg(not(feature = "heap"))]
5482        let mut pcm: FixedVec<f32, OPUS_PCM_PACKET> = FixedVec::new();
5483        let mut done = 0;
5484        let result = loop {
5485            let left = frame_size - done;
5486            let piece = if left > max_samples { step } else { left };
5487            let len = piece * channels;
5488            if pcm.len() < len {
5489                pcm.resize(len, 0.0);
5490            }
5491            match self.decode_native(&[], piece, &mut pcm[..len], false, false, true) {
5492                Ok((samples, _)) => {
5493                    let out = &mut output[done * channels..(done + samples) * channels];
5494                    for (o, &x) in out.iter_mut().zip(&pcm[..samples * channels]) {
5495                        *o = convert(x);
5496                    }
5497                    done += samples;
5498                }
5499                Err(e) => break Err(e),
5500            }
5501            if piece == left {
5502                break Ok(done);
5503            }
5504        };
5505        #[cfg(feature = "heap")]
5506        {
5507            self.w_pcm_float = Some(pcm);
5508        }
5509        // libopus conceals the whole loss in one call, which sets the
5510        // duration once: to the whole loss, or not at all when it fails.
5511        self.last_packet_duration = if result.is_ok() { frame_size } else { saved_duration };
5512        result
5513    }
5514
5515    /// libopus `opus_decode` (opus_decoder.c, float build): decode into a
5516    /// float buffer with the soft clipper on, then round to 16 bits.
5517    ///
5518    /// The soft clipper needs the whole packet at once, so the float buffer
5519    /// holds 120 ms, the longest packet. A longer loss is concealed 60 ms at
5520    /// a time, which gives the same samples as concealing it in one call. At least 60 ms stay for the last call,
5521    /// enough for the longest frame an FEC copy can stand for.
5522    fn decode_i16_native(
5523        &mut self,
5524        data: &[u8],
5525        frame_size: usize,
5526        output: &mut [i16],
5527        decode_fec: bool,
5528    ) -> Result<usize, Error> {
5529        // C `opus_decode`: soft clipping (`OPTIONAL_CLIP`), then
5530        // `celt_float2int16`.
5531        self.decode_int_native(data, frame_size, output, decode_fec, true, celt_float2int16)
5532    }
5533
5534    /// Integer output through a float buffer: libopus `opus_decode` and
5535    /// `opus_decode24` of the float build. `soft_clip` is `opus_decode`'s
5536    /// `OPTIONAL_CLIP`; `convert` turns the float samples into `T`.
5537    fn decode_int_native<T>(
5538        &mut self,
5539        data: &[u8],
5540        frame_size: usize,
5541        output: &mut [T],
5542        decode_fec: bool,
5543        soft_clip: bool,
5544        convert: fn(&[f32], &mut [T]),
5545    ) -> Result<usize, Error> {
5546        // C `opus_decode` and `opus_decode24`: `frame_size <= 0` is
5547        // OPUS_BAD_ARG, before anything else.
5548        if frame_size == 0 {
5549            return Err(Error::INVALID_FRAME_SIZE);
5550        }
5551        let channels = self.channels;
5552        let lost = decode_fec || data.is_empty();
5553        let max_samples = packet::max_packet_samples(self.sampling_rate);
5554        let step = max_samples / 2;
5555        if lost && frame_size > max_samples {
5556            // `decode_native` checks each call, but the whole loss must be
5557            // checked before any of it is concealed. libopus also reads the
5558            // packet before it conceals anything, so an invalid packet is
5559            // an error that leaves the decoder as it was.
5560            if !is_whole_2_5ms(frame_size, self.sampling_rate) {
5561                return Err(Error::LOST_FRAME_SIZE);
5562            }
5563            // A product that overflows cannot fit any buffer.
5564            if frame_size.checked_mul(channels).is_none_or(|len| len > output.len()) {
5565                return Err(Error::BUFFER_TOO_SMALL);
5566            }
5567            if !data.is_empty() {
5568                packet::parse(data, packet::Framing::Normal)?;
5569            }
5570        }
5571
5572        // The buffer leaves the decoder during the call, because the decoder
5573        // is borrowed while it fills the buffer. Without `heap` it is an
5574        // uninitialized array on the stack; only the part a call fills is
5575        // touched.
5576        let split = lost && frame_size > max_samples;
5577        let saved_duration = self.last_packet_duration;
5578        #[cfg(feature = "heap")]
5579        let mut pcm = self.w_pcm_float.take().unwrap_or_default();
5580        #[cfg(not(feature = "heap"))]
5581        let mut pcm: FixedVec<f32, OPUS_PCM_PACKET> = FixedVec::new();
5582        let mut done = 0;
5583        let result = loop {
5584            let last = !(lost && frame_size - done > max_samples);
5585            let (data, piece, decode_fec) = if last {
5586                (data, frame_size - done, decode_fec)
5587            } else {
5588                (&[][..], step, false)
5589            };
5590            let output = &mut output[done * channels..];
5591            // The float buffer gets the length of `output`, so that
5592            // `decode_native` checks the caller's buffer. It need not be
5593            // longer than the call or the packet.
5594            let needed = if lost {
5595                piece
5596            } else {
5597                match packet::nb_samples(data, self.sampling_rate()) {
5598                    Ok(samples) => piece.min(samples),
5599                    Err(e) => break Err(e),
5600                }
5601            };
5602            let len = output.len().min(needed * channels);
5603            if pcm.len() < len {
5604                pcm.resize(len, 0.0);
5605            }
5606            match self.decode_native(data, piece, &mut pcm[..len], decode_fec, false, soft_clip) {
5607                Ok((samples, _)) => {
5608                    // A piece of a long loss is 60 ms, a whole number of
5609                    // blocks of `celt_float2int16`, so the blocks fall where
5610                    // they fall in libopus's single conversion of the call.
5611                    convert(&pcm[..samples * channels], output);
5612                    done += samples;
5613                }
5614                Err(e) => break Err(e),
5615            }
5616            if last {
5617                break Ok(done);
5618            }
5619        };
5620        #[cfg(feature = "heap")]
5621        {
5622            self.w_pcm_float = Some(pcm);
5623        }
5624        if split {
5625            // libopus conceals the whole loss in one call, which sets the
5626            // duration once: to the whole loss, or not at all when the call
5627            // fails.
5628            self.last_packet_duration = if result.is_ok() { frame_size } else { saved_duration };
5629        }
5630        result
5631    }
5632
5633    /// Decode a packet that may be followed by other data: libopus
5634    /// `opus_decode_native` (opus_decoder.c).
5635    ///
5636    /// - `data` empty: the packet is lost. `frame_size` samples are
5637    ///   concealed.
5638    /// - `decode_fec`: `data` is the packet after a lost one, see
5639    ///   [`decode_fec`](Self::decode_fec).
5640    /// - `self_delimited`: `data` starts with a self-delimited packet
5641    ///   (RFC 6716 appendix B), as every stream but the last of a
5642    ///   multistream packet does.
5643    /// - `soft_clip`: a decoded packet is soft-clipped with this decoder's
5644    ///   memory ([`pcm_soft_clip`]), as libopus does for 16-bit output.
5645    ///   Concealed and FEC output is left as it is, as in libopus. The
5646    ///   caller converts to 16 bits: [`celt_float2int16`] for one stream
5647    ///   (`opus_decode`), [`float2int16`] for each sample of a multistream
5648    ///   stream (`opus_multistream_decode`).
5649    ///
5650    /// Returns the samples per channel written to `output`, and the number
5651    /// of bytes of `data` the packet takes (0 for a lost packet).
5652    pub(crate) fn decode_native(
5653        &mut self,
5654        data: &[u8],
5655        frame_size: usize,
5656        output: &mut [f32],
5657        decode_fec: bool,
5658        self_delimited: bool,
5659        soft_clip: bool,
5660    ) -> Result<(usize, usize), Error> {
5661        // C `opus_decode_float`: `frame_size <= 0` is OPUS_BAD_ARG, before
5662        // anything else.
5663        if frame_size == 0 {
5664            return Err(Error::INVALID_FRAME_SIZE);
5665        }
5666        let channels = self.channels;
5667        if (decode_fec || data.is_empty()) && !is_whole_2_5ms(frame_size, self.sampling_rate) {
5668            return Err(Error::LOST_FRAME_SIZE);
5669        }
5670        // A lost duration so long that `frame_size * channels` overflows
5671        // cannot fit any buffer.
5672        let lost_len = frame_size.checked_mul(channels);
5673        if data.is_empty() {
5674            let lost_len = lost_len
5675                .filter(|&len| len <= output.len())
5676                .ok_or(Error::BUFFER_TOO_SMALL)?;
5677            self.conceal(frame_size, &mut output[..lost_len])?;
5678            self.last_packet_duration = frame_size;
5679            return Ok((frame_size, 0));
5680        }
5681
5682        let toc = data[0];
5683        let packet_mode = mode_from_toc(toc);
5684        let packet_bandwidth = packet::bandwidth(toc);
5685        let packet_frame_size = packet::samples_per_frame(toc, self.sampling_rate());
5686        let packet_channels = packet::nb_channels(toc).count();
5687        let parsed = packet::parse(data, packet::Framing::from_flag(self_delimited))?;
5688
5689        if decode_fec {
5690            if lost_len.is_none_or(|len| len > output.len()) {
5691                return Err(Error::BUFFER_TOO_SMALL);
5692            }
5693            // If no FEC can be present, run the loss concealment.
5694            if frame_size < packet_frame_size
5695                || packet_mode == OpusMode::CeltOnly
5696                || self.mode == Some(OpusMode::CeltOnly)
5697            {
5698                self.conceal(frame_size, &mut output[..frame_size * channels])?;
5699                self.last_packet_duration = frame_size;
5700                return Ok((frame_size, parsed.packet_offset()));
5701            }
5702            let frame = parsed.frame(data, 0);
5703            // Otherwise, conceal everything except the duration the FEC
5704            // data stands for.
5705            let lead = frame_size - packet_frame_size;
5706            if lead != 0 {
5707                self.conceal(lead, &mut output[..lead * channels])?;
5708                // C: the concealment is a call of its own, which sets the
5709                // duration. It stays when the FEC frame below fails.
5710                self.last_packet_duration = lead;
5711            }
5712            // Complete with FEC.
5713            self.mode = Some(packet_mode);
5714            self.bandwidth = Some(packet_bandwidth);
5715            self.frame_size = packet_frame_size;
5716            self.stream_channels = packet_channels;
5717            self.decode_or_conceal_frame(
5718                packet_mode,
5719                packet_bandwidth,
5720                frame,
5721                packet_frame_size,
5722                &mut output[lead * channels..frame_size * channels],
5723                true,
5724            )?;
5725            self.last_packet_duration = frame_size;
5726            return Ok((frame_size, parsed.packet_offset()));
5727        }
5728
5729        // The duration comes from the ToC, not from the caller's
5730        // `frame_size`, which only says how much room there is.
5731        let decoded_total = parsed.nb_frames() * packet_frame_size;
5732        if decoded_total > frame_size {
5733            return Err(Error::FRAME_SIZE_TOO_SMALL);
5734        }
5735        if output.len() < decoded_total * channels {
5736            return Err(Error::BUFFER_TOO_SMALL);
5737        }
5738        // Update the state as the last step, so that an invalid packet
5739        // leaves it alone.
5740        self.mode = Some(packet_mode);
5741        self.bandwidth = Some(packet_bandwidth);
5742        self.frame_size = packet_frame_size;
5743        self.stream_channels = packet_channels;
5744
5745        // Each frame of the packet goes through the same steps as libopus
5746        // `opus_decode_frame`.
5747        let frame_len = packet_frame_size * channels;
5748        for (frame, out) in parsed.frames(data).zip(output.chunks_exact_mut(frame_len)) {
5749            self.decode_or_conceal_frame(
5750                packet_mode,
5751                packet_bandwidth,
5752                frame,
5753                packet_frame_size,
5754                out,
5755                false,
5756            )?;
5757        }
5758        self.last_packet_duration = decoded_total;
5759        // C: the soft clipper runs on a decoded packet only. Concealed and
5760        // FEC output returns above, without it, and leaves its memory alone.
5761        if soft_clip {
5762            crate::soft_clip(
5763                &mut output[..decoded_total * channels],
5764                decoded_total,
5765                channels,
5766                &mut self.softclip_mem,
5767            );
5768        } else {
5769            self.softclip_mem = [0.0; OPUS_MAX_CHANNELS];
5770        }
5771        Ok((decoded_total, parsed.packet_offset()))
5772    }
5773
5774    /// One frame of a packet: decode it, or conceal it when it carries no
5775    /// data (libopus `opus_decode_frame`: "Payloads of 1 (2 including ToC)
5776    /// or 0 trigger the PLC/DTX").
5777    fn decode_or_conceal_frame(
5778        &mut self,
5779        mode: OpusMode,
5780        bandwidth: Bandwidth,
5781        payload: &[u8],
5782        frame_size: usize,
5783        out: &mut [f32],
5784        decode_fec: bool,
5785    ) -> Result<(), Error> {
5786        if payload.len() <= 1 {
5787            self.conceal(frame_size, out)
5788        } else {
5789            self.decode_frame(mode, bandwidth, payload, frame_size, out, decode_fec)
5790        }
5791    }
5792
5793    /// libopus `OPUS_GET_FINAL_RANGE`: the state of the range decoder after
5794    /// the last frame, or 0 when that frame was lost. For a packet that
5795    /// encoder and decoder read alike it equals the encoder's
5796    /// [`OpusEncoder::final_range`].
5797    ///
5798    /// After [`decode_fec`](Self::decode_fec) of a Hybrid packet the value
5799    /// is the random state of the CELT loss concealment, as in libopus: the
5800    /// CELT layer of the recovered frame is concealed, and libopus reports
5801    /// what the CELT decoder ends with.
5802    pub fn final_range(&self) -> u32 {
5803        self.range_final
5804    }
5805
5806    /// libopus `OPUS_GET_LAST_PACKET_DURATION`: the samples per channel of
5807    /// the last packet that was decoded or concealed with success, 0 before
5808    /// the first one and after [`reset_state`](Self::reset_state).
5809    ///
5810    /// A decoded packet sets it to its own duration, a concealment or an FEC
5811    /// call to the duration it was asked for. A failed call leaves it as it
5812    /// was. One exception, as in libopus: when an FEC call must conceal a
5813    /// part of the loss before the recovered frame and the recovered frame
5814    /// then fails, the value is the concealed part.
5815    ///
5816    /// After a loss, a caller can use it as the duration to conceal or to
5817    /// recover with [`decode_fec`](Self::decode_fec), as `opus_demo` does.
5818    pub fn last_packet_duration(&self) -> usize {
5819        self.last_packet_duration
5820    }
5821
5822    /// libopus `OPUS_GET_BANDWIDTH` of the decoder: the audio bandwidth of
5823    /// the last packet that was decoded, read from its first byte
5824    /// ([`packet::bandwidth`]). `None` before the first packet and after
5825    /// [`reset_state`](Self::reset_state), where libopus returns 0.
5826    ///
5827    /// Concealment of a lost packet does not change it. An FEC call
5828    /// ([`decode_fec`](Self::decode_fec)) sets it to the bandwidth of the
5829    /// packet it reads, unless that packet holds no FEC data and the call
5830    /// only conceals.
5831    pub fn bandwidth(&self) -> Option<Bandwidth> {
5832        self.bandwidth
5833    }
5834
5835    /// libopus `opus_decoder_get_nb_samples`: the duration of `packet` in
5836    /// samples per channel at this decoder's sampling rate. It is
5837    /// [`packet::nb_samples`] with [`sampling_rate`](Self::sampling_rate).
5838    ///
5839    /// Errors: [`BadArg`](crate::ErrorKind::BadArg) for an empty packet,
5840    /// and [`InvalidPacket`](crate::ErrorKind::InvalidPacket) when the
5841    /// packet is too short to say its frame count or says more than
5842    /// 120 ms.
5843    pub fn nb_samples(&self, packet: &[u8]) -> Result<usize, Error> {
5844        packet::nb_samples(packet, self.sampling_rate())
5845    }
5846
5847    /// libopus `OPUS_RESET_STATE`: forget the stream decoded so far. The
5848    /// decoder then behaves like a new one with the same sampling rate and
5849    /// channel count. The settings stay: the complexity, the bandwidth
5850    /// extension switch and the loaded neural network weights.
5851    ///
5852    /// With the neural network features there are exceptions, as in
5853    /// libopus:
5854    ///
5855    /// - With `deep-plc`, the state of FARGAN, the vocoder of deep packet
5856    ///   loss concealment, survives the reset. Concealment after a reset
5857    ///   can then differ from that of a new decoder, when deep PLC
5858    ///   concealed a loss before the reset.
5859    /// - With `osce-bwe`, the state of the bandwidth extension survives,
5860    ///   and so does the mode of the last SILK frame. After a reset in the
5861    ///   middle of a stream with the extension on, the next frame continues
5862    ///   from the old state of the extension, without starting it afresh.
5863    pub fn reset_state(&mut self) {
5864        // C opus_decoder_ctl, OPUS_RESET_STATE: clear the stream state,
5865        // reset both layers, and put back the two values that do not start
5866        // at zero. `st->DecControl` is not part of what libopus clears, so
5867        // the SILK channel count and rate of the last frame stay. They are
5868        // not used before the next SILK frame sets them again. The previous
5869        // OSCE extended mode of `DecControl` stays too; `SilkDecoder::reset`
5870        // keeps it, and it keeps the BWE state of each channel, which lies
5871        // before the part `silk_reset_decoder` clears. The complexity and
5872        // the BWE switch lie outside what libopus clears too. The neural
5873        // network models stay as well; libopus reloads PitchDNN here
5874        // (`dnn/lpcnet_enc.c:53-57`).
5875        self.celt_dec.reset_state();
5876        self.silk_dec.reset();
5877        self.mode = None;
5878        self.prev_mode = None;
5879        self.bandwidth = None;
5880        self.prev_redundancy = false;
5881        self.frame_size = self.sampling_rate as usize / 400;
5882        self.stream_channels = self.channels;
5883        self.range_final = 0;
5884        self.last_packet_duration = 0;
5885        self.softclip_mem = [0.0; OPUS_MAX_CHANNELS];
5886        // C `lpcnet_plc_reset`.
5887        #[cfg(feature = "deep-plc")]
5888        self.deep_plc.reset();
5889    }
5890
5891    /// The sampling rate of the output (`OPUS_GET_SAMPLE_RATE`).
5892    pub fn sampling_rate(&self) -> SampleRate {
5893        SampleRate::from_valid_hz(self.sampling_rate)
5894    }
5895
5896    /// libopus `OPUS_SET_COMPLEXITY` of the decoder: 0 to 10. The default is 0.
5897    /// A value outside that range is refused with
5898    /// [`BadArg`](crate::ErrorKind::BadArg) and the setting stays as it was.
5899    ///
5900    /// Since libopus 1.5 the decoder complexity turns on the neural network
5901    /// features that were compiled in: deep packet loss concealment from 5
5902    /// (cargo feature `deep-plc`), the LACE speech enhancer at 6 and NoLACE
5903    /// from 7 (feature `osce`), and from 4 the bandwidth extension, when it
5904    /// is switched on with `set_osce_bwe` (feature `osce-bwe`). Without
5905    /// these features the value is only stored, as in a libopus built
5906    /// without them.
5907    ///
5908    /// LACE and NoLACE enhance SILK frames of 20 ms at the 16 kHz SILK
5909    /// rate: wideband SILK-only frames and the SILK layer of Hybrid frames.
5910    /// A change of complexity that changes the method starts the
5911    /// enhancement afresh: the next such frame comes out unenhanced, and
5912    /// the one after it fades in over 10 ms, as in libopus.
5913    ///
5914    /// [`reset_state`](Self::reset_state) keeps the value. A value above
5915    /// 10 is refused with [`BadArg`](crate::ErrorKind::BadArg), and the
5916    /// setting stays.
5917    pub fn set_complexity(&mut self, complexity: u8) -> Result<(), Error> {
5918        if complexity > 10 {
5919            return Err(Error::INVALID_COMPLEXITY);
5920        }
5921        let complexity = i32::from(complexity);
5922        self.complexity = complexity;
5923        // C: the request is passed on to the CELT decoder, whose deep PLC
5924        // reads it.
5925        self.celt_dec.set_complexity(complexity)?;
5926        Ok(())
5927    }
5928
5929    /// The complexity set with [`set_complexity`](Self::set_complexity)
5930    /// (`OPUS_GET_COMPLEXITY`).
5931    pub fn complexity(&self) -> u8 {
5932        self.complexity as u8
5933    }
5934
5935    /// libopus `OPUS_SET_PHASE_INVERSION_DISABLED` on the decoder: with
5936    /// `true`, CELT decodes intensity stereo bands without inverting the
5937    /// sign of the second channel, even where the packet codes the
5938    /// inversion.
5939    ///
5940    /// The default depends on the channel count, as in libopus. A mono
5941    /// decoder starts with `true`: it mixes a stereo stream down, and the
5942    /// inverted channels would cancel in the mix. A stereo decoder starts
5943    /// with `false`. [`reset_state`](Self::reset_state) keeps the value.
5944    pub fn set_phase_inversion_disabled(&mut self, disabled: bool) {
5945        self.celt_dec.set_phase_inversion_disabled(disabled);
5946    }
5947
5948    /// The value of
5949    /// [`set_phase_inversion_disabled`](Self::set_phase_inversion_disabled)
5950    /// (`OPUS_GET_PHASE_INVERSION_DISABLED`).
5951    pub fn phase_inversion_disabled(&self) -> bool {
5952        self.celt_dec.phase_inversion_disabled()
5953    }
5954
5955    /// libopus `OPUS_SET_GAIN`: scales the decoded output by `gain`, in
5956    /// units of 1/256 dB (Q8 dB). The range of the type, -32768 to 32767,
5957    /// is the range of libopus: about -128 to +128 dB. The default is 0, no
5958    /// scaling.
5959    ///
5960    /// The factor is `2^(6.48814081e-4 * gain)`, which is
5961    /// `10^(gain / (20 * 256))`, computed as libopus's float build does.
5962    /// Every decoded or concealed frame is multiplied by it before the
5963    /// 16-bit conversion and its soft clipping. The decoder's own state
5964    /// does not see the gain. [`reset_state`](Self::reset_state) keeps the
5965    /// value.
5966    pub fn set_gain(&mut self, gain: i16) {
5967        self.decode_gain = i32::from(gain);
5968    }
5969
5970    /// The gain set with [`set_gain`](Self::set_gain), in 1/256 dB
5971    /// (`OPUS_GET_GAIN`).
5972    pub fn gain(&self) -> i16 {
5973        self.decode_gain as i16
5974    }
5975
5976    /// libopus `OPUS_GET_PITCH`: the pitch period of the last decoded or
5977    /// concealed frame, in samples at 48 kHz, or 0 when it had none.
5978    ///
5979    /// After a CELT-only frame it is the period of CELT's pitch
5980    /// post-filter: 0 when the frame switched the filter off, and at least
5981    /// 15 after concealment from noise. Otherwise it is the pitch lag of the
5982    /// last SILK frame, scaled to 48 kHz, or 0 when that frame was not
5983    /// voiced. [`reset_state`](Self::reset_state) keeps the SILK value, as
5984    /// in libopus, and it is what this returns until the next frame.
5985    pub fn pitch(&self) -> i32 {
5986        if self.prev_mode == Some(OpusMode::CeltOnly) {
5987            self.celt_dec.pitch()
5988        } else {
5989            self.silk_prev_pitch_lag
5990        }
5991    }
5992
5993    /// C 681-693: multiply `pcm` by the output gain, when there is one.
5994    #[allow(clippy::excessive_precision)]
5995    fn apply_gain(&self, pcm: &mut [f32]) {
5996        if self.decode_gain != 0 {
5997            // C `QCONST16(6.48814081e-4f, 25)`, with libopus's digits. In
5998            // the float build the macros are plain float products.
5999            let gain = mathops::celt_exp2(6.488_140_81e-4_f32 * self.decode_gain as f32);
6000            for x in pcm {
6001                *x *= gain;
6002            }
6003        }
6004    }
6005
6006    /// libopus `OPUS_SET_OSCE_BWE`: switches the bandwidth extension (BWE)
6007    /// of SILK wideband speech to 48 kHz on or off. The default is off.
6008    ///
6009    /// When it is on, the complexity is 4 or more and the output is
6010    /// 48 kHz, the network BBWENet makes the 48 kHz output of SILK frames
6011    /// at the 16 kHz SILK rate in place of the resampler, with the band
6012    /// above 8 kHz. It runs on SILK-only frames that arrive and on lost
6013    /// frames (also of Hybrid streams, whose CELT layer is then not
6014    /// concealed), as in libopus. Switching between it and the resampler
6015    /// fades over 10 ms. Its output is delayed by 21 samples (0.44 ms)
6016    /// against the resampler's.
6017    ///
6018    /// libopus 1.6.1 does not decode CELT-only frames that follow frames
6019    /// with BWE (it outputs silence until the next SILK frame). opus1
6020    /// decodes them, as libopus main does.
6021    ///
6022    /// The method exists only with the cargo feature `osce-bwe`. (libopus
6023    /// built without the extension answers `OPUS_UNIMPLEMENTED`.)
6024    /// [`reset_state`](Self::reset_state) keeps the switch, and so does the
6025    /// state of the extension, as in libopus.
6026    #[cfg(feature = "osce-bwe")]
6027    pub fn set_osce_bwe(&mut self, enabled: bool) {
6028        self.osce_bwe = enabled;
6029    }
6030
6031    /// The switch set with [`set_osce_bwe`](Self::set_osce_bwe)
6032    /// (`OPUS_GET_OSCE_BWE`, feature `osce-bwe`).
6033    #[cfg(feature = "osce-bwe")]
6034    pub fn osce_bwe(&self) -> bool {
6035        self.osce_bwe
6036    }
6037
6038    /// libopus `OPUS_SET_DNN_BLOB`: loads neural network weights from a
6039    /// blob in the libopus format, such as the file that libopus's
6040    /// `dump_weights_blob` writes, in place of the weights the decoder has.
6041    ///
6042    /// Every model group of this build that the blob holds completely is
6043    /// loaded: deep PLC (PitchDNN, the PLC model and FARGAN together), LACE,
6044    /// NoLACE and BBWENet. Each group is replaced only when all of its arrays
6045    /// load; the groups that the blob lacks keep the weights they had. Returns
6046    /// the groups loaded by this call, or [`BadArg`](crate::ErrorKind::BadArg)
6047    /// when the blob holds no complete group of this build, and then nothing
6048    /// changes. [`DnnBlob::builtin`] brings back the built-in weights.
6049    ///
6050    /// The decoder keeps a clone of `blob` (the bytes are not copied) for
6051    /// as long as it uses the models. A new decoder starts with the
6052    /// built-in weights of every model this build contains.
6053    /// [`reset_state`](Self::reset_state) keeps the loaded models.
6054    ///
6055    /// libopus differs: the request exists only in a libopus built with
6056    /// `USE_WEIGHTS_FILE` (and so without built-in weights), returns 1 on
6057    /// any failure, and can leave a model half loaded.
6058    ///
6059    /// The method exists only with the cargo feature `deep-plc` (which
6060    /// `osce`, `osce-bwe` and `dred` turn on): a build without a model
6061    /// could load nothing.
6062    #[cfg(feature = "deep-plc")]
6063    pub fn set_dnn_blob(&mut self, blob: &DnnBlob) -> Result<DnnModels, Error> {
6064        self.dnn.load(blob)
6065    }
6066
6067    /// The model groups the decoder has loaded (feature `deep-plc`).
6068    #[cfg(feature = "deep-plc")]
6069    pub fn dnn_models(&self) -> DnnModels {
6070        self.dnn.models()
6071    }
6072
6073    /// The number of output channels.
6074    pub fn channels(&self) -> Channels {
6075        Channels::from_valid_count(self.channels)
6076    }
6077
6078    /// Decode one frame of a packet: a port of libopus `opus_decode_frame`
6079    /// for a frame that carries data.
6080    ///
6081    /// Besides the SILK and CELT layers this handles what happens when the
6082    /// coding mode changes inside a stream:
6083    ///
6084    /// - A SILK-only or Hybrid frame can end with a 5 ms CELT frame that
6085    ///   covers the whole band (the "redundancy" frame). The encoder adds it
6086    ///   next to a switch to or from CELT-only, and the decoder cross-fades
6087    ///   it with the main frame so the switch is not audible.
6088    /// - A switch without such a frame is bridged with 5 ms of concealment
6089    ///   in the previous mode, cross-faded into the new frame.
6090    /// - A switch between SILK-only and Hybrid needs neither.
6091    ///
6092    /// With `decode_fec` the frame is not decoded itself. Its SILK layer
6093    /// yields the redundant copy it carries of the frame before it (or
6094    /// conceals, when it carries none), and the CELT layer of a Hybrid frame
6095    /// is concealed. A redundancy frame is not read.
6096    fn decode_frame(
6097        &mut self,
6098        mode: OpusMode,
6099        bandwidth: Bandwidth,
6100        payload: &[u8],
6101        frame_size: usize,
6102        out: &mut [f32],
6103        decode_fec: bool,
6104    ) -> Result<(), Error> {
6105        let channels = self.channels;
6106        let f2_5 = self.sampling_rate as usize / 400;
6107        let f5 = 2 * f2_5;
6108        let frame_len = frame_size * channels;
6109        let prev_mode = self.prev_mode;
6110        let mut len = payload.len();
6111        let mut rc = RangeCoder::new_decoder(payload);
6112
6113        // A switch to or from CELT-only needs a cross-fade, unless the
6114        // previous frame ended with a redundancy frame.
6115        let mut transition = match prev_mode {
6116            Some(prev) => {
6117                (mode == OpusMode::CeltOnly
6118                    && prev != OpusMode::CeltOnly
6119                    && !self.prev_redundancy)
6120                    || (mode != OpusMode::CeltOnly && prev == OpusMode::CeltOnly)
6121            }
6122            None => false,
6123        };
6124        // 5 ms of concealment for the cross-fade. The buffer is filled only
6125        // on a switch that needs it; every other frame leaves it untouched.
6126        let mut pcm_transition: FixedVec<f32, OPUS_PCM_TAIL> = FixedVec::new();
6127        let transition_len = f5.min(frame_size);
6128        if transition && mode == OpusMode::CeltOnly {
6129            pcm_transition.resize(f5 * channels, 0.0);
6130            // 5 ms of concealment in the previous (SILK or Hybrid) mode.
6131            self.conceal(transition_len, &mut pcm_transition[..transition_len * channels])?;
6132        }
6133
6134        // SILK layer (C opus_decoder.c:402-497).
6135        if mode != OpusMode::CeltOnly {
6136            if prev_mode == Some(OpusMode::CeltOnly) {
6137                // libopus `silk_ResetDecoder`: the SILK state is stale after
6138                // CELT-only frames. Its resamplers start afresh as well.
6139                self.silk_dec.reset();
6140            }
6141            // C 424-442: a frame that carries data says how many channels
6142            // SILK codes and at which rate. Lost frames keep both.
6143            self.silk_channels_internal = self.stream_channels;
6144            self.silk_internal_rate = if mode == OpusMode::SilkOnly {
6145                1000 * bandwidth.silk_khz()
6146            } else {
6147                16000
6148            };
6149            // C `lost_flag = 2 * decode_fec`: read the frame itself, or the
6150            // redundant copy (LBRR) of the frame before it.
6151            let lost_flag = if decode_fec {
6152                silk::decode_frame::FLAG_DECODE_LBRR
6153            } else {
6154                silk::decode_frame::FLAG_DECODE_NORMAL
6155            };
6156            self.decode_silk(&mut rc, lost_flag, frame_size, mode, out)?;
6157        }
6158
6159        // Redundancy frame: present if enough bits are left after SILK.
6160        // A Hybrid frame says so with a flag; in a SILK-only frame any such
6161        // remainder is one.
6162        let mut redundancy = false;
6163        let mut celt_to_silk = false;
6164        let mut redundancy_bytes = 0usize;
6165        // C `redundant_rng`: the final range of the redundancy frame.
6166        let mut redundant_rng = 0u32;
6167        let hybrid = mode == OpusMode::Hybrid;
6168        if !decode_fec
6169            && mode != OpusMode::CeltOnly
6170            && rc.tell() + 17 + if hybrid { 20 } else { 0 } <= 8 * len as i32
6171        {
6172            redundancy = if hybrid {
6173                rc.decode_bit_logp(12)
6174            } else {
6175                true
6176            };
6177            if redundancy {
6178                celt_to_silk = rc.decode_bit_logp(1);
6179                redundancy_bytes = if hybrid {
6180                    rc.dec_uint(256) as usize + 2
6181                } else {
6182                    len - ((rc.tell() + 7) >> 3) as usize
6183                };
6184                if redundancy_bytes > len || ((len - redundancy_bytes) * 8) < rc.tell() as usize {
6185                    // Not possible in a valid packet; ignore the frame.
6186                    len = 0;
6187                    redundancy_bytes = 0;
6188                    redundancy = false;
6189                } else {
6190                    len -= redundancy_bytes;
6191                    // The CELT layer reads its raw bits from the end of the
6192                    // main frame, not from the end of the redundancy frame.
6193                    rc.storage -= redundancy_bytes as u32;
6194                }
6195            }
6196        }
6197        let start_band = if mode != OpusMode::CeltOnly { HYBRID_START_BAND } else { 0 };
6198        if redundancy {
6199            transition = false;
6200        }
6201        if transition && mode != OpusMode::CeltOnly {
6202            pcm_transition.resize(f5 * channels, 0.0);
6203            // 5 ms of concealment in the previous (CELT-only) mode.
6204            self.conceal(transition_len, &mut pcm_transition[..transition_len * channels])?;
6205        }
6206
6207        // C 556-581, `CELT_SET_END_BAND` and `CELT_SET_CHANNELS`: the CELT
6208        // frames of this Opus frame code the bands of the packet's
6209        // bandwidth, and as many channels as the packet says. That holds
6210        // for the main frame, a redundancy frame and the fade-out frame
6211        // alike, and for the concealment of an FEC decode. The CELT decoder
6212        // converts to the output channel count. Each CELT call below sets
6213        // the first band itself (`CELT_SET_START_BAND`).
6214        self.celt_dec.set_end_band(bandwidth.celt_end_band())?;
6215        self.celt_dec.set_stream_channels(self.stream_channels)?;
6216        // The decoded redundancy frame. Filled only when the frame has one.
6217        let mut redundant_audio: FixedVec<f32, OPUS_PCM_TAIL> = FixedVec::new();
6218        if redundancy {
6219            redundant_audio.resize(f5 * channels, 0.0);
6220        }
6221
6222        // Redundancy frame for a switch from CELT-only: it continues the
6223        // CELT state of the previous frame, so it is decoded first. The
6224        // CELT decoder accepts every redundancy frame a packet can hold. A
6225        // frame it refused would leave silence.
6226        if redundancy && celt_to_silk {
6227            let mut rc_red = RangeCoder::new_decoder(&payload[len..len + redundancy_bytes]);
6228            let bits = (redundancy_bytes * 8) as i32;
6229            self.celt_dec.set_start_band(0)?;
6230            let layout = PcmLayout::Interleaved;
6231            self.celt_dec.decode(&mut rc_red, bits, f5, &mut redundant_audio, layout);
6232            redundant_rng = self.celt_dec.final_range();
6233        }
6234
6235        // The SILK layer is in `out` already. The CELT layer of a Hybrid
6236        // frame is added to it (libopus `celt_accum`).
6237        if mode != OpusMode::SilkOnly {
6238            // Discard the CELT state of another mode.
6239            if prev_mode.is_some() && prev_mode != Some(mode) && !self.prev_redundancy {
6240                self.celt_dec.reset_state();
6241            }
6242            self.celt_dec.set_start_band(start_band)?;
6243            let layout = if hybrid { PcmLayout::InterleavedAdd } else { PcmLayout::Interleaved };
6244            if decode_fec {
6245                // libopus hands CELT no data here (`decode_fec ? NULL :
6246                // data`): the redundant copy has no CELT layer, so the band
6247                // above 8 kHz is concealed on top of SILK's output.
6248                //
6249                // The band range of this packet is set above, so the
6250                // concealment covers the bands of this packet, not those of
6251                // the last CELT frame decoded. The two differ when the
6252                // bandwidth changes across the loss, or when SILK-only
6253                // packets came before it.
6254                with_deep_plc!(self, |p| {
6255                    self.celt_dec.decode_lost_with_deep_plc(frame_size, out, layout, p)
6256                })?;
6257            } else {
6258                let bits = (len * 8) as i32;
6259                // C: the main CELT call gets the deep PLC state; the
6260                // redundancy and fade-out frames do not.
6261                let decoded = with_deep_plc!(self, |p| {
6262                    self.celt_dec.decode_with_deep_plc(&mut rc, bits, frame_size, out, layout, p)
6263                });
6264                // C: `return celt_ret < 0 ? celt_ret : audiosize`. The CELT
6265                // decoder refuses a frame it cannot decode at all (a frame
6266                // size or band range that is not valid), which the packet
6267                // parser rules out.
6268                if decoded != frame_size {
6269                    return Err(Error::internal("CELT decoding failed"));
6270                }
6271            }
6272        } else if prev_mode == Some(OpusMode::Hybrid)
6273            && !(redundancy && celt_to_silk && self.prev_redundancy)
6274        {
6275            // After a Hybrid frame the CELT layer still holds half a window
6276            // of signal. Decoding 2.5 ms of CELT silence on top of the SILK
6277            // output lets it fade out.
6278            let mut rc_silence = RangeCoder::new_decoder(&[0xFF, 0xFF]);
6279            let fade = &mut out[..f2_5 * channels];
6280            self.celt_dec.set_start_band(0)?;
6281            self.celt_dec.decode(&mut rc_silence, 16, f2_5, fade, PcmLayout::InterleavedAdd);
6282        }
6283        // C 621, 636 `st->rangeFinal`: what the CELT decoder ends with when
6284        // the frame has a CELT layer, and the range decoder's state after
6285        // SILK otherwise. For a decoded CELT layer the two are the same
6286        // value. For an FEC decode of a Hybrid frame the CELT layer is
6287        // concealed, and the value is the random state of that concealment.
6288        let frame_rng = if mode != OpusMode::SilkOnly {
6289            self.celt_dec.final_range()
6290        } else {
6291            rc.rng
6292        };
6293
6294        let window = modes::default_mode().window;
6295        let inc = celt::resampling_factor(self.sampling_rate).unwrap_or(1);
6296        let f2_5_ch = f2_5 * channels;
6297
6298        // Redundancy frame for a switch to CELT-only: it starts from a
6299        // fresh CELT state and replaces the end of this frame.
6300        if redundancy && !celt_to_silk {
6301            self.celt_dec.reset_state();
6302            let mut rc_red = RangeCoder::new_decoder(&payload[len..len + redundancy_bytes]);
6303            let bits = (redundancy_bytes * 8) as i32;
6304            self.celt_dec.set_start_band(0)?;
6305            let layout = PcmLayout::Interleaved;
6306            self.celt_dec.decode(&mut rc_red, bits, f5, &mut redundant_audio, layout);
6307            redundant_rng = self.celt_dec.final_range();
6308            let tail = frame_len - f2_5_ch;
6309            // The end of the main frame fades out.
6310            let fade = &redundant_audio[f2_5_ch..];
6311            smooth_fade(fade, &mut out[tail..], false, f2_5, channels, window, inc);
6312        }
6313        // Redundancy frame for a switch from CELT-only: it supplies the
6314        // start of this frame. It is ignored if the previous frame did not
6315        // use CELT (the first frame of the switch was lost).
6316        if redundancy
6317            && celt_to_silk
6318            && (prev_mode != Some(OpusMode::SilkOnly) || self.prev_redundancy)
6319        {
6320            out[..f2_5_ch].copy_from_slice(&redundant_audio[..f2_5_ch]);
6321            // The main frame fades in.
6322            let fade = &redundant_audio[f2_5_ch..];
6323            smooth_fade(fade, &mut out[f2_5_ch..2 * f2_5_ch], true, f2_5, channels, window, inc);
6324        }
6325        if transition {
6326            if frame_size >= f5 {
6327                out[..f2_5_ch].copy_from_slice(&pcm_transition[..f2_5_ch]);
6328                let fade = &pcm_transition[f2_5_ch..];
6329                let main = &mut out[f2_5_ch..2 * f2_5_ch];
6330                smooth_fade(fade, main, true, f2_5, channels, window, inc);
6331            } else {
6332                // A 2.5 ms frame: no room for a clean cross-fade.
6333                let main = &mut out[..f2_5_ch];
6334                smooth_fade(&pcm_transition, main, true, f2_5, channels, window, inc);
6335            }
6336        }
6337
6338        // C 681-693: the output gain, on this frame's samples.
6339        self.apply_gain(&mut out[..frame_len]);
6340
6341        // The output is not clipped: libopus `opus_decode_float` does not
6342        // clip, and `decode_i16` soft-clips the whole packet.
6343
6344        // C: `if (len <= 1) st->rangeFinal = 0; else st->rangeFinal ^=
6345        // redundant_rng;`, with `len` the bytes left for the main frame.
6346        self.range_final = if len <= 1 { 0 } else { frame_rng ^ redundant_rng };
6347
6348        self.prev_mode = Some(mode);
6349        self.prev_redundancy = redundancy && !celt_to_silk;
6350        Ok(())
6351    }
6352
6353    /// Fill `output` with `total` samples per channel of concealment in the
6354    /// mode of the previous frame: what libopus `opus_decode_native` does
6355    /// for a lost packet, a loop over `opus_decode_frame` without data
6356    /// (opus_decoder.c:774-788 and 316-366). After a frame that ended with
6357    /// a redundancy frame for a switch to CELT-only, that mode is CELT-only.
6358    ///
6359    /// The loss is concealed in pieces, and the pieces are audible: every
6360    /// piece of a pitch-concealed run is quieter than the one before. The
6361    /// rules for a piece are libopus's:
6362    ///
6363    /// - One call of `opus_decode_frame` covers at most one frame of the
6364    ///   last packet (`frame_size = IMIN(frame_size, st->frame_size)`). A
6365    ///   loss after 10 ms packets is concealed 10 ms at a time.
6366    /// - A call longer than 20 ms is cut into pieces of 20 ms, and a last
6367    ///   shorter piece.
6368    /// - A piece is 2.5, 5, 10 or 20 ms: the next shorter one when what is
6369    ///   left lies between two of them. SILK-only also takes 7.5 ms.
6370    fn conceal(&mut self, total: usize, output: &mut [f32]) -> Result<(), Error> {
6371        let f2_5 = self.sampling_rate as usize / 400;
6372        let (f5, f10, f20) = (2 * f2_5, 4 * f2_5, 8 * f2_5);
6373        let channels = self.channels;
6374        // C 331: "Run PLC using last used mode (CELT if we ended with CELT
6375        // redundancy)".
6376        let plc_mode = if self.prev_redundancy {
6377            Some(OpusMode::CeltOnly)
6378        } else {
6379            self.prev_mode
6380        };
6381        let Some(plc_mode) = plc_mode else {
6382            // C 334-341: no packet yet, all there is to return is zeros. The
6383            // state stays as it is.
6384            output[..total * channels].fill(0.0);
6385            return Ok(());
6386        };
6387
6388        let mut pos = 0usize;
6389        while pos < total {
6390            // One call of `opus_decode_frame`. A frame of a packet is 60 ms
6391            // at most, which is also below the 120 ms that libopus limits a
6392            // call to.
6393            let mut left = (total - pos).min(self.frame_size);
6394            while left > 0 {
6395                // C 345-365. The inner calls of a call longer than 20 ms get
6396                // `IMIN(audiosize, F20)`.
6397                let limit = left.min(f20);
6398                let piece = if limit > f10 && limit < f20 {
6399                    f10
6400                } else if plc_mode != OpusMode::SilkOnly && limit > f5 && limit < f10 {
6401                    f5
6402                } else {
6403                    limit
6404                };
6405                let dst = &mut output[pos * channels..(pos + piece) * channels];
6406                if plc_mode == OpusMode::CeltOnly {
6407                    self.conceal_celt(piece, 0, dst, PcmLayout::Interleaved)?;
6408                } else {
6409                    // C 402-497: SILK conceals 10 or 20 ms, with the channel
6410                    // count and rate of the last frame that carried data. A
6411                    // shorter piece is the head of 10 ms.
6412                    let mut rc = RangeCoder::new_decoder(&[]);
6413                    let lost = silk::decode_frame::FLAG_PACKET_LOST;
6414                    self.decode_silk(&mut rc, lost, piece, plc_mode, dst)?;
6415                    if plc_mode == OpusMode::Hybrid && self.silk_bwe_replaces_celt() {
6416                        // C 595-627: when the bandwidth extension makes the
6417                        // whole band, CELT does not conceal. As after any
6418                        // Hybrid frame without a CELT layer, 2.5 ms of CELT
6419                        // silence are decoded on top of SILK's output, so
6420                        // that the CELT layer fades out.
6421                        self.celt_dec.set_stream_channels(self.stream_channels)?;
6422                        self.celt_dec.set_start_band(0)?;
6423                        let mut rc_silence = RangeCoder::new_decoder(&[0xFF, 0xFF]);
6424                        let fade = &mut dst[..f2_5 * channels];
6425                        self.celt_dec.decode(&mut rc_silence, 16, f2_5, fade, PcmLayout::InterleavedAdd);
6426                    } else if plc_mode == OpusMode::Hybrid {
6427                        // C 610: CELT conceals the piece itself
6428                        // (`celt_frame_size = IMIN(F20, frame_size)`), also
6429                        // when SILK had to produce 10 ms for a shorter one.
6430                        // It adds its output to SILK's.
6431                        let layout = PcmLayout::InterleavedAdd;
6432                        self.conceal_celt(piece, HYBRID_START_BAND, dst, layout)?;
6433                    }
6434                }
6435                pos += piece;
6436                left -= piece;
6437            }
6438        }
6439        // C 681-693: each call of `opus_decode_frame` applies the output
6440        // gain to what it made. One pass over the whole output does the
6441        // same. The transition audio of `decode_frame` comes from here too,
6442        // so it gets the gain twice, once here and once with its frame, as
6443        // in libopus.
6444        self.apply_gain(&mut output[..total * channels]);
6445        // C 706-712: a concealed frame has no final range and no redundancy
6446        // frame, and leaves its mode behind.
6447        self.prev_mode = Some(plc_mode);
6448        self.prev_redundancy = false;
6449        self.range_final = 0;
6450        Ok(())
6451    }
6452
6453    /// CELT concealment for `n` samples per channel into `out` (libopus
6454    /// `opus_decode_frame` with `data == NULL`, which calls
6455    /// `celt_decode_with_ec` without data).
6456    ///
6457    /// The band range starts at `start_band`: 0 for a CELT-only stream and
6458    /// `HYBRID_START_BAND` for the CELT layer of a Hybrid stream. It ends
6459    /// where the last frame with data set it.
6460    ///
6461    /// libopus sets the CELT decoder's stream channel count before every
6462    /// CELT call, this one included (`CELT_SET_CHANNELS(st->stream_channels)`,
6463    /// opus_decoder.c:581), and so does this function. The concealment
6464    /// itself works on the output channels and does not read the count.
6465    fn conceal_celt(
6466        &mut self,
6467        n: usize,
6468        start_band: usize,
6469        out: &mut [f32],
6470        layout: PcmLayout,
6471    ) -> Result<(), Error> {
6472        self.celt_dec.set_stream_channels(self.stream_channels)?;
6473        self.celt_dec.set_start_band(start_band)?;
6474        with_deep_plc!(self, |p| self.celt_dec.decode_lost_with_deep_plc(n, out, layout, p))?;
6475        Ok(())
6476    }
6477}
6478
6479impl OpusDecoder {
6480    /// The SILK layer of one Opus frame: decode, conceal or recover
6481    /// `frame_size` samples per channel into `out`, interleaved at the
6482    /// output rate with the decoder's channel count (libopus
6483    /// `opus_decode_frame`, "SILK processing", opus_decoder.c:402-497).
6484    ///
6485    /// SILK itself works in frames of 10 or 20 ms. A 40 or 60 ms Opus frame
6486    /// holds 2 or 3 of them in one range-coded stream, so `silk_Decode` is
6487    /// called until the duration is there, with the "new packet" flag in
6488    /// the first call only.
6489    ///
6490    /// The channel count and the rate SILK codes at are those of the last
6491    /// frame that carried data (`silk_channels_internal`,
6492    /// `silk_internal_rate`). `SilkDecoder::decode_with_control` resamples
6493    /// to the output rate and converts between channel counts.
6494    ///
6495    /// `lost_flag` is one of `FLAG_DECODE_NORMAL`, `FLAG_PACKET_LOST`
6496    /// (conceal) and `FLAG_DECODE_LBRR` (the redundant copy of the frame
6497    /// before, for FEC).
6498    ///
6499    /// `mode` is the mode of the frame, SILK-only or Hybrid; for a lost
6500    /// frame the mode it is concealed in. With the features `osce` and
6501    /// `osce-bwe` it selects, with the complexity and the BWE switch, the
6502    /// OSCE method and whether the bandwidth extension replaces the
6503    /// resampler (opus_decoder.c:444-466).
6504    fn decode_silk(
6505        &mut self,
6506        rc: &mut RangeCoder,
6507        lost_flag: i32,
6508        frame_size: usize,
6509        mode: OpusMode,
6510        out: &mut [f32],
6511    ) -> Result<(), Error> {
6512        // C 444-466: the OSCE method follows the complexity. The extended
6513        // mode says whether the bandwidth extension makes the output.
6514        // After CELT-only frames there is no fade between it and the
6515        // resampler, and its state starts afresh.
6516        #[cfg(feature = "osce-bwe")]
6517        let extended_mode = self.osce_extended_mode(mode, lost_flag != silk::decode_frame::FLAG_PACKET_LOST);
6518        #[cfg(feature = "osce-bwe")]
6519        if self.prev_mode == Some(OpusMode::CeltOnly) {
6520            self.silk_dec.prev_osce_extended_mode = OsceExtMode::CeltOnly;
6521        }
6522        #[cfg(feature = "osce")]
6523        let osce_args = osce_args::OsceArgs {
6524            models: dnn::osce::OsceModels::from_decoder(&self.dnn),
6525            method: dnn::osce::OsceMethod::for_complexity(self.complexity),
6526            #[cfg(feature = "osce-bwe")]
6527            extended_mode,
6528        };
6529        #[cfg(feature = "osce")]
6530        let osce = Some(&osce_args);
6531        #[cfg(not(feature = "osce"))]
6532        let osce: Option<&osce_args::OsceArgs> = None;
6533        #[cfg(not(feature = "osce-bwe"))]
6534        let _ = mode;
6535        let channels = self.channels;
6536        let f10 = self.sampling_rate as usize / 100;
6537        let control = silk::decoder_structs::SilkDecControl {
6538            n_channels_api: channels as i32,
6539            n_channels_internal: self.silk_channels_internal as i32,
6540            api_sample_rate: self.sampling_rate,
6541            internal_sample_rate: self.silk_internal_rate,
6542            // C 421-422: "The SILK PLC cannot produce frames of less than
6543            // 10 ms".
6544            payload_size_ms: (1000 * frame_size as i32 / self.sampling_rate).max(10),
6545        };
6546        // C 443: `DecControl.enable_deep_plc = complexity >= 5`, for every
6547        // SILK call.
6548        let enable_deep_plc = self.complexity >= 5;
6549        // C 409-416 and 494-496 (`pcm_too_small`): a piece shorter than
6550        // 10 ms is the head of a 10 ms frame. Only concealment asks for
6551        // such a piece; a frame with data lasts 10 ms or more. libopus
6552        // decodes the 10 ms into a buffer of its own and copies the head.
6553        // Here only the samples of the piece are converted into `out`.
6554        let room = frame_size.max(f10);
6555        let mut done = 0usize;
6556        while done < frame_size {
6557            let decoded = with_deep_plc!(self, |p| {
6558                let (silk_dec, pcm) = (
6559                    state_mut(&mut self.silk_dec),
6560                    state_mut(&mut self.w_pcm_i16),
6561                );
6562                silk_dec.decode_with_dnn(
6563                    &control,
6564                    rc,
6565                    pcm,
6566                    lost_flag,
6567                    done == 0,
6568                    p,
6569                    enable_deep_plc,
6570                    osce,
6571                )
6572            });
6573            match decoded {
6574                Ok(n) if n > 0 && done + n <= room => {
6575                    // C `silk_Decode` (dec_API.c:457-463) exports the pitch
6576                    // lag after each frame.
6577                    self.silk_prev_pitch_lag = self.silk_dec.prev_pitch_lag();
6578                    // C `INT16TORES`: SILK's 16-bit samples as floats.
6579                    let end = (done + n).min(frame_size);
6580                    let silk_out = &mut out[done * channels..end * channels];
6581                    for (o, &v) in silk_out.iter_mut().zip(self.w_pcm_i16.iter()) {
6582                        *o = int16_to_res(v);
6583                    }
6584                    done += n;
6585                }
6586                _ if lost_flag != silk::decode_frame::FLAG_DECODE_NORMAL => {
6587                    // C 480-485: "PLC failure should not be fatal". The
6588                    // rest of the frame is silence.
6589                    out[done * channels..frame_size * channels].fill(0.0);
6590                    done = frame_size;
6591                }
6592                _ => return Err(Error::internal("SILK decoding failed")),
6593            }
6594        }
6595        Ok(())
6596    }
6597}
6598
6599impl OpusDecoder {
6600    /// libopus `DecControl.osce_extended_mode` of a SILK frame
6601    /// (opus_decoder.c:452-461): `SilkBbwe` when the bandwidth extension
6602    /// makes the output, that is at complexity 4 or more with the switch
6603    /// on, 48 kHz output and SILK at 16 kHz, for a SILK-only frame or a
6604    /// frame without data (lost, or a DTX frame). Otherwise the mode of the
6605    /// frame.
6606    ///
6607    /// A decoder whose BBWENet layers are not loaded uses the resampler.
6608    /// That does not happen with the built-in weights: `set_dnn_blob`
6609    /// replaces a model only with a complete one.
6610    #[cfg(feature = "osce-bwe")]
6611    fn osce_extended_mode(&self, mode: OpusMode, has_data: bool) -> OsceExtMode {
6612        let bbwe = self.complexity >= 4
6613            && self.osce_bwe
6614            && self.sampling_rate == 48000
6615            && self.silk_internal_rate == 16000
6616            && (mode == OpusMode::SilkOnly || !has_data)
6617            && self.dnn.bbwenet().is_some();
6618        if bbwe {
6619            OsceExtMode::SilkBbwe
6620        } else if mode == OpusMode::SilkOnly {
6621            OsceExtMode::SilkOnly
6622        } else {
6623            OsceExtMode::Hybrid
6624        }
6625    }
6626
6627    /// Whether the concealment of a Hybrid frame runs in BBWE mode, where
6628    /// the bandwidth extension makes the whole band and CELT does not
6629    /// conceal (opus_decoder.c:595-627).
6630    ///
6631    /// libopus 1.6.1 also skips the CELT layer of CELT-only frames after
6632    /// BBWE frames, because the extended mode of the last SILK frame stays
6633    /// set. opus1 decodes them, as libopus main does since commit
6634    /// 228a0f85, which sets the extended mode to CELT-only for those
6635    /// frames. With that fix, a frame with data is never in BBWE mode
6636    /// unless it is SILK-only, so only this concealment checks it.
6637    fn silk_bwe_replaces_celt(&self) -> bool {
6638        #[cfg(feature = "osce-bwe")]
6639        {
6640            self.osce_extended_mode(OpusMode::Hybrid, false) == OsceExtMode::SilkBbwe
6641        }
6642        #[cfg(not(feature = "osce-bwe"))]
6643        {
6644            false
6645        }
6646    }
6647}
6648
6649/// libopus `INT16TORES` of the float build: a 16-bit sample as a float in
6650/// [-1, 1). Dividing by a power of two is exact.
6651#[inline(always)]
6652pub(crate) fn int16_to_res(x: i16) -> f32 {
6653    x as f32 * (1.0 / 32768.0)
6654}
6655
6656/// libopus `FLOAT2INT16` (float_cast.h): scale a float sample to 16 bits,
6657/// limit it to the 16-bit range and round it to the nearest integer. A
6658/// value halfway between two integers goes to the even one.
6659#[inline]
6660pub(crate) fn float2int16(x: f32) -> i16 {
6661    let x = x * 32768.0;
6662    // The comparisons are written as in C, so that a NaN gives -32768.
6663    let x = if x > -32768.0 { x } else { -32768.0 };
6664    let x = if x < 32767.0 { x } else { 32767.0 };
6665    // `x` is within the 16-bit range here, so the rounded value is too.
6666    mathops::float2int(x) as i16
6667}
6668
6669/// [`float2int24`] over a buffer, for [`OpusDecoder::decode24`]. `input`
6670/// and `output` should have the same length; the shorter one sets how
6671/// many values are converted.
6672///
6673/// On 64-bit ARM whole blocks of 4 values go through `vcvtnq_s32_f32`, the
6674/// vector form of `vcvtns_s32_f32`: the same rounding, the same limit to
6675/// the 32-bit range and 0 for a NaN. The scaling by 2^23 is the same
6676/// multiplication. So every value is the one `float2int24` gives.
6677fn res_to_int24(input: &[f32], output: &mut [i32]) {
6678    let n = input.len().min(output.len());
6679    let (input, output) = (&input[..n], &mut output[..n]);
6680    #[cfg(target_arch = "aarch64")]
6681    let blocks = n / 4 * 4;
6682    #[cfg(not(target_arch = "aarch64"))]
6683    let blocks = 0;
6684    // SAFETY: NEON is available: src/lib.rs refuses to build for aarch64
6685    // without it.
6686    #[cfg(target_arch = "aarch64")]
6687    unsafe {
6688        res_to_int24_blocks_neon(&input[..blocks], &mut output[..blocks]);
6689    }
6690    for (o, &x) in output[blocks..].iter_mut().zip(&input[blocks..]) {
6691        *o = float2int24(x);
6692    }
6693}
6694
6695/// The blocks of `res_to_int24` on 64-bit ARM, four values at a time.
6696/// Converts as many values as `input` and `output` both hold, in whole
6697/// blocks of 4.
6698#[cfg(target_arch = "aarch64")]
6699#[target_feature(enable = "neon")]
6700#[inline]
6701fn res_to_int24_blocks_neon(input: &[f32], output: &mut [i32]) {
6702    use crate::simd_mem::neon::{load_f32x4, store_i32x4};
6703    use core::arch::aarch64::{vcvtnq_s32_f32, vmulq_n_f32};
6704    for (src, dst) in input.as_chunks::<4>().0.iter().zip(output.as_chunks_mut::<4>().0) {
6705        store_i32x4(dst, vcvtnq_s32_f32(vmulq_n_f32(load_f32x4(src), 32768.0 * 256.0)));
6706    }
6707}
6708
6709/// libopus `INT24TORES` of the float build (celt/arch.h): a 24-bit sample
6710/// in a 32-bit integer as a float with full scale 1.0,
6711/// `(1.f/32768.f/256.f)*(a)`. The conversion of `a` to `f32` rounds values
6712/// beyond 2^24 to the nearest float, as in C.
6713#[inline(always)]
6714pub(crate) fn int24_to_res(x: i32) -> f32 {
6715    x as f32 * (1.0 / 8_388_608.0)
6716}
6717
6718/// libopus `RES2INT24` of the float build (celt/arch.h):
6719/// `float2int(32768.f*256.f*x)`, the sample scaled by 2^23 and rounded to
6720/// the nearest integer, halfway values to the even one. A value beyond the
6721/// 32-bit range gives the nearest 32-bit value and NaN gives 0, as
6722/// `vcvtns_s32_f32` does on 64-bit ARM; libopus on x86 gives -2^31 for
6723/// both.
6724pub(crate) fn float2int24(x: f32) -> i32 {
6725    mathops::float2int(32768.0f32 * 256.0 * x)
6726}
6727
6728/// libopus `celt_float2int16` (celt/mathops.h), as the float build of
6729/// libopus 1.6.1 compiles it for the target of this crate: the conversion
6730/// from float to 16 bits at the end of `opus_decode`.
6731///
6732/// The conversions differ only for a value halfway between two integers
6733/// after the scaling by 32768 (and for NaN).
6734///
6735/// - **64-bit ARM:** `celt_float2int16_neon` (celt/arm/celt_neon_intr.c).
6736///   libopus's build system enables the NEON (ARM vector instructions)
6737///   intrinsics by default, and every 64-bit ARM processor has them, so
6738///   this version is called directly, with or without run-time CPU
6739///   detection. It converts whole blocks of 16 values with vector
6740///   instructions: scale by 32768, round to nearest with halfway values
6741///   away from zero (`vcvtaq_s32_f32`), then limit to 16 bits
6742///   (`vqmovn_s32`). A NaN becomes 0. The values after the last whole block
6743///   go through [`float2int16`], which rounds halfway values to the even
6744///   integer (`vcvtns_s32_f32`).
6745/// - **32-bit ARM:** the same NEON function, with the rounding of ARMv7
6746///   in the blocks (see `float2int16_neon_arm32`). libopus calls it when
6747///   the processor has NEON: always when it is built for NEON (as the
6748///   Android NDK builds `armeabi-v7a` by default), and after a run-time
6749///   check otherwise. This crate assumes a processor with NEON.
6750/// - **x86 and every other target:** [`float2int16`] for each value. On
6751///   x86 it is `_mm_cvt_ss2si`, elsewhere `lrintf`; both round halfway
6752///   values to the even integer. On x86-64 this crate converts blocks of 8
6753///   values with SSE2 instead: scale, limit to the 16-bit range with
6754///   `_mm_max_ps` and `_mm_min_ps` (a NaN becomes -32768, as in C), round
6755///   with `_mm_cvtps_epi32` and narrow with `_mm_packs_epi32`. That is the
6756///   result of [`float2int16`] for every value.
6757///
6758/// `input` and `output` should have the same length; the shorter one sets
6759/// how many values are converted. libopus converts all the samples of one
6760/// `opus_decode` call at once, so the blocks start at the first sample of
6761/// the call.
6762pub(crate) fn celt_float2int16(input: &[f32], output: &mut [i16]) {
6763    let n = input.len().min(output.len());
6764    let (input, output) = (&input[..n], &mut output[..n]);
6765    #[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
6766    let blocks = n / 16 * 16;
6767    #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
6768    let blocks = n / 8 * 8;
6769    #[cfg(not(any(
6770        target_arch = "aarch64",
6771        target_arch = "arm",
6772        all(target_arch = "x86_64", target_feature = "sse2")
6773    )))]
6774    let blocks = 0;
6775    // SAFETY: NEON is available: src/lib.rs refuses to build for aarch64
6776    // without it.
6777    #[cfg(target_arch = "aarch64")]
6778    unsafe {
6779        celt_float2int16_blocks_neon(&input[..blocks], &mut output[..blocks]);
6780    }
6781    #[cfg(target_arch = "arm")]
6782    for (dst, &src) in output[..blocks].iter_mut().zip(&input[..blocks]) {
6783        *dst = float2int16_neon_arm32(src);
6784    }
6785    // SAFETY: SSE2 is part of this target (see the `cfg`).
6786    #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
6787    unsafe {
6788        celt_float2int16_blocks_sse2(&input[..blocks], &mut output[..blocks]);
6789    }
6790    for (dst, &src) in output[blocks..].iter_mut().zip(&input[blocks..]) {
6791        *dst = float2int16(src);
6792    }
6793}
6794
6795/// The blocks of `celt_float2int16` on 64-bit ARM, four values at a time:
6796/// scale by 32768, round with halfway values away from zero, limit to 16
6797/// bits. Converts as many values as `input` and `output` both hold, in
6798/// whole blocks of 4.
6799#[cfg(target_arch = "aarch64")]
6800#[target_feature(enable = "neon")]
6801#[inline]
6802fn celt_float2int16_blocks_neon(input: &[f32], output: &mut [i16]) {
6803    use crate::simd_mem::neon::{load_f32x4, store_i16x4};
6804    use core::arch::aarch64::{vcvtaq_s32_f32, vmulq_n_f32, vqmovn_s32};
6805    for (src, dst) in input.as_chunks::<4>().0.iter().zip(output.as_chunks_mut::<4>().0) {
6806        let x = vmulq_n_f32(load_f32x4(src), 32768.0);
6807        store_i16x4(dst, vqmovn_s32(vcvtaq_s32_f32(x)));
6808    }
6809}
6810
6811/// The blocks of `celt_float2int16` on x86-64, eight values at a time:
6812/// scale by 32768, limit to the 16-bit range, round, narrow. Converts as
6813/// many values as `input` and `output` both hold, in whole blocks of 8.
6814///
6815/// The values are limited to the 16-bit range before the conversion, so it
6816/// cannot overflow. It rounds as the processor's rounding mode says, to
6817/// nearest with halfway values to the even integer unless a caller changed
6818/// it, as `_mm_cvt_ss2si` in libopus.
6819#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
6820#[target_feature(enable = "sse2")]
6821#[inline]
6822fn celt_float2int16_blocks_sse2(input: &[f32], output: &mut [i16]) {
6823    use crate::simd_mem::array_at;
6824    use crate::simd_mem::x86::{load_f32x4, store_i16x8};
6825    use core::arch::x86_64::*;
6826    for (src, dst) in input.as_chunks::<8>().0.iter().zip(output.as_chunks_mut::<8>().0) {
6827        let scale = _mm_set1_ps(32768.0);
6828        let low = _mm_set1_ps(-32768.0);
6829        let high = _mm_set1_ps(32767.0);
6830        // `_mm_max_ps` returns its second operand when the first is NaN.
6831        let limit = |x: __m128| _mm_min_ps(_mm_max_ps(_mm_mul_ps(x, scale), low), high);
6832        let a = limit(load_f32x4(array_at(src, 0)));
6833        let b = limit(load_f32x4(array_at(src, 4)));
6834        let packed = _mm_packs_epi32(_mm_cvtps_epi32(a), _mm_cvtps_epi32(b));
6835        store_i16x8(dst, packed);
6836    }
6837}
6838
6839/// One value of a block of `celt_float2int16_neon` on 32-bit ARM: scale,
6840/// `vroundf` of celt/arm/mathops_arm.h for ARMv7, then `vqmovn_s32`.
6841///
6842/// ARMv7 has no instruction that rounds halfway values away from zero.
6843/// `vroundf` adds 0.5 with the sign of the value, in float arithmetic, and
6844/// truncates toward zero. Rust's `as` conversion truncates, saturates and
6845/// turns NaN into 0, as `vcvtq_s32_f32` does.
6846///
6847/// libopus built for ARMv8 in 32-bit mode uses `vcvtaq_s32_f32` instead,
6848/// as on 64-bit ARM. The two differ for one scaled value only, ยฑ0.49999997
6849/// (0.5 - 2^-25): the addition rounds it up to 1. Rust offers no stable way
6850/// to tell the two architectures apart at compile time (the 32-bit ARM
6851/// target features are unstable), so this follows ARMv7.
6852#[cfg(any(target_arch = "arm", test))]
6853#[inline]
6854fn float2int16_neon_arm32(x: f32) -> i16 {
6855    let x = x * 32768.0;
6856    let half = f32::from_bits(0x3F00_0000 | (x.to_bits() & 0x8000_0000));
6857    ((x + half) as i32).clamp(i16::MIN as i32, i16::MAX as i32) as i16
6858}
6859
6860/// libopus `opus_pcm_soft_clip` (opus.c): bring a float signal into
6861/// [-1, 1] without hard clipping.
6862///
6863/// Where the signal goes beyond ยฑ1, the stretch between the zero crossings
6864/// around that place is bent by `x + a * x * x`. `a` is chosen so that the
6865/// peak of the stretch lands on ยฑ1. Samples beyond ยฑ2 are cut to ยฑ2 first.
6866///
6867/// On 64-bit ARM two kinds of input change this, as in libopus there. The
6868/// decoder gives neither.
6869/// - A NaN (not a number) anywhere in the whole blocks of 16 samples,
6870///   counted over all channels from the start of `pcm`. These blocks are
6871///   then not cut to ยฑ2. The search for stretches beyond ยฑ1 is skipped,
6872///   unless a sample after the last whole block is beyond ยฑ1.
6873/// - A value of `declip_mem` beyond ยฑ2. The bend it carries over can take
6874///   the first samples beyond ยฑ1. When every sample was within ยฑ1 before,
6875///   the search that would bring them back is skipped.
6876///
6877/// Output samples can then lie beyond ยฑ1, and also beyond ยฑ2. On other
6878/// targets the cut and the bend work as described above. A NaN itself stays
6879/// a NaN on every target.
6880///
6881/// - `pcm`: interleaved samples of `channels` channels. The number of
6882///   samples per channel (libopus `frame_size`) is `pcm.len() / channels`.
6883/// - `declip_mem`: at least one value per channel, all 0 at the start of a
6884///   stream. It carries the bend that is under way from one call to the
6885///   next, so that consecutive buffers join without a step.
6886///
6887/// Returns [`BadArg`](crate::ErrorKind::BadArg), and leaves `pcm` and
6888/// `declip_mem` unchanged, when `channels` is 0, when `pcm.len()` is not a
6889/// multiple of `channels`, or when `declip_mem` has fewer than `channels`
6890/// values. An empty `pcm` changes nothing.
6891///
6892/// On 64-bit ARM the result has the bits of libopus 1.6.1 built by clang:
6893/// `x + a*x*x` rounds `a*x` and then adds `(a*x)*x` to `x` in one fused
6894/// multiply-add, and so does the small boost of `a` (`a + a*2.4e-7`).
6895///
6896/// ```
6897/// use opus1::pcm_soft_clip;
6898///
6899/// // Two channels, three samples each, interleaved.
6900/// let mut pcm = [0.5, -0.5, 1.5, -1.5, 0.25, -0.25];
6901/// let mut memory = [0.0; 2];
6902/// pcm_soft_clip(&mut pcm, 2, &mut memory)?;
6903/// assert!(pcm.iter().all(|x| x.abs() <= 1.0));
6904/// # Ok::<(), opus1::Error>(())
6905/// ```
6906pub fn pcm_soft_clip(pcm: &mut [f32], channels: usize, declip_mem: &mut [f32]) -> Result<(), Error> {
6907    if channels == 0 || !pcm.len().is_multiple_of(channels) || declip_mem.len() < channels {
6908        return Err(Error::BAD_ARG);
6909    }
6910    soft_clip(pcm, pcm.len() / channels, channels, declip_mem);
6911    Ok(())
6912}
6913
6914/// [`pcm_soft_clip`] on `frame_size` samples per channel at the start of
6915/// `pcm`, with the argument checks of libopus `opus_pcm_soft_clip`:
6916/// arguments that do not fit leave `pcm` unchanged.
6917fn soft_clip(pcm: &mut [f32], frame_size: usize, channels: usize, declip_mem: &mut [f32]) {
6918    let (n, nc) = (frame_size, channels);
6919    // A sample count that overflows cannot fit `pcm` either.
6920    let fits = n.checked_mul(nc).is_some_and(|len| len <= pcm.len());
6921    if nc < 1 || n < 1 || !fits || declip_mem.len() < nc {
6922        return;
6923    }
6924    // Clamp everything to [-2, 2], the domain of the non-linearity. Beyond
6925    // it the derivative is zero, so this adds no discontinuity. The check
6926    // may also tell that every sample is within [-1, 1].
6927    let all_within_neg1pos1 = limit2_checkwithin1(&mut pcm[..n * nc]);
6928    for c in 0..nc {
6929        // Channel `c`: sample `i` is `x[i * nc]`.
6930        let x = &mut pcm[c..];
6931        let mut a = declip_mem[c];
6932        // On other targets than 64-bit ARM, `all_within_neg1pos1` comes
6933        // from this crate's own check; libopus's C version always says
6934        // `false`, so the C soft clipper always searches. The search finds
6935        // nothing, and only sets the memory to 0, when no sample is beyond
6936        // ยฑ1 after the bend below. The check covers the samples the bend
6937        // leaves alone, and the bend checks the samples it changes.
6938        #[cfg(not(target_arch = "aarch64"))]
6939        let mut all_within_neg1pos1 = all_within_neg1pos1;
6940        // Continue applying the non-linearity from the previous frame to
6941        // avoid any discontinuity.
6942        // `x + a*x*x`: the libopus build on 64-bit ARM rounds `a*x` and
6943        // fuses the second product into the sum (`mac`).
6944        for i in 0..n {
6945            let v = x[i * nc];
6946            let av = a * v;
6947            if av >= 0.0 {
6948                break;
6949            }
6950            let bent = mac(v, av, v);
6951            x[i * nc] = bent;
6952            #[cfg(not(target_arch = "aarch64"))]
6953            {
6954                all_within_neg1pos1 &= !(bent > 1.0 || bent < -1.0);
6955            }
6956        }
6957
6958        let mut curr = 0usize;
6959        let x0 = x[0];
6960        loop {
6961            let mut i = curr;
6962            // The search for a sample beyond ยฑ1 is skipped when
6963            // `all_within_neg1pos1` says there is none.
6964            if all_within_neg1pos1 {
6965                i = n;
6966            } else {
6967                while i < n {
6968                    let v = x[i * nc];
6969                    if v > 1.0 || v < -1.0 {
6970                        break;
6971                    }
6972                    i += 1;
6973                }
6974            }
6975            if i == n {
6976                a = 0.0;
6977                break;
6978            }
6979            let clip = x[i * nc];
6980            let mut peak_pos = i;
6981            let (mut start, mut end) = (i, i);
6982            let mut maxval = clip.abs();
6983            // Look for first zero crossing before clipping.
6984            while start > 0 && clip * x[(start - 1) * nc] >= 0.0 {
6985                start -= 1;
6986            }
6987            // Look for first zero crossing after clipping.
6988            while end < n && clip * x[end * nc] >= 0.0 {
6989                // Look for other peaks until the next zero-crossing.
6990                let v = x[end * nc].abs();
6991                if v > maxval {
6992                    maxval = v;
6993                    peak_pos = end;
6994                }
6995                end += 1;
6996            }
6997            // Detect the special case where we clip before the first zero
6998            // crossing.
6999            let special = start == 0 && clip * x[0] >= 0.0;
7000
7001            // Compute a such that maxval + a*maxval^2 = 1.
7002            a = (maxval - 1.0) / (maxval * maxval);
7003            // Slightly boost "a" by 2^-22. libopus does this so that a
7004            // fast-math build cannot give values beyond +/-1. It is too
7005            // small to matter even for 24-bit output.
7006            a = mac(a, a, 2.4e-7);
7007            if clip > 0.0 {
7008                a = -a;
7009            }
7010            // Apply soft clipping.
7011            for k in start..end {
7012                let v = x[k * nc];
7013                x[k * nc] = mac(v, a * v, v);
7014            }
7015
7016            if special && peak_pos >= 2 {
7017                // Add a linear ramp from the first sample to the signal
7018                // peak. This avoids a discontinuity at the beginning of the
7019                // frame.
7020                let mut offset = x0 - x[0];
7021                let delta = offset / peak_pos as f32;
7022                for k in curr..peak_pos {
7023                    offset -= delta;
7024                    x[k * nc] = (x[k * nc] + offset).clamp(-1.0, 1.0);
7025                }
7026            }
7027            curr = end;
7028            if curr == n {
7029                break;
7030            }
7031        }
7032        declip_mem[c] = a;
7033    }
7034}
7035
7036/// libopus `opus_limit2_checkwithin1` (celt/mathops.h): limit every sample
7037/// to [-2, 2], and return whether every sample was within [-1, 1] already.
7038/// Then the soft clipper has nothing to search for.
7039///
7040/// libopus has two versions:
7041/// - `opus_limit2_checkwithin1_neon` (celt/arm/celt_neon_intr.c), called
7042///   when libopus is built to presume NEON, as the reference build of the
7043///   tests is. (A build with run-time CPU detection that does not presume
7044///   NEON calls it from the decoder only, and the C version from
7045///   `opus_pcm_soft_clip`.) It reads whole blocks of 16 samples first and
7046///   finds their largest and smallest value. It writes the blocks only
7047///   when one of these is beyond ยฑ2. The samples after the last whole
7048///   block are limited and checked one at a time. A NaN anywhere in the
7049///   blocks makes the largest and the smallest value NaN, because the FMAX
7050///   and FMIN instructions keep a NaN (FMAXNM and FMINNM would not). Then
7051///   none of the blocks is limited or counted as beyond ยฑ1.
7052/// - `opus_limit2_checkwithin1_c` (celt/mathops.c) on other targets. It
7053///   limits every sample and always returns `false`, so the soft clipper
7054///   always searches.
7055///
7056/// On 64-bit ARM this function is the NEON version. On other targets it
7057/// limits every sample as the C version does, and also returns whether
7058/// every sample was within [-1, 1]. A NaN counts as within, because the
7059/// search skips it too. `soft_clip` skips the search only where the C
7060/// version's search would find nothing. On x86-64 whole blocks of 4
7061/// samples go through SSE2 (Streaming SIMD Extensions 2, where SIMD means
7062/// single instruction, multiple data): the compiler does not turn the plain
7063/// loop into vector code for every x86-64 target.
7064/// On 32-bit ARM libopus can use the NEON version; this crate uses its own
7065/// version there.
7066///
7067/// The NEON version and the C version give a different soft clipper output
7068/// in two cases only, and the decoder gives neither. One is a NaN in the
7069/// whole blocks together with a sample beyond ยฑ1. The other is a value of
7070/// the soft clipper's memory beyond ยฑ2.
7071fn limit2_checkwithin1(samples: &mut [f32]) -> bool {
7072    #[cfg(target_arch = "aarch64")]
7073    let (blocks, mut exceeding1) = {
7074        let blocks = samples.len() / 16 * 16;
7075        // SAFETY: NEON is available: src/lib.rs refuses to build for
7076        // aarch64 without it.
7077        (blocks, unsafe { limit2_checkwithin1_blocks_neon(&mut samples[..blocks]) })
7078    };
7079    #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
7080    let (blocks, mut exceeding1) = {
7081        let blocks = samples.len() / 4 * 4;
7082        // SAFETY: SSE2 is part of this target (see the `cfg`).
7083        (blocks, unsafe { limit2_checkwithin1_blocks_sse2(&mut samples[..blocks]) })
7084    };
7085    #[cfg(not(any(target_arch = "aarch64", all(target_arch = "x86_64", target_feature = "sse2"))))]
7086    let (blocks, mut exceeding1) = (0, false);
7087    for v in samples[blocks..].iter_mut() {
7088        // `|`, not `||`: no branch per sample.
7089        exceeding1 |= (*v > 1.0) | (*v < -1.0);
7090        // `clamp` keeps a NaN, as `MAX16` and `MIN16` (the NEON version's
7091        // tail) and `FMAX` and `FMIN` (the C version) of celt/arch.h do.
7092        *v = v.clamp(-2.0, 2.0);
7093    }
7094    !exceeding1
7095}
7096
7097/// The whole blocks of 16 values of `limit2_checkwithin1` on 64-bit ARM, as
7098/// `opus_limit2_checkwithin1_neon` does them. Returns whether the largest
7099/// or the smallest value is beyond ยฑ1, which is `false` when a block holds
7100/// a NaN. Takes as many values as `samples` holds in whole blocks of 16.
7101#[cfg(target_arch = "aarch64")]
7102#[target_feature(enable = "neon")]
7103#[inline]
7104fn limit2_checkwithin1_blocks_neon(samples: &mut [f32]) -> bool {
7105    use crate::simd_mem::{array_at, neon::load_f32x4};
7106    use core::arch::aarch64::*;
7107    let blocks = samples.as_chunks_mut::<16>().0;
7108    let zero = vdupq_n_f32(0.0);
7109    let (mut max0, mut max1, mut min0, mut min1) = (zero, zero, zero, zero);
7110    for b in blocks.iter() {
7111        let x0 = load_f32x4(array_at(b, 0));
7112        let x1 = load_f32x4(array_at(b, 4));
7113        let x2 = load_f32x4(array_at(b, 8));
7114        let x3 = load_f32x4(array_at(b, 12));
7115        // The FMAX and FMIN instructions give a NaN when either input is a
7116        // NaN.
7117        max0 = vmaxq_f32(max0, vmaxq_f32(x0, x1));
7118        max1 = vmaxq_f32(max1, vmaxq_f32(x2, x3));
7119        min0 = vminq_f32(min0, vminq_f32(x0, x1));
7120        min1 = vminq_f32(min1, vminq_f32(x2, x3));
7121    }
7122    let max = vmaxvq_f32(vmaxq_f32(max0, max1));
7123    let min = vminvq_f32(vminq_f32(min0, min1));
7124    // Both comparisons are false when the blocks hold a NaN.
7125    if min < -2.0 || max > 2.0 {
7126        // The blocks hold no NaN here, so `clamp` gives the result of
7127        // `vminq_f32(2, vmaxq_f32(x, -2))`.
7128        for v in blocks.as_flattened_mut() {
7129            *v = v.clamp(-2.0, 2.0);
7130        }
7131    }
7132    max > 1.0 || min < -1.0
7133}
7134
7135/// The blocks of `limit2_checkwithin1` on x86-64, four values at a time:
7136/// limit each value to [-2, 2], and return whether one was beyond ยฑ1.
7137/// `_mm_max_ps(lo, x)` and `_mm_min_ps(hi, x)` return `x` when it is a NaN,
7138/// as `FMAX(lo, x)` and `FMIN(hi, x)` of celt/arch.h do; a NaN is not
7139/// beyond ยฑ1. Takes as many values as `samples` holds in whole blocks of 4.
7140#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
7141#[target_feature(enable = "sse2")]
7142#[inline]
7143fn limit2_checkwithin1_blocks_sse2(samples: &mut [f32]) -> bool {
7144    use crate::simd_mem::x86::{load_f32x4, store_f32x4};
7145    use core::arch::x86_64::*;
7146    let (lo, hi) = (_mm_set1_ps(-2.0), _mm_set1_ps(2.0));
7147    let (one, minus_one) = (_mm_set1_ps(1.0), _mm_set1_ps(-1.0));
7148    let mut exceeding = _mm_setzero_ps();
7149    for block in samples.as_chunks_mut::<4>().0 {
7150        let x = load_f32x4(block);
7151        let beyond = _mm_or_ps(_mm_cmpgt_ps(x, one), _mm_cmplt_ps(x, minus_one));
7152        exceeding = _mm_or_ps(exceeding, beyond);
7153        store_f32x4(block, _mm_min_ps(hi, _mm_max_ps(lo, x)));
7154    }
7155    _mm_movemask_ps(exceeding) != 0
7156}
7157
7158/// Whether `frame_size` samples at `fs` samples per second are a whole number
7159/// of 2.5 ms, and not 0. libopus requires this of the frame size of a lost
7160/// frame and of an FEC decode.
7161#[inline]
7162fn is_whole_2_5ms(frame_size: usize, fs: i32) -> bool {
7163    frame_size != 0 && frame_size.is_multiple_of(fs as usize / 400)
7164}
7165
7166/// The number of frames per second (rounded down) for frames of
7167/// `frame_size` samples at `sampling_rate`, or `None` when the encoder does
7168/// not take that frame size. A frame is 2.5, 5, 10, 20, 40, 60, 80, 100 or
7169/// 120 ms: the durations libopus `frame_size_select` accepts.
7170pub(crate) fn frame_rate_from_params(sampling_rate: i32, frame_size: usize) -> Option<i32> {
7171    // A size that does not fit an `i32` is no frame size. Cutting it to 32
7172    // bits could turn it into one. No valid frame is longer than a second,
7173    // and checking this first keeps the products below in range.
7174    let frame_size = i32::try_from(frame_size).ok()?;
7175    if frame_size <= 0 || frame_size > sampling_rate {
7176        return None;
7177    }
7178    // The check goes by duration, as in libopus, not by
7179    // `sampling_rate % frame_size == 0`: 60 ms is 16.67 frames per second.
7180    let (fs, n) = (sampling_rate, frame_size);
7181    let valid = 400 * n == fs
7182        || 200 * n == fs
7183        || 100 * n == fs
7184        || 50 * n == fs
7185        || 25 * n == fs
7186        || 50 * n == 3 * fs
7187        || 50 * n == 4 * fs
7188        || 50 * n == 5 * fs
7189        || 50 * n == 6 * fs;
7190    if !valid {
7191        return None;
7192    }
7193    Some(fs / frame_size)
7194}
7195
7196/// libopus `frame_size_select` (opus_encoder.c:827): the frame an encode
7197/// call codes, in samples per channel, or `None` when the call is refused.
7198///
7199/// - `frame_size` is what the caller passed (C `analysis_frame_size`).
7200/// - With [`FrameDuration::Argument`] the frame is `frame_size`.
7201/// - With any other duration the frame has that duration. The caller must
7202///   pass at least that much.
7203///
7204/// The frame must then be one of the durations Opus has (see
7205/// [`frame_rate_from_params`]). The `RestrictedSilk` application also
7206/// refuses frames under 10 ms: SILK frames are 10 ms or longer.
7207pub(crate) fn frame_size_select(
7208    application: Application,
7209    frame_size: usize,
7210    duration: FrameDuration,
7211    sampling_rate: i32,
7212) -> Option<usize> {
7213    if frame_size < sampling_rate as usize / 400 {
7214        return None;
7215    }
7216    let new_size = duration.samples(SampleRate::from_valid_hz(sampling_rate)).unwrap_or(frame_size);
7217    if new_size > frame_size {
7218        return None;
7219    }
7220    frame_rate_from_params(sampling_rate, new_size)?;
7221    if application == Application::RestrictedSilk && new_size < sampling_rate as usize / 100 {
7222        return None;
7223    }
7224    Some(new_size)
7225}
7226
7227/// The bandwidth the TOC byte of a frame names (C `curr_bandwidth`): the
7228/// bandwidth decided for the packet, except in SILK-only frames. A
7229/// SILK-only frame names the bandwidth of the rate SILK coded it at
7230/// (`silk_fs_khz`, opus_encoder.c:2223-2232): SILK does not follow every
7231/// bandwidth request at once, and a TOC that names another rate makes the
7232/// decoder read the frame wrongly.
7233fn toc_bandwidth(mode: OpusMode, silk_fs_khz: i32, bandwidth: Bandwidth) -> Bandwidth {
7234    match (mode, silk_fs_khz) {
7235        (OpusMode::SilkOnly, 8) => Bandwidth::Narrowband,
7236        (OpusMode::SilkOnly, 12) => Bandwidth::Mediumband,
7237        (OpusMode::SilkOnly, _) => Bandwidth::Wideband,
7238        _ => bandwidth,
7239    }
7240}
7241
7242fn gen_toc(mode: OpusMode, frame_rate: i32, bandwidth: Bandwidth, channels: usize) -> u8 {
7243    let mut rate = frame_rate;
7244    let mut period = 0;
7245    while rate < 400 {
7246        rate <<= 1;
7247        period += 1;
7248    }
7249
7250    let mut toc = match mode {
7251        OpusMode::SilkOnly => {
7252            let bw = (bandwidth as i32 - Bandwidth::Narrowband as i32) << 5;
7253            let per = (period - 2) << 3;
7254            (bw | per) as u8
7255        }
7256        OpusMode::CeltOnly => {
7257            let mut tmp = bandwidth as i32 - Bandwidth::Mediumband as i32;
7258            if tmp < 0 {
7259                tmp = 0;
7260            }
7261            let per = period << 3;
7262            (0x80 | (tmp << 5) | per) as u8
7263        }
7264        OpusMode::Hybrid => {
7265            let base_config = if bandwidth == Bandwidth::Superwideband {
7266                12
7267            } else {
7268                14
7269            };
7270            let period_offset = if frame_rate >= 100 { 0 } else { 1 };
7271            ((base_config + period_offset) << 3) as u8
7272        }
7273    };
7274
7275    if channels == 2 {
7276        toc |= 0x04;
7277    }
7278    toc
7279}
7280
7281fn mode_from_toc(toc: u8) -> OpusMode {
7282    if toc & 0x80 != 0 {
7283        OpusMode::CeltOnly
7284    } else if toc & 0x60 == 0x60 {
7285        OpusMode::Hybrid
7286    } else {
7287        OpusMode::SilkOnly
7288    }
7289}
7290
7291#[cfg(all(test, feature = "std"))]
7292fn frame_duration_ms_from_toc(toc: u8) -> i32 {
7293    let mode = mode_from_toc(toc);
7294    match mode {
7295        OpusMode::SilkOnly => {
7296            let config = (toc >> 3) & 0x03;
7297            match config {
7298                0 => 10,
7299                1 => 20,
7300                2 => 40,
7301                3 => 60,
7302                _ => 20,
7303            }
7304        }
7305        OpusMode::Hybrid => {
7306            let config = (toc >> 3) & 0x01;
7307            if config == 0 { 10 } else { 20 }
7308        }
7309        OpusMode::CeltOnly => {
7310            let config = (toc >> 3) & 0x03;
7311            match config {
7312                0 => 2,
7313                1 => 5,
7314                2 => 10,
7315                3 => 20,
7316                _ => 20,
7317            }
7318        }
7319    }
7320}
7321
7322/// Cross-fade `overlap` interleaved samples per channel between `out` and
7323/// `other`, in place (libopus `smooth_fade`, with `out` the same buffer as
7324/// one of its inputs). The weight of the signal that fades in rises from 0
7325/// to 1 as the square of the CELT window. `window` is the 120-sample CELT
7326/// window at 48 kHz, and `inc` = 48000 / Fs strides it.
7327///
7328/// With `out_fades_in`, `other` fades out and `out` fades in. Otherwise
7329/// `out` fades out and `other` fades in.
7330///
7331/// libopus computes `w*in2 + (1-w)*in1`. On 64-bit ARM, clang rounds
7332/// `(1-w)*in1` first and adds `w*in2` to it in one fused multiply-add
7333/// (`fmul`, then `fmadd`, in the Homebrew build of 1.6.1). [`mac`] does the
7334/// same.
7335fn smooth_fade(
7336    other: &[f32],
7337    out: &mut [f32],
7338    out_fades_in: bool,
7339    overlap: usize,
7340    channels: usize,
7341    window: &[f32],
7342    inc: usize,
7343) {
7344    for (i, &win) in window.iter().step_by(inc).take(overlap).enumerate() {
7345        let w = win * win;
7346        for c in 0..channels {
7347            let k = i * channels + c;
7348            let (in1, in2) = if out_fades_in { (other[k], out[k]) } else { (out[k], other[k]) };
7349            // C `ADD32(MULT_COEF_32(w,in2), MULT_COEF_32(COEF_ONE-w, in1))`:
7350            // clang on 64-bit ARM rounds `(1 - w) * in1` and fuses `w * in2`
7351            // into the sum, as in `stereo_fade`.
7352            out[k] = mac((1.0 - w) * in1, w, in2);
7353        }
7354    }
7355}
7356
7357#[cfg(all(test, feature = "std"))]
7358mod tests {
7359    use super::*;
7360    use crate::packet::{Framing, Padding};
7361
7362    /// The `Debug` output of the codecs shows their settings and none of
7363    /// their buffers, so it stays short.
7364    #[test]
7365    fn debug_shows_the_settings_only() {
7366        let mut enc = OpusEncoder::new(SampleRate::Hz48000, Channels::Stereo, Application::Audio).unwrap();
7367        enc.set_force_mode(Some(ForcedMode::CeltOnly));
7368        let text = format!("{enc:?}");
7369        assert!(text.starts_with("OpusEncoder { sampling_rate: Hz48000, channels: Stereo, application: Audio, bitrate_setting: Auto, complexity: 9,"), "{text}");
7370        assert!(text.contains("force_mode: Some(CeltOnly)") && text.ends_with(", .. }"), "{text}");
7371        assert!(text.len() < 600, "{text}");
7372
7373        let dec = OpusDecoder::new(SampleRate::Hz16000, Channels::Mono).unwrap();
7374        let text = format!("{dec:?}");
7375        assert!(text.starts_with("OpusDecoder { sampling_rate: Hz16000, channels: Mono, complexity: 0, gain: 0, phase_inversion_disabled: true"), "{text}");
7376        assert!(text.len() < 200, "{text}");
7377
7378        let packet = [0xfc, 1, 2, 3];
7379        let mut rp = packet::Repacketizer::new();
7380        rp.cat(&packet).unwrap();
7381        assert_eq!(format!("{rp:?}"), "Repacketizer { toc: 252, nb_frames: 1, .. }");
7382
7383        let ms = multistream::MultistreamEncoder::new(SampleRate::Hz48000, 2, 1, 1, &[0, 1], Application::Voip).unwrap();
7384        let text = format!("{ms:?}");
7385        assert!(text.starts_with("MultistreamEncoder { sampling_rate: Hz48000, layout: "), "{text}");
7386        assert!(text.contains("application: Voip") && text.len() < 600, "{text}");
7387        let ms = multistream::MultistreamDecoder::new(SampleRate::Hz24000, 2, 2, 0, &[0, 1]).unwrap();
7388        let text = format!("{ms:?}");
7389        assert!(text.starts_with("MultistreamDecoder { sampling_rate: Hz24000, layout: "), "{text}");
7390        assert!(text.len() < 400, "{text}");
7391
7392        #[cfg(feature = "dred")]
7393        {
7394            assert_eq!(
7395                format!("{:?}", OpusDred::new()),
7396                "OpusDred { parsed: false, processed: false, nb_latents: 0, dred_offset: 0, .. }"
7397            );
7398            assert_eq!(format!("{:?}", OpusDredDecoder::new()), "OpusDredDecoder { loaded: true, .. }");
7399        }
7400    }
7401
7402    /// The getters of the settings that have no libopus request return
7403    /// what was set; the bandwidth getters follow libopus
7404    /// (`core_controls_libopus.rs` compares them).
7405    #[test]
7406    fn the_new_getters_return_what_was_set() {
7407        let mut enc = OpusEncoder::new(SampleRate::Hz24000, Channels::Mono, Application::Voip).unwrap();
7408        assert_eq!(enc.force_mode(), None);
7409        for mode in [ForcedMode::SilkOnly, ForcedMode::Hybrid, ForcedMode::CeltOnly] {
7410            enc.set_force_mode(Some(mode));
7411            assert_eq!(enc.force_mode(), Some(mode));
7412        }
7413        enc.set_force_mode(None);
7414        assert_eq!(enc.force_mode(), None);
7415        assert_eq!(enc.max_bandwidth(), Bandwidth::Fullband);
7416        enc.set_max_bandwidth(Bandwidth::Wideband);
7417        assert_eq!(enc.max_bandwidth(), Bandwidth::Wideband);
7418        // libopus starts with fullband, whatever the rate.
7419        assert_eq!(enc.bandwidth(), Bandwidth::Fullband);
7420        let mut packet = [0u8; 1275];
7421        enc.encode(&[0.1f32; 480], 480, &mut packet).unwrap();
7422        assert!(matches!(enc.bandwidth(), Bandwidth::Narrowband | Bandwidth::Mediumband | Bandwidth::Wideband));
7423
7424        let mut dec = OpusDecoder::new(SampleRate::Hz24000, Channels::Mono).unwrap();
7425        assert_eq!(dec.bandwidth(), None);
7426        assert_eq!(dec.nb_samples(&packet), Ok(480));
7427        let mut pcm = [0.0f32; 480];
7428        dec.decode(&packet, 480, &mut pcm).unwrap();
7429        assert_eq!(dec.bandwidth(), Some(packet::bandwidth(packet[0])));
7430        dec.decode(&[], 480, &mut pcm).unwrap();
7431        assert_eq!(dec.bandwidth(), Some(packet::bandwidth(packet[0])), "a loss keeps it");
7432        dec.reset_state();
7433        assert_eq!(dec.bandwidth(), None);
7434    }
7435
7436    #[test]
7437    fn sample_rates_convert_to_and_from_numbers() {
7438        let hz = [8000, 12000, 16000, 24000, 48000];
7439        assert!(SampleRate::ALL.iter().map(|rate| rate.hz()).eq(hz));
7440        for &rate in SampleRate::ALL {
7441            assert_eq!(SampleRate::try_from(rate.hz()), Ok(rate));
7442            assert_eq!(SampleRate::try_from(rate.hz() as i32), Ok(rate));
7443            assert_eq!(u32::from(rate), rate.hz());
7444            assert_eq!(SampleRate::from_valid_hz(rate.hz() as i32), rate);
7445            // 120 ms, the room the decoder of libopus may need.
7446            assert_eq!(rate.max_frame_size(), packet::max_packet_samples(rate.hz() as i32));
7447            assert_eq!(rate.max_frame_size(), rate.hz() as usize * 120 / 1000);
7448        }
7449        assert!(SampleRate::ALL.windows(2).all(|w| w[0] < w[1]));
7450        for hz in [0, 1, 4000, 11025, 22050, 32000, 44100, 96000, u32::MAX] {
7451            let err = SampleRate::try_from(hz).unwrap_err();
7452            assert_eq!((err.kind(), err.message()), (ErrorKind::BadArg, "invalid sampling rate"));
7453        }
7454        for hz in [-1, -48000, i32::MIN, i32::MAX] {
7455            assert_eq!(SampleRate::try_from(hz), Err(Error::INVALID_SAMPLING_RATE));
7456        }
7457    }
7458
7459    #[test]
7460    fn channels_convert_to_and_from_numbers() {
7461        assert_eq!(Channels::ALL.map(Channels::count), [1, 2]);
7462        for channels in Channels::ALL {
7463            assert_eq!(Channels::try_from(channels.count()), Ok(channels));
7464            assert_eq!(usize::from(channels), channels.count());
7465            assert_eq!(Channels::from_valid_count(channels.count()), channels);
7466        }
7467        for count in [0, 3, 8, 255, usize::MAX] {
7468            let err = Channels::try_from(count).unwrap_err();
7469            assert_eq!((err.kind(), err.message()), (ErrorKind::BadArg, "invalid number of channels"));
7470        }
7471    }
7472
7473    #[test]
7474    fn codecs_report_their_rate_and_channels() {
7475        for &rate in SampleRate::ALL {
7476            for channels in Channels::ALL {
7477                let enc = OpusEncoder::new(rate, channels, Application::Audio).unwrap();
7478                assert_eq!((enc.sampling_rate(), enc.channels()), (rate, channels));
7479                let dec = OpusDecoder::new(rate, channels).unwrap();
7480                assert_eq!((dec.sampling_rate(), dec.channels()), (rate, channels));
7481            }
7482        }
7483    }
7484
7485    #[test]
7486    fn forced_channels_are_kept_on_a_mono_encoder() {
7487        let mut enc =
7488            OpusEncoder::new(SampleRate::Hz48000, Channels::Mono, Application::Audio).unwrap();
7489        assert_eq!(enc.force_channels(), None);
7490        enc.set_force_channels(Some(Channels::Stereo));
7491        assert_eq!(enc.force_channels(), Some(Channels::Stereo));
7492        // A mono encoder codes mono whatever is set: the packets are those
7493        // of an encoder without the setting.
7494        let mut plain =
7495            OpusEncoder::new(SampleRate::Hz48000, Channels::Mono, Application::Audio).unwrap();
7496        let (mut out, mut plain_out) = ([0u8; 1500], [0u8; 1500]);
7497        for k in 0..10 {
7498            let pcm: Vec<f32> = (0..960).map(|i| (0.01 * (k * 960 + i) as f32).sin() * 0.3).collect();
7499            let len = enc.encode(&pcm, 960, &mut out).unwrap();
7500            let plain_len = plain.encode(&pcm, 960, &mut plain_out).unwrap();
7501            assert_eq!(out[..len], plain_out[..plain_len], "packet {k}");
7502            assert_eq!(packet::nb_channels(out[0]), Channels::Mono);
7503        }
7504        enc.set_force_channels(None);
7505        assert_eq!(enc.force_channels(), None);
7506    }
7507
7508    fn frame_size_from_toc(toc: u8, sampling_rate: i32) -> Option<usize> {
7509        let mode = mode_from_toc(toc);
7510        match mode {
7511            OpusMode::CeltOnly => {
7512                let period = ((toc >> 3) & 0x03) as i32;
7513                let frame_rate = 400 >> period;
7514                if frame_rate == 0 || sampling_rate % frame_rate != 0 {
7515                    return None;
7516                }
7517                Some((sampling_rate / frame_rate) as usize)
7518            }
7519            OpusMode::SilkOnly => {
7520                let duration_ms = frame_duration_ms_from_toc(toc);
7521                Some((sampling_rate as i64 * duration_ms as i64 / 1000) as usize)
7522            }
7523            OpusMode::Hybrid => {
7524                let duration_ms = frame_duration_ms_from_toc(toc);
7525                Some((sampling_rate as i64 * duration_ms as i64 / 1000) as usize)
7526            }
7527        }
7528    }
7529
7530    #[test]
7531    fn gen_toc_matches_celt_reference_values() {
7532        let sampling_rate = 48_000;
7533        let cases = [
7534            (120usize, 0xE0u8),
7535            (240usize, 0xE8u8),
7536            (480usize, 0xF0u8),
7537            (960usize, 0xF8u8),
7538        ];
7539
7540        for (frame_size, expected_toc) in cases {
7541            let frame_rate = frame_rate_from_params(sampling_rate, frame_size).unwrap();
7542            let toc = gen_toc(OpusMode::CeltOnly, frame_rate, Bandwidth::Fullband, 1);
7543            assert_eq!(
7544                toc, expected_toc,
7545                "frame_size {} expected TOC {:02X} got {:02X}",
7546                frame_size, expected_toc, toc
7547            );
7548            let decoded_size = frame_size_from_toc(toc, sampling_rate).unwrap();
7549            assert_eq!(decoded_size, frame_size);
7550        }
7551
7552        let stereo_toc = gen_toc(
7553            OpusMode::CeltOnly,
7554            frame_rate_from_params(sampling_rate, 960).unwrap(),
7555            Bandwidth::Fullband,
7556            2,
7557        );
7558        assert_eq!(packet::nb_channels(stereo_toc), Channels::Stereo);
7559    }
7560
7561    #[test]
7562    fn test_celt_decoder_large_frame_sizes() {
7563        let sampling_rate = 48000;
7564        let channels = 1;
7565
7566        let mut decoder =
7567            OpusDecoder::new(sampling_rate.try_into().unwrap(), channels.try_into().unwrap()).unwrap();
7568
7569        let frame_sizes = [120, 240, 480, 960];
7570
7571        for frame_size in frame_sizes {
7572            let toc = gen_toc(
7573                OpusMode::CeltOnly,
7574                frame_rate_from_params(sampling_rate, frame_size).unwrap(),
7575                Bandwidth::Fullband,
7576                channels,
7577            );
7578            let packet = [toc, 0, 0, 0, 0];
7579
7580            let mut output = vec![0.0f32; frame_size * channels];
7581
7582            let _ = decoder.decode(&packet, frame_size, &mut output);
7583        }
7584
7585        let channels = 2;
7586        let mut decoder =
7587            OpusDecoder::new(sampling_rate.try_into().unwrap(), channels.try_into().unwrap()).unwrap();
7588
7589        for frame_size in frame_sizes {
7590            let toc = gen_toc(
7591                OpusMode::CeltOnly,
7592                frame_rate_from_params(sampling_rate, frame_size).unwrap(),
7593                Bandwidth::Fullband,
7594                channels,
7595            );
7596            let packet = [toc, 0, 0, 0, 0];
7597
7598            let mut output = vec![0.0f32; frame_size * channels];
7599            let _ = decoder.decode(&packet, frame_size, &mut output);
7600        }
7601    }
7602
7603    #[test]
7604    fn test_celt_decoder_edge_case_frame_sizes() {
7605        let channels = 1;
7606        let mut decoder = OpusDecoder::new(SampleRate::Hz48000, Channels::Mono).unwrap();
7607
7608        let edge_sizes = [2048, 2167, 2168, 2169, 2880, 3072];
7609
7610        for frame_size in edge_sizes {
7611            let mut output = vec![0.0f32; frame_size * channels];
7612
7613            let _ = decoder.decode(&[0x80, 0, 0, 0], frame_size, &mut output);
7614        }
7615    }
7616
7617    // Regression test for: "index out of bounds: the len is 48 but the index is 119"
7618    // Root cause: frame_size=48 at 48kHz gives frame_rate=1000, which is not a valid
7619    // Hybrid-mode frame rate but was not validated.  CELT's lm-search then silently
7620    // fell back to lm=0, computed n2=120, and wrote output[119] into a 48-element
7621    // slice.  Triggered via G.729-decoded PCM (8kHz) passed to a 48kHz Opus encoder
7622    // without proper resampling, so the encoder received 48 samples instead of 480.
7623    #[test]
7624    fn test_invalid_small_frame_size_returns_error_not_panic() {
7625        let mut enc =
7626            OpusEncoder::new(SampleRate::Hz48000, Channels::Stereo, Application::Voip).unwrap();
7627        enc.set_bitrate(Bitrate::BitsPerSecond(NonZeroU32::new(64000).unwrap()));
7628        enc.set_complexity(5).unwrap();
7629        enc.set_vbr(false);
7630
7631        // 48 samples at 48kHz = 1ms โ†’ frame_rate=1000, invalid for Hybrid mode.
7632        let input = vec![0.0f32; 48 * 2]; // stereo interleaved
7633        let mut output = vec![0u8; 256];
7634
7635        let result = enc.encode(&input, 48, &mut output);
7636        assert!(
7637            result.is_err(),
7638            "encode with invalid frame_size=48 should return Err, not panic"
7639        );
7640    }
7641
7642    /// libopus `FLOAT2INT16`: scale, limit to 16 bits, round to nearest
7643    /// with halfway cases to the even integer.
7644    #[test]
7645    fn float2int16_rounds_and_saturates() {
7646        let lsb = 1.0 / 32768.0;
7647        assert_eq!(float2int16(0.0), 0);
7648        assert_eq!(float2int16(100.4 * lsb), 100);
7649        assert_eq!(float2int16(100.6 * lsb), 101);
7650        assert_eq!(float2int16(-100.6 * lsb), -101);
7651        // Halfway cases go to the even neighbour.
7652        assert_eq!(float2int16(0.5 * lsb), 0);
7653        assert_eq!(float2int16(1.5 * lsb), 2);
7654        assert_eq!(float2int16(2.5 * lsb), 2);
7655        assert_eq!(float2int16(-0.5 * lsb), 0);
7656        assert_eq!(float2int16(-1.5 * lsb), -2);
7657        // The 16-bit range is not symmetric.
7658        assert_eq!(float2int16(1.0), 32767);
7659        assert_eq!(float2int16(32767.4 * lsb), 32767);
7660        assert_eq!(float2int16(-1.0), -32768);
7661        assert_eq!(float2int16(7.0), 32767);
7662        assert_eq!(float2int16(-7.0), -32768);
7663        assert_eq!(float2int16(f32::INFINITY), 32767);
7664        assert_eq!(float2int16(f32::NEG_INFINITY), -32768);
7665        assert_eq!(float2int16(f32::NAN), -32768);
7666    }
7667
7668    /// libopus `celt_float2int16`: on ARM, halfway values in whole blocks of
7669    /// 16 go away from zero, the values after the last block to the even
7670    /// integer. Elsewhere every halfway value goes to the even integer.
7671    #[test]
7672    fn celt_float2int16_rounds_blocks_as_libopus() {
7673        let lsb = 1.0 / 32768.0;
7674        // 35 values: two blocks of 16, then 3 more. Every value is halfway
7675        // between two integers.
7676        let input: Vec<f32> = (0..35).map(|i| (i as f32 - 17.0 + 0.5) * lsb).collect();
7677        let mut output = vec![0i16; 35];
7678        celt_float2int16(&input, &mut output);
7679        let arm = cfg!(any(target_arch = "aarch64", target_arch = "arm"));
7680        for (i, (&x, &y)) in input.iter().zip(&output).enumerate() {
7681            let v = x * 32768.0;
7682            let expected = if arm && i < 32 { v.round() } else { v.round_ties_even() };
7683            assert_eq!(y, expected as i16, "value {i}: {v}");
7684        }
7685        // The limits, infinities and NaN, in a block and after it.
7686        let mut input = vec![0f32; 17];
7687        input[..5].copy_from_slice(&[1.0, -1.0, 7.0, f32::NEG_INFINITY, f32::NAN]);
7688        input[12..].copy_from_slice(&[32767.5 * lsb, -32768.5 * lsb, f32::INFINITY, -7.0, f32::NAN]);
7689        let mut output = vec![1i16; 17];
7690        celt_float2int16(&input, &mut output);
7691        assert_eq!(output[..5], [32767, -32768, 32767, -32768, if arm { 0 } else { -32768 }]);
7692        assert_eq!(output[12..], [32767, -32768, 32767, -32768, -32768]);
7693        // Only the shorter of the two slices is converted.
7694        let mut output = [5i16; 3];
7695        celt_float2int16(&[0.5 * lsb, 1.5 * lsb], &mut output);
7696        assert_eq!(output, [0, 2, 5]);
7697    }
7698
7699    /// On x86-64 the SSE2 blocks of `celt_float2int16` give the result of
7700    /// `float2int16` for every value: random values, halfway values, the
7701    /// limits, values beyond them, infinities, NaN and the special zeros, at
7702    /// every position of a block and with every tail length.
7703    #[test]
7704    fn celt_float2int16_blocks_match_float2int16_off_arm() {
7705        if cfg!(any(target_arch = "aarch64", target_arch = "arm")) {
7706            return;
7707        }
7708        let lsb = 1.0 / 32768.0;
7709        let special = [
7710            0.0f32,
7711            -0.0,
7712            0.5 * lsb,
7713            -0.5 * lsb,
7714            1.5 * lsb,
7715            -2.5 * lsb,
7716            32766.5 * lsb,
7717            32767.5 * lsb,
7718            -32767.5 * lsb,
7719            -32768.5 * lsb,
7720            1.0,
7721            -1.0,
7722            1e30,
7723            -1e30,
7724            f32::INFINITY,
7725            f32::NEG_INFINITY,
7726            f32::NAN,
7727            -f32::NAN,
7728            f32::MIN_POSITIVE,
7729            1e-40,
7730        ];
7731        let mut seed = 0x0f12_1600u32;
7732        let mut values: Vec<f32> = Vec::new();
7733        for i in 0..400 {
7734            seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
7735            values.push(if i % 3 == 0 {
7736                special[(seed >> 8) as usize % special.len()]
7737            } else {
7738                ((seed >> 8) as f32 / 8_388_608.0 - 1.0) * 1.2
7739            });
7740        }
7741        for n in (0..=33).chain([399, 400]) {
7742            let mut output = vec![0x5555i16; n + 2];
7743            celt_float2int16(&values[..n], &mut output);
7744            for (i, &x) in values[..n].iter().enumerate() {
7745                assert_eq!(output[i], float2int16(x), "n {n} value {i}: {x:e}");
7746            }
7747            assert_eq!(output[n..], [0x5555; 2], "n {n}: wrote past the input");
7748        }
7749    }
7750
7751    /// `celt_float2int16` against the function that libopus's
7752    /// `celt_float2int16` runs on this processor, from the libopus these
7753    /// tests link (exported by the static library): `celt_float2int16_neon`
7754    /// (celt/arm/celt_neon_intr.c) on aarch64, where it always replaces the
7755    /// C function, and `celt_float2int16_c` (celt/mathops.c) on x86-64. The
7756    /// values: random ones, halfway values, the limits, values beyond them,
7757    /// infinities, NaN and the special zeros, with every tail length.
7758    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
7759    #[test]
7760    fn celt_float2int16_matches_libopus() {
7761        use audiopus_sys as _;
7762        unsafe extern "C" {
7763            /// `void celt_float2int16_neon(const float *in, short *out,
7764            /// int cnt)` on aarch64, `celt_float2int16_c` with the same
7765            /// arguments elsewhere.
7766            #[cfg_attr(target_arch = "aarch64", link_name = "celt_float2int16_neon")]
7767            #[cfg_attr(not(target_arch = "aarch64"), link_name = "celt_float2int16_c")]
7768            fn c_celt_float2int16(input: *const f32, output: *mut i16, cnt: i32);
7769        }
7770        let lsb = 1.0 / 32768.0;
7771        let special = [
7772            0.0f32,
7773            -0.0,
7774            0.5 * lsb,
7775            -0.5 * lsb,
7776            1.5 * lsb,
7777            -2.5 * lsb,
7778            32766.5 * lsb,
7779            32767.5 * lsb,
7780            -32767.5 * lsb,
7781            -32768.5 * lsb,
7782            1.0,
7783            -1.0,
7784            1e30,
7785            -1e30,
7786            f32::INFINITY,
7787            f32::NEG_INFINITY,
7788            f32::NAN,
7789            -f32::NAN,
7790            f32::MIN_POSITIVE,
7791            1e-40,
7792        ];
7793        let mut seed = 0x0f12_1601u32;
7794        let mut values: Vec<f32> = Vec::new();
7795        for i in 0..1000 {
7796            seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
7797            values.push(if i % 4 == 0 {
7798                special[(seed >> 8) as usize % special.len()]
7799            } else {
7800                ((seed >> 8) as f32 / 8_388_608.0 - 1.0) * 1.2
7801            });
7802        }
7803        for n in (0..=40).chain([999, 1000]) {
7804            let mut want = vec![0x5555i16; n];
7805            // SAFETY: `values` holds at least `n` values and `want` `n`.
7806            unsafe { c_celt_float2int16(values.as_ptr(), want.as_mut_ptr(), n as i32) };
7807            let mut got = vec![0x5555i16; n];
7808            celt_float2int16(&values[..n], &mut got);
7809            assert_eq!(got, want, "n {n}");
7810        }
7811    }
7812
7813    /// The ARMv7 rounding of `celt_float2int16_neon`: add 0.5 with the sign
7814    /// of the value, then truncate.
7815    #[test]
7816    fn float2int16_neon_arm32_adds_half_and_truncates() {
7817        let lsb = 1.0 / 32768.0;
7818        for (v, expected) in [
7819            (0.5f32, 1i16),
7820            (1.5, 2),
7821            (2.5, 3),
7822            (-0.5, -1),
7823            (-2.5, -3),
7824            (2.4999998, 2),
7825            (100.49, 100),
7826            (-100.51, -101),
7827            // 0.5 - 2^-25: the addition rounds up to 1. `vcvtaq_s32_f32`
7828            // would give 0.
7829            (0.49999997, 1),
7830            (-0.49999997, -1),
7831            (32767.5, 32767),
7832            (-32768.5, -32768),
7833            (1e9, 32767),
7834            (f32::NEG_INFINITY, -32768),
7835            (f32::NAN, 0),
7836        ] {
7837            assert_eq!(float2int16_neon_arm32(v * lsb), expected, "{v}");
7838        }
7839    }
7840
7841    /// Encode a tone with `enc`, `frames` frames of `frame_size` samples.
7842    fn encode_tone(enc: &mut OpusEncoder, frame_size: usize, frames: usize) -> Vec<Vec<u8>> {
7843        let mut packets = Vec::new();
7844        for f in 0..frames {
7845            let pcm: Vec<f32> = (0..frame_size)
7846                .map(|i| 0.4 * ((f * frame_size + i) as f32 * 0.05).sin())
7847                .collect();
7848            let mut out = vec![0u8; 1500];
7849            let n = enc.encode(&pcm, frame_size, &mut out).unwrap();
7850            out.truncate(n);
7851            packets.push(out);
7852        }
7853        packets
7854    }
7855
7856    /// `decode_native` reads a self-delimited packet that is followed by
7857    /// other data, decodes what `decode` decodes from the plain packet, and
7858    /// says where the packet ends.
7859    #[test]
7860    fn decode_native_reads_self_delimited_packets() {
7861        // 20 ms packets hold one frame, 60 ms CELT packets three.
7862        for frame_size in [960usize, 2880] {
7863            let mut enc = OpusEncoder::new(
7864                SampleRate::Hz48000,
7865                Channels::Mono,
7866                Application::RestrictedLowDelay,
7867            )
7868            .unwrap();
7869            let mut plain = OpusDecoder::new(SampleRate::Hz48000, Channels::Mono).unwrap();
7870            let mut delimited = OpusDecoder::new(SampleRate::Hz48000, Channels::Mono).unwrap();
7871            let (mut a, mut b) = (vec![0f32; frame_size], vec![0f32; frame_size]);
7872            for p in encode_tone(&mut enc, frame_size, 12) {
7873                let parsed = packet::parse(&p, Framing::Normal).unwrap();
7874                assert_eq!(parsed.nb_frames(), frame_size / 960);
7875                let frames: Vec<&[u8]> = parsed.frames(&p).collect();
7876                let mut stream = vec![0u8; p.len() + 16];
7877                let len = packet::write(parsed.toc(), &frames, &mut stream, Framing::SelfDelimited, Padding::Shortest).unwrap();
7878                // The next stream of a multistream packet would follow here.
7879                stream.truncate(len);
7880                stream.extend_from_slice(&[0xF8, 1, 2, 3, 4]);
7881
7882                assert_eq!(plain.decode(&p, frame_size, &mut a), Ok(frame_size));
7883                assert_eq!(
7884                    delimited.decode_native(&stream, frame_size, &mut b, false, true, false),
7885                    Ok((frame_size, len))
7886                );
7887                assert_eq!(a, b);
7888                assert_eq!(plain.final_range(), delimited.final_range());
7889                assert_ne!(plain.final_range(), 0);
7890            }
7891            // A lost packet takes no bytes.
7892            assert_eq!(delimited.decode_native(&[], 960, &mut b, false, true, false), Ok((960, 0)));
7893            assert_eq!(delimited.final_range(), 0);
7894            // FEC decode of a CELT-only packet conceals, and still says how
7895            // long the packet is.
7896            let stream = [0xF8, 3, 1, 2, 3, 0xF8, 9];
7897            assert_eq!(
7898                delimited.decode_native(&stream, 960, &mut b, true, true, false),
7899                Ok((960, 5))
7900            );
7901            // A self-delimited packet that is cut short is an error.
7902            let cut = [0xF8, 3, 1, 2];
7903            assert!(delimited.decode_native(&cut, 960, &mut b, false, true, false).is_err());
7904        }
7905    }
7906
7907    /// Self-delimited SILK packets with in-band FEC, some of them padded, as
7908    /// the streams of a multistream packet are: a normal decode, an FEC
7909    /// decode and a soft-clipped decode through `decode_native` give what
7910    /// the public calls give for the plain packet, and each says where the
7911    /// self-delimited packet ends.
7912    #[test]
7913    fn decode_native_handles_fec_and_padding_in_self_delimited_packets() {
7914        let frame_size = 320usize;
7915        let mut enc =
7916            OpusEncoder::new(SampleRate::Hz16000, Channels::Mono, Application::Voip).unwrap();
7917        enc.set_bitrate(Bitrate::BitsPerSecond(NonZeroU32::new(28000).unwrap()));
7918        enc.set_inband_fec(InbandFec::On);
7919        enc.set_packet_loss_perc(25).unwrap();
7920        let packets = encode_tone(&mut enc, frame_size, 40);
7921        // SILK-only packets, half of them or more with a copy of the frame
7922        // before: the second bit of a mono SILK frame is its FEC flag.
7923        assert!(packets.iter().all(|p| p[0] & 0x80 == 0));
7924        let with_copy = packets.iter().filter(|p| p[1] & 0x40 != 0).count();
7925        assert!(with_copy >= 15, "{with_copy} of 40 packets carry FEC data");
7926        let mut plain = OpusDecoder::new(SampleRate::Hz16000, Channels::Mono).unwrap();
7927        let mut delimited = OpusDecoder::new(SampleRate::Hz16000, Channels::Mono).unwrap();
7928        let (mut a, mut b) = (vec![0f32; 2 * frame_size], vec![0f32; 2 * frame_size]);
7929        let mut a16 = vec![0i16; frame_size];
7930        let mut fec_calls = 0;
7931        for (i, p) in packets.iter().enumerate() {
7932            let parsed = packet::parse(p, Framing::Normal).unwrap();
7933            let frames: Vec<&[u8]> = parsed.frames(p).collect();
7934            // Every third packet is padded by 1, 2 or 300 bytes.
7935            let extra = if i % 3 == 0 { [1usize, 2, 300][(i / 3) % 3] } else { 0 };
7936            let mut stream = vec![0u8; p.len() + 2 + extra];
7937            let len = if extra == 0 {
7938                packet::write(parsed.toc(), &frames, &mut stream, Framing::SelfDelimited, Padding::Shortest).unwrap()
7939            } else {
7940                packet::write(parsed.toc(), &frames, &mut stream, Framing::SelfDelimited, Padding::FillBuffer).unwrap()
7941            };
7942            stream.truncate(len);
7943            stream.extend_from_slice(&[0x0B, 0xFF, 7]);
7944
7945            if i % 7 == 5 {
7946                // The packet before this one was lost, together with the
7947                // one before that on every second occasion.
7948                let lost = if fec_calls % 2 == 0 { frame_size } else { 2 * frame_size };
7949                assert_eq!(plain.decode_fec(p, lost, &mut a), Ok(lost));
7950                assert_eq!(
7951                    delimited.decode_native(&stream, lost, &mut b, true, true, false),
7952                    Ok((lost, len))
7953                );
7954                assert_eq!(a[..lost], b[..lost], "packet {i}: FEC decode");
7955                assert_eq!(plain.final_range(), delimited.final_range());
7956                fec_calls += 1;
7957            }
7958            if i % 4 == 1 {
7959                // The 16-bit path: soft clipping, then rounding.
7960                assert_eq!(plain.decode_i16(p, frame_size, &mut a16), Ok(frame_size));
7961                assert_eq!(
7962                    delimited.decode_native(&stream, frame_size, &mut b, false, true, true),
7963                    Ok((frame_size, len))
7964                );
7965                let mut converted = vec![0i16; frame_size];
7966                celt_float2int16(&b[..frame_size], &mut converted);
7967                assert_eq!(a16, converted, "packet {i}: 16-bit decode");
7968            } else {
7969                assert_eq!(plain.decode(p, frame_size, &mut a), Ok(frame_size));
7970                assert_eq!(
7971                    delimited.decode_native(&stream, frame_size, &mut b, false, true, false),
7972                    Ok((frame_size, len))
7973                );
7974                assert_eq!(a[..frame_size], b[..frame_size], "packet {i}");
7975            }
7976            assert_eq!(plain.final_range(), delimited.final_range(), "packet {i}");
7977            assert_ne!(plain.final_range(), 0, "packet {i}");
7978        }
7979        assert!(fec_calls >= 4);
7980    }
7981
7982    // Also verify that the Audio application path (always Hybrid at 48 kHz) rejects
7983    // the same bad frame size.
7984    #[test]
7985    fn test_invalid_small_frame_size_audio_application_returns_error() {
7986        let mut enc =
7987            OpusEncoder::new(SampleRate::Hz48000, Channels::Mono, Application::Audio).unwrap();
7988        let input = vec![0.0f32; 48];
7989        let mut output = vec![0u8; 256];
7990
7991        let result = enc.encode(&input, 48, &mut output);
7992        assert!(
7993            result.is_err(),
7994            "Audio/48kHz encoder with frame_size=48 should return Err"
7995        );
7996    }
7997
7998    /// The enums with a libopus number convert to it and back, and refuse
7999    /// every other number, also the numbers next to theirs.
8000    #[test]
8001    fn settings_enums_convert_to_and_from_libopus_numbers() {
8002        fn check<T>(values: &[T], raw: fn(T) -> i32)
8003        where
8004            T: Copy + PartialEq + core::fmt::Debug + TryFrom<i32, Error = Error>,
8005        {
8006            for &v in values {
8007                assert_eq!(T::try_from(raw(v)), Ok(v));
8008            }
8009            let numbers: Vec<i32> = values.iter().map(|&v| raw(v)).collect();
8010            for &n in &numbers {
8011                for other in [n - 1, n + 1] {
8012                    if !numbers.contains(&other) {
8013                        assert_eq!(T::try_from(other).map_err(|e| e.kind()), Err(ErrorKind::BadArg));
8014                    }
8015                }
8016            }
8017            for other in [i32::MIN, -1, 0, i32::MAX] {
8018                if !numbers.contains(&other) {
8019                    assert!(T::try_from(other).is_err(), "{other}");
8020                }
8021            }
8022        }
8023        let apps = [
8024            Application::Voip,
8025            Application::Audio,
8026            Application::RestrictedLowDelay,
8027            Application::RestrictedSilk,
8028            Application::RestrictedCelt,
8029        ];
8030        assert_eq!(apps.map(Application::to_raw), [2048, 2049, 2051, 2052, 2053]);
8031        check(&apps, Application::to_raw);
8032        let bandwidths = [
8033            Bandwidth::Narrowband,
8034            Bandwidth::Mediumband,
8035            Bandwidth::Wideband,
8036            Bandwidth::Superwideband,
8037            Bandwidth::Fullband,
8038        ];
8039        assert_eq!(bandwidths.map(Bandwidth::to_raw), [1101, 1102, 1103, 1104, 1105]);
8040        check(&bandwidths, Bandwidth::to_raw);
8041        assert!(Bandwidth::try_from(OPUS_AUTO).is_err());
8042        let modes = [ForcedMode::SilkOnly, ForcedMode::Hybrid, ForcedMode::CeltOnly];
8043        assert_eq!(modes.map(ForcedMode::to_raw), [1000, 1001, 1002]);
8044        check(&modes, ForcedMode::to_raw);
8045        let signals = [Signal::Auto, Signal::Voice, Signal::Music];
8046        assert_eq!(signals.map(Signal::to_raw), [OPUS_AUTO, 3001, 3002]);
8047        check(&signals, Signal::to_raw);
8048        let fec = [InbandFec::Off, InbandFec::On, InbandFec::OnUnlessMusic];
8049        assert_eq!(fec.map(InbandFec::to_raw), [0, 1, 2]);
8050        check(&fec, InbandFec::to_raw);
8051        check(&FrameDuration::ALL, FrameDuration::to_raw);
8052        // The defaults are those of libopus.
8053        assert_eq!(Bitrate::default(), Bitrate::Auto);
8054        assert_eq!(Signal::default(), Signal::Auto);
8055        assert_eq!(InbandFec::default(), InbandFec::Off);
8056        assert_eq!(FrameDuration::default(), FrameDuration::Argument);
8057    }
8058
8059    /// The settings with a narrow type refuse only what libopus refuses
8060    /// inside that type, and keep their value then.
8061    #[test]
8062    fn narrow_settings_refuse_what_libopus_refuses() {
8063        let mut enc =
8064            OpusEncoder::new(SampleRate::Hz48000, Channels::Stereo, Application::Audio).unwrap();
8065        for v in 0..=u8::MAX {
8066            assert_eq!(enc.set_complexity(v).is_ok(), v <= 10, "complexity {v}");
8067            assert_eq!(enc.complexity(), v.min(10), "complexity {v}");
8068            assert_eq!(enc.set_packet_loss_perc(v).is_ok(), v <= 100, "loss {v}");
8069            assert_eq!(enc.packet_loss_perc(), v.min(100), "loss {v}");
8070            assert_eq!(enc.set_voice_ratio(Some(v)).is_ok(), v <= 100, "voice ratio {v}");
8071            assert_eq!(enc.voice_ratio(), Some(v.min(100)), "voice ratio {v}");
8072        }
8073        for v in [0, 7, 8, 16, 24, 25, u8::MAX] {
8074            let ok = (8..=24).contains(&v);
8075            assert_eq!(enc.set_lsb_depth(v).is_ok(), ok, "LSB depth {v}");
8076            assert_eq!(enc.lsb_depth(), if ok { v } else { 24 }, "LSB depth {v}");
8077        }
8078        enc.set_voice_ratio(None).unwrap();
8079        assert_eq!(enc.voice_ratio(), None);
8080        assert_eq!(enc.voice_ratio, -1);
8081
8082        // A bitrate is limited to 500 b/s and 750,000 b/s per channel, also
8083        // beyond the `opus_int32` of libopus.
8084        let bps = |v| Bitrate::BitsPerSecond(NonZeroU32::new(v).unwrap());
8085        for (set, kept) in [(1, 500), (499, 500), (64_000, 64_000), (1_500_001, 1_500_000), (u32::MAX, 1_500_000)] {
8086            enc.set_bitrate(bps(set));
8087            assert_eq!(enc.bitrate_setting(), bps(kept), "bitrate {set}");
8088        }
8089
8090        let mut dec = OpusDecoder::new(SampleRate::Hz48000, Channels::Mono).unwrap();
8091        for v in 0..=u8::MAX {
8092            assert_eq!(dec.set_complexity(v).is_ok(), v <= 10, "decoder complexity {v}");
8093            assert_eq!(dec.complexity(), v.min(10), "decoder complexity {v}");
8094        }
8095        for gain in [i16::MIN, -1, 0, 1, i16::MAX] {
8096            dec.set_gain(gain);
8097            assert_eq!(dec.gain(), gain);
8098        }
8099    }
8100
8101    /// `pcm_soft_clip` takes the samples per channel from the length of
8102    /// `pcm` and refuses arguments that do not fit.
8103    #[test]
8104    fn pcm_soft_clip_checks_its_arguments() {
8105        let mut pcm = [1.5f32, -1.5, 1.5, -1.5, 0.0, 0.0];
8106        let mut memory = [0.0f32; 2];
8107        let kind = |r: Result<(), Error>| r.map_err(|e| e.kind());
8108        assert_eq!(kind(pcm_soft_clip(&mut pcm, 0, &mut memory)), Err(ErrorKind::BadArg));
8109        assert_eq!(kind(pcm_soft_clip(&mut pcm, 4, &mut memory)), Err(ErrorKind::BadArg));
8110        assert_eq!(kind(pcm_soft_clip(&mut pcm, 3, &mut memory)), Err(ErrorKind::BadArg));
8111        assert_eq!(pcm, [1.5, -1.5, 1.5, -1.5, 0.0, 0.0]);
8112        // Three samples of two channels, as `soft_clip` with a frame size of
8113        // 3 gives them.
8114        let mut expected = pcm;
8115        let mut expected_memory = memory;
8116        soft_clip(&mut expected, 3, 2, &mut expected_memory);
8117        pcm_soft_clip(&mut pcm, 2, &mut memory).unwrap();
8118        assert_eq!(pcm, expected);
8119        assert_eq!(memory, expected_memory);
8120        assert!(pcm.iter().all(|x| x.abs() <= 1.0));
8121    }
8122}