oximedia-codec 0.1.8

Video codec implementations for OxiMedia
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Opus audio codec decoder.
//!
//! Opus is a modern, royalty-free audio codec designed for interactive
//! speech and music transmission over the Internet. It combines SILK
//! (for speech) and CELT (for music) to provide excellent quality
//! across a wide range of bitrates and content types.
//!
//! # Features
//!
//! - **SILK mode**: Optimized for speech (narrowband to wideband)
//! - **CELT mode**: Optimized for music (narrowband to fullband)
//! - **Hybrid mode**: Combines SILK and CELT for mixed content
//! - **Adaptive bandwidth**: 4 kHz (narrowband) to 20 kHz (fullband)
//! - **Low latency**: Frame sizes from 2.5ms to 60ms
//! - **Scalable complexity**: Adjustable CPU usage
//!
//! # Architecture
//!
//! This implementation provides:
//!
//! - Complete packet parsing and frame structure handling
//! - A normative RFC 6716 §4.1 range decoder for entropy coding
//! - MDCT transforms for CELT mode
//! - A CELT decoder for music content
//! - A normative RFC 6716 §4.2 SILK decoder (NLSF, LTP, shell-coded
//!   excitation, LTP+LPC synthesis) for speech content
//! - A real hybrid decoder that decodes SILK then CELT from one shared
//!   range-coded bitstream (RFC 6716 §3.1)
//!
//! # Example
//!
//! ```ignore
//! use oximedia_codec::opus::OpusDecoder;
//!
//! let mut decoder = OpusDecoder::new(48000, 2)?;
//! let output = decoder.decode_packet(&packet_data)?;
//! ```
//!
//! # References
//!
//! - RFC 6716: Definition of the Opus Audio Codec
//! - <https://opus-codec.org/>

pub mod celt;
pub mod encoder;
pub mod hybrid;
pub mod mdct;
pub mod packet;
pub mod range_decoder;
pub mod range_encoder;
pub mod silk;
pub mod silk_decoder;
pub mod silk_encoder;
pub mod silk_excitation;
pub mod silk_lpc;
pub mod silk_ltp;
pub mod silk_nsq;
pub mod silk_range;
pub mod silk_range_encoder;
pub mod silk_tables;
pub mod vad;

use crate::{AudioFrame, CodecError, CodecResult, SampleFormat};

use celt::CeltDecoder;
use hybrid::HybridDecoder;
use packet::{OpusBandwidth, OpusMode, OpusPacket};
use silk::SilkDecoder;

// Re-export encoder types
pub use encoder::{OpusEncoder, OpusEncoderConfig};

/// Opus decoder configuration.
#[derive(Debug, Clone)]
pub struct OpusConfig {
    /// Sample rate in Hz (8000, 12000, 16000, 24000, or 48000)
    pub sample_rate: u32,
    /// Number of channels (1 or 2)
    pub channels: usize,
    /// Output sample format
    pub sample_format: SampleFormat,
}

impl Default for OpusConfig {
    fn default() -> Self {
        Self {
            sample_rate: 48000,
            channels: 2,
            sample_format: SampleFormat::F32,
        }
    }
}

/// Opus audio decoder.
///
/// Decodes Opus-compressed audio packets to PCM samples.
pub struct OpusDecoder {
    /// Configuration
    config: OpusConfig,
    /// SILK decoder (for speech mode)
    silk: Option<SilkDecoder>,
    /// CELT decoder (for music mode)
    celt: Option<CeltDecoder>,
    /// Hybrid decoder (for mixed mode)
    hybrid: Option<HybridDecoder>,
    /// Current operating mode
    current_mode: Option<OpusMode>,
    /// Frame counter
    frame_count: u64,
}

impl OpusDecoder {
    /// Creates a new Opus decoder.
    ///
    /// # Arguments
    ///
    /// * `sample_rate` - Sample rate in Hz (8000, 12000, 16000, 24000, or 48000)
    /// * `channels` - Number of channels (1 or 2)
    pub fn new(sample_rate: u32, channels: usize) -> CodecResult<Self> {
        Self::with_config(OpusConfig {
            sample_rate,
            channels,
            sample_format: SampleFormat::F32,
        })
    }

    /// Creates a new Opus decoder with custom configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Decoder configuration
    pub fn with_config(config: OpusConfig) -> CodecResult<Self> {
        // Validate sample rate
        if !matches!(config.sample_rate, 8000 | 12000 | 16000 | 24000 | 48000) {
            return Err(CodecError::InvalidData(format!(
                "Invalid sample rate: {}",
                config.sample_rate
            )));
        }

        // Validate channels
        if config.channels == 0 || config.channels > 2 {
            return Err(CodecError::InvalidData(format!(
                "Invalid channel count: {}",
                config.channels
            )));
        }

        Ok(Self {
            config,
            silk: None,
            celt: None,
            hybrid: None,
            current_mode: None,
            frame_count: 0,
        })
    }

    /// Decodes an Opus packet to audio samples.
    ///
    /// # Arguments
    ///
    /// * `data` - Opus packet data
    pub fn decode_packet(&mut self, data: &[u8]) -> CodecResult<AudioFrame> {
        // Parse packet
        let packet = OpusPacket::parse(data)?;

        // Determine frame size
        let frame_size = packet.toc.frame_size as usize;

        // Initialize appropriate decoder if needed
        self.initialize_decoder(&packet.toc.mode, packet.toc.bandwidth, frame_size)?;

        // Allocate output buffer
        let sample_count = frame_size * packet.frame_count();
        let mut samples = vec![0.0f32; sample_count * self.config.channels];

        // Decode each frame
        let mut offset = 0;
        for frame_data in &packet.frames {
            let frame_samples = frame_size * self.config.channels;
            let output_slice = &mut samples[offset..offset + frame_samples];

            self.decode_frame(&packet.toc.mode, frame_data, output_slice, frame_size)?;

            offset += frame_samples;
            self.frame_count += 1;
        }

        // Convert to output format
        let output_samples = self.convert_samples(&samples)?;

        Ok(AudioFrame::new(
            output_samples,
            sample_count,
            self.config.sample_rate,
            self.config.channels,
            self.config.sample_format,
        ))
    }

    /// Initializes the appropriate decoder for the given mode.
    fn initialize_decoder(
        &mut self,
        mode: &OpusMode,
        bandwidth: OpusBandwidth,
        frame_size: usize,
    ) -> CodecResult<()> {
        // Only initialize if mode changed or decoder doesn't exist
        if self.current_mode.as_ref() != Some(mode) {
            match mode {
                OpusMode::Silk => {
                    if self.silk.is_none() {
                        self.silk = Some(SilkDecoder::new(
                            self.config.sample_rate,
                            self.config.channels,
                            bandwidth,
                        ));
                    }
                }
                OpusMode::Celt => {
                    if self.celt.is_none() {
                        self.celt = Some(CeltDecoder::new(
                            self.config.sample_rate,
                            self.config.channels,
                            bandwidth,
                            frame_size,
                        ));
                    }
                }
                OpusMode::Hybrid => {
                    if self.hybrid.is_none() {
                        self.hybrid = Some(HybridDecoder::new(
                            self.config.sample_rate,
                            self.config.channels,
                            bandwidth,
                            frame_size,
                        ));
                    }
                }
            }
            self.current_mode = Some(*mode);
        }

        Ok(())
    }

    /// Decodes a single frame.
    fn decode_frame(
        &mut self,
        mode: &OpusMode,
        data: &[u8],
        output: &mut [f32],
        frame_size: usize,
    ) -> CodecResult<()> {
        match mode {
            OpusMode::Silk => {
                if let Some(silk) = &mut self.silk {
                    silk.decode(data, output, frame_size)?;
                } else {
                    return Err(CodecError::InvalidData(
                        "SILK decoder not initialized".to_string(),
                    ));
                }
            }
            OpusMode::Celt => {
                if let Some(celt) = &mut self.celt {
                    celt.decode(data, output, frame_size)?;
                } else {
                    return Err(CodecError::InvalidData(
                        "CELT decoder not initialized".to_string(),
                    ));
                }
            }
            OpusMode::Hybrid => {
                if let Some(hybrid) = &mut self.hybrid {
                    // Hybrid mode: the SILK and CELT layers share one
                    // range-coded bitstream (RFC 6716 §3.1). The whole frame
                    // payload is passed as a single stream — no byte split.
                    hybrid.decode(data, output, frame_size)?;
                } else {
                    return Err(CodecError::InvalidData(
                        "Hybrid decoder not initialized".to_string(),
                    ));
                }
            }
        }

        Ok(())
    }

    /// Converts f32 samples to the configured output format.
    fn convert_samples(&self, samples: &[f32]) -> CodecResult<Vec<u8>> {
        match self.config.sample_format {
            SampleFormat::F32 => {
                // Convert f32 slice to bytes
                let mut output = Vec::with_capacity(samples.len() * 4);
                for &sample in samples {
                    output.extend_from_slice(&sample.to_le_bytes());
                }
                Ok(output)
            }
            SampleFormat::I16 => {
                // Convert to i16
                let mut output = Vec::with_capacity(samples.len() * 2);
                for &sample in samples {
                    let i16_sample = (sample.clamp(-1.0, 1.0) * 32767.0) as i16;
                    output.extend_from_slice(&i16_sample.to_le_bytes());
                }
                Ok(output)
            }
            SampleFormat::I32 => {
                // Convert to i32
                let mut output = Vec::with_capacity(samples.len() * 4);
                for &sample in samples {
                    let i32_sample = (sample.clamp(-1.0, 1.0) * 2_147_483_647.0) as i32;
                    output.extend_from_slice(&i32_sample.to_le_bytes());
                }
                Ok(output)
            }
            SampleFormat::U8 => {
                // Convert to u8
                let mut output = Vec::with_capacity(samples.len());
                for &sample in samples {
                    let u8_sample = ((sample.clamp(-1.0, 1.0) + 1.0) * 127.5) as u8;
                    output.push(u8_sample);
                }
                Ok(output)
            }
        }
    }

    /// Resets decoder state.
    pub fn reset(&mut self) {
        if let Some(silk) = &mut self.silk {
            silk.reset();
        }
        if let Some(celt) = &mut self.celt {
            celt.reset();
        }
        if let Some(hybrid) = &mut self.hybrid {
            hybrid.reset();
        }
        self.current_mode = None;
        self.frame_count = 0;
    }

    /// Returns the current configuration.
    #[must_use]
    pub const fn config(&self) -> &OpusConfig {
        &self.config
    }

    /// Returns the number of frames decoded.
    #[must_use]
    pub const fn frame_count(&self) -> u64 {
        self.frame_count
    }

    /// Returns the current operating mode.
    #[must_use]
    pub const fn current_mode(&self) -> Option<OpusMode> {
        self.current_mode
    }
}

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

    #[test]
    fn test_opus_decoder_creation() {
        let decoder = OpusDecoder::new(48000, 2);
        assert!(decoder.is_ok());
    }

    #[test]
    fn test_opus_decoder_invalid_sample_rate() {
        let decoder = OpusDecoder::new(44100, 2);
        assert!(decoder.is_err());
    }

    #[test]
    fn test_opus_decoder_invalid_channels() {
        let decoder = OpusDecoder::new(48000, 0);
        assert!(decoder.is_err());
    }

    #[test]
    fn test_opus_config_default() {
        let config = OpusConfig::default();
        assert_eq!(config.sample_rate, 48000);
        assert_eq!(config.channels, 2);
        assert_eq!(config.sample_format, SampleFormat::F32);
    }

    #[test]
    fn test_opus_decoder_reset() {
        let mut decoder = OpusDecoder::new(48000, 2).expect("should succeed");
        decoder.reset();
        assert_eq!(decoder.frame_count(), 0);
    }
}