rvoip-codec-core 0.2.2

G.711 and optional G.729A/G.729AB audio codec implementation for RVOIP
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! # Audio Codec Implementations
//!
//! This module contains G.711 audio codec implementation for VoIP applications.
//!
//! ## Available Codecs
//!
//! ### G.711 (PCMU/PCMA) - [`g711`]
//! - **Standard**: ITU-T G.711
//! - **Sample Rate**: 8 kHz
//! - **Bitrate**: 64 kbps
//! - **Quality**: ~37 dB SNR
//! - **Use Case**: Standard telephony
//! - **Variants**: μ-law (PCMU), A-law (PCMA)
//!
//! ## Testing
//!
//! G.711 is validated with real speech samples through WAV roundtrip tests:
//! - Downloads reference audio samples
//! - Round-trip encoding and decoding validation
//! - Signal-to-Noise Ratio (SNR) measurement
//!
//! ## Usage Examples
//!
//! ### Using the Codec Factory
//! ```rust
//! use codec_core::codecs::CodecFactory;
//! use codec_core::types::{CodecConfig, CodecType, SampleRate};
//!
//! // Create any codec through the factory
//! let config = CodecConfig::new(CodecType::G711Pcmu)
//!     .with_sample_rate(SampleRate::Rate8000);
//! let mut codec = CodecFactory::create(config)?;
//!
//! // Use unified interface
//! let samples = vec![0i16; 160];
//! let encoded = codec.encode(&samples)?;
//! let decoded = codec.decode(&encoded)?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ### Direct Codec Access
//! ```rust
//! use codec_core::codecs::g711::{G711Codec, G711Variant};
//!
//! // Direct instantiation
//! let mut g711_ulaw = G711Codec::new(G711Variant::MuLaw);
//! let mut g711_alaw = G711Codec::new(G711Variant::ALaw);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Testing & Validation
//!
//! All codecs include comprehensive test suites:
//! - ITU-T compliance validation
//! - Real audio roundtrip tests
//! - Performance benchmarks
//! - Quality measurements (SNR)
//!
//! ```bash
//! # Test all codecs
//! cargo test
//!
//! # Test with real audio (downloads speech samples)
//! cargo test wav_roundtrip_test -- --nocapture
//! ```

use crate::error::{CodecError, Result};
use crate::types::{AudioCodec, CodecConfig, CodecInfo, CodecType};
use std::collections::HashMap;

// Codec implementations
#[cfg(feature = "g711")]
pub mod g711;

#[cfg(feature = "g729")]
pub mod g729;

#[cfg(any(feature = "opus", feature = "opus-sim"))]
pub mod opus;

/// Codec factory for creating codec instances
pub struct CodecFactory;

impl CodecFactory {
    /// Create a codec instance from configuration
    pub fn create(config: CodecConfig) -> Result<Box<dyn AudioCodec>> {
        // Validate configuration first
        config.validate()?;

        match config.codec_type {
            #[cfg(feature = "g711")]
            CodecType::G711Pcmu => {
                let codec = g711::G711Codec::new_pcmu(config)?;
                Ok(Box::new(codec))
            }

            #[cfg(feature = "g711")]
            CodecType::G711Pcma => {
                let codec = g711::G711Codec::new_pcma(config)?;
                Ok(Box::new(codec))
            }

            #[cfg(feature = "g729")]
            CodecType::G729 | CodecType::G729A | CodecType::G729BA => {
                let codec = g729::G729Codec::new(config)?;
                Ok(Box::new(codec))
            }

            #[cfg(any(feature = "opus", feature = "opus-sim"))]
            CodecType::Opus => {
                let codec = opus::OpusCodec::new(config)?;
                Ok(Box::new(codec))
            }

            codec_type => Err(CodecError::feature_not_enabled(format!(
                "Codec {} not enabled in build features",
                codec_type.name()
            ))),
        }
    }

    /// Create a codec by name
    pub fn create_by_name(name: &str, config: CodecConfig) -> Result<Box<dyn AudioCodec>> {
        let codec_type = match normalize_codec_name(name).as_str() {
            "PCMU" => CodecType::G711Pcmu,
            "PCMA" => CodecType::G711Pcma,
            "G729" => CodecType::G729,
            "G729A" => CodecType::G729A,
            "G729AB" | "G729BA" => CodecType::G729BA,
            "OPUS" => CodecType::Opus,
            _ => return Err(CodecError::unsupported_codec(name)),
        };

        let config = CodecConfig {
            codec_type,
            ..config
        };

        Self::create(config)
    }

    /// Create a codec by RTP payload type
    pub fn create_by_payload_type(
        payload_type: u8,
        config: CodecConfig,
    ) -> Result<Box<dyn AudioCodec>> {
        let codec_type = match payload_type {
            0 => CodecType::G711Pcmu,
            8 => CodecType::G711Pcma,
            18 => CodecType::G729,

            _ => return Err(CodecError::unsupported_codec(format!("PT{}", payload_type))),
        };

        let config = CodecConfig {
            codec_type,
            ..config
        };

        Self::create(config)
    }

    /// Get all supported codec names
    pub fn supported_codecs() -> Vec<&'static str> {
        vec![
            #[cfg(feature = "g711")]
            "PCMU",
            #[cfg(feature = "g711")]
            "PCMA",
            #[cfg(feature = "g729")]
            "G729",
            #[cfg(feature = "g729")]
            "G729A",
            #[cfg(feature = "g729")]
            "G729BA",
            #[cfg(any(feature = "opus", feature = "opus-sim"))]
            "OPUS",
        ]
    }

    /// Check if a codec is supported
    pub fn is_supported(name: &str) -> bool {
        let normalized = normalize_codec_name(name);
        match normalized.as_str() {
            #[cfg(feature = "g711")]
            "PCMU" | "PCMA" => true,
            #[cfg(feature = "g729")]
            "G729" | "G729A" | "G729AB" | "G729BA" => true,
            #[cfg(any(feature = "opus", feature = "opus-sim"))]
            "OPUS" => true,
            _ => false,
        }
    }
}

fn normalize_codec_name(name: &str) -> String {
    name.to_ascii_uppercase().replace('.', "")
}

/// Codec registry for managing multiple codec instances
pub struct CodecRegistry {
    codecs: HashMap<String, Box<dyn AudioCodec>>,
}

impl CodecRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self {
            codecs: HashMap::new(),
        }
    }

    /// Register a codec with a name
    pub fn register(&mut self, name: String, codec: Box<dyn AudioCodec>) {
        self.codecs.insert(name, codec);
    }

    /// Get a codec by name
    pub fn get(&self, name: &str) -> Option<&dyn AudioCodec> {
        self.codecs.get(name).map(|codec| codec.as_ref())
    }

    /// Get a mutable codec by name
    pub fn get_mut(&mut self, name: &str) -> Option<&mut Box<dyn AudioCodec>> {
        self.codecs.get_mut(name)
    }

    /// Remove a codec by name
    pub fn remove(&mut self, name: &str) -> Option<Box<dyn AudioCodec>> {
        self.codecs.remove(name)
    }

    /// List all registered codec names
    pub fn list_codecs(&self) -> Vec<&String> {
        self.codecs.keys().collect()
    }

    /// Get the count of registered codecs
    pub fn len(&self) -> usize {
        self.codecs.len()
    }

    /// Check if the registry is empty
    pub fn is_empty(&self) -> bool {
        self.codecs.is_empty()
    }

    /// Clear all registered codecs
    pub fn clear(&mut self) {
        self.codecs.clear();
    }
}

impl Default for CodecRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Codec capability information
#[derive(Debug, Clone)]
pub struct CodecCapabilities {
    /// Available codec types
    pub codec_types: Vec<CodecType>,
    /// Codec information
    pub codec_info: HashMap<CodecType, CodecInfo>,
}

impl CodecCapabilities {
    /// Get capabilities for all supported codecs
    pub fn get_all() -> Self {
        let mut codec_types = Vec::new();
        let mut codec_info = HashMap::new();

        #[cfg(feature = "g711")]
        {
            codec_types.push(CodecType::G711Pcmu);
            codec_types.push(CodecType::G711Pcma);

            codec_info.insert(
                CodecType::G711Pcmu,
                CodecInfo {
                    name: "PCMU",
                    sample_rate: 8000,
                    channels: 1,
                    bitrate: 64000,
                    frame_size: 160,
                    payload_type: Some(0),
                },
            );

            codec_info.insert(
                CodecType::G711Pcma,
                CodecInfo {
                    name: "PCMA",
                    sample_rate: 8000,
                    channels: 1,
                    bitrate: 64000,
                    frame_size: 160,
                    payload_type: Some(8),
                },
            );
        }

        #[cfg(any(feature = "opus", feature = "opus-sim"))]
        {
            codec_types.push(CodecType::Opus);
            codec_info.insert(
                CodecType::Opus,
                CodecInfo {
                    name: "opus",
                    sample_rate: 48000,
                    channels: 1,
                    bitrate: 64000,
                    frame_size: 960,
                    payload_type: None,
                },
            );
        }

        #[cfg(feature = "g729")]
        {
            codec_types.push(CodecType::G729);
            codec_types.push(CodecType::G729A);
            codec_types.push(CodecType::G729BA);

            codec_info.insert(
                CodecType::G729,
                CodecInfo {
                    name: "G729",
                    sample_rate: 8000,
                    channels: 1,
                    bitrate: 8000,
                    frame_size: 80,
                    payload_type: Some(18),
                },
            );
            codec_info.insert(
                CodecType::G729A,
                CodecInfo {
                    name: "G729A",
                    sample_rate: 8000,
                    channels: 1,
                    bitrate: 8000,
                    frame_size: 80,
                    payload_type: Some(18),
                },
            );
            codec_info.insert(
                CodecType::G729BA,
                CodecInfo {
                    name: "G729BA",
                    sample_rate: 8000,
                    channels: 1,
                    bitrate: 8000,
                    frame_size: 80,
                    payload_type: Some(18),
                },
            );
        }

        Self {
            codec_types,
            codec_info,
        }
    }

    /// Check if a codec type is supported
    pub fn is_supported(&self, codec_type: CodecType) -> bool {
        self.codec_types.contains(&codec_type)
    }

    /// Get information for a specific codec type
    pub fn get_info(&self, codec_type: CodecType) -> Option<&CodecInfo> {
        self.codec_info.get(&codec_type)
    }
}

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

    #[test]
    fn test_codec_factory_supported_codecs() {
        let supported = CodecFactory::supported_codecs();
        assert!(!supported.is_empty());

        #[cfg(feature = "g711")]
        {
            assert!(supported.contains(&"PCMU"));
            assert!(supported.contains(&"PCMA"));
        }
    }

    #[test]
    fn test_codec_factory_is_supported() {
        #[cfg(feature = "g711")]
        {
            assert!(CodecFactory::is_supported("PCMU"));
            assert!(CodecFactory::is_supported("pcmu"));
            assert!(CodecFactory::is_supported("PCMA"));
        }

        assert!(!CodecFactory::is_supported("UNSUPPORTED"));
    }

    #[test]
    fn test_codec_registry() {
        let mut registry = CodecRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);

        #[cfg(feature = "g711")]
        {
            let config = CodecConfig::g711_pcmu();
            let codec = CodecFactory::create(config).unwrap();
            registry.register("test_pcmu".to_string(), codec);

            assert_eq!(registry.len(), 1);
            assert!(!registry.is_empty());
            assert!(registry.get("test_pcmu").is_some());
        }

        registry.clear();
        assert!(registry.is_empty());
    }

    #[test]
    fn test_codec_capabilities() {
        let caps = CodecCapabilities::get_all();
        assert!(!caps.codec_types.is_empty());
        assert!(!caps.codec_info.is_empty());

        #[cfg(feature = "g711")]
        {
            assert!(caps.is_supported(CodecType::G711Pcmu));
            assert!(caps.get_info(CodecType::G711Pcmu).is_some());
        }
    }

    #[test]
    #[cfg(feature = "g711")]
    fn test_codec_creation() {
        let config = CodecConfig::g711_pcmu();
        let codec = CodecFactory::create(config);
        assert!(codec.is_ok());

        let codec = codec.unwrap();
        let info = codec.info();
        assert_eq!(info.name, "PCMU");
        assert_eq!(info.sample_rate, 8000);
    }

    #[test]
    #[cfg(feature = "g711")]
    fn test_codec_creation_by_name() {
        let config = CodecConfig::new(CodecType::G711Pcmu);
        let codec = CodecFactory::create_by_name("PCMU", config.clone());
        assert!(codec.is_ok());

        let codec = CodecFactory::create_by_name("UNKNOWN", config);
        assert!(codec.is_err());
    }

    #[test]
    #[cfg(feature = "g711")]
    fn test_codec_creation_by_payload_type() {
        let config = CodecConfig::new(CodecType::G711Pcmu);
        let codec = CodecFactory::create_by_payload_type(0, config.clone());
        assert!(codec.is_ok());

        let codec = CodecFactory::create_by_payload_type(255, config);
        assert!(codec.is_err());
    }
}