Skip to main content

codec_core/codecs/
mod.rs

1//! # Audio Codec Implementations
2//!
3//! This module contains G.711 audio codec implementation for `VoIP` applications.
4//!
5//! ## Available Codecs
6//!
7//! ### G.711 (PCMU/PCMA) - [`g711`]
8//! - **Standard**: ITU-T G.711
9//! - **Sample Rate**: 8 kHz
10//! - **Bitrate**: 64 kbps
11//! - **Quality**: ~37 dB SNR
12//! - **Use Case**: Standard telephony
13//! - **Variants**: μ-law (PCMU), A-law (PCMA)
14//!
15//! ## Testing
16//!
17//! G.711 is validated with real speech samples through WAV roundtrip tests:
18//! - Downloads reference audio samples
19//! - Round-trip encoding and decoding validation
20//! - Signal-to-Noise Ratio (SNR) measurement
21//!
22//! ## Usage Examples
23//!
24//! ### Using the Codec Factory
25//! ```rust
26//! # #[cfg(feature = "g711")]
27//! # {
28//! use codec_core::codecs::CodecFactory;
29//! use codec_core::types::{CodecConfig, CodecType, SampleRate};
30//!
31//! // Create any codec through the factory
32//! let config = CodecConfig::new(CodecType::G711Pcmu)
33//!     .with_sample_rate(SampleRate::Rate8000);
34//! let mut codec = CodecFactory::create(config)?;
35//!
36//! // Use unified interface
37//! let samples = vec![0i16; 160];
38//! let encoded = codec.encode(&samples)?;
39//! let decoded = codec.decode(&encoded)?;
40//! # }
41//! # Ok::<(), Box<dyn std::error::Error>>(())
42//! ```
43//!
44//! ### Direct Codec Access
45//! ```rust
46//! # #[cfg(feature = "g711")]
47//! # {
48//! use codec_core::codecs::g711::{G711Codec, G711Variant};
49//!
50//! // Direct instantiation
51//! let mut g711_ulaw = G711Codec::new(G711Variant::MuLaw);
52//! let mut g711_alaw = G711Codec::new(G711Variant::ALaw);
53//! # }
54//! # Ok::<(), Box<dyn std::error::Error>>(())
55//! ```
56//!
57//! ## Testing & Validation
58//!
59//! All codecs include comprehensive test suites:
60//! - ITU-T compliance validation
61//! - Real audio roundtrip tests
62//! - Performance benchmarks
63//! - Quality measurements (SNR)
64//!
65//! ```bash
66//! # Test all codecs
67//! cargo test
68//!
69//! # Test with real audio (downloads speech samples)
70//! cargo test wav_roundtrip_test -- --nocapture
71//! ```
72
73use crate::error::{CodecError, Result};
74use crate::types::{AudioCodec, CodecConfig, CodecInfo, CodecType};
75use std::collections::HashMap;
76
77// The ITU-T G.711 reference algorithms back the always-compiled `utils`
78// helpers, so they build even when the `g711` codec feature is disabled.
79#[path = "g711/reference.rs"]
80pub(crate) mod g711_reference;
81
82// Codec implementations
83#[cfg(feature = "g711")]
84pub mod g711;
85
86#[cfg(feature = "g729")]
87pub mod g729;
88
89#[cfg(feature = "opus")]
90pub mod opus;
91
92#[cfg(any(feature = "amr-nb", feature = "amr-wb"))]
93pub mod amr;
94
95/// Codec factory for creating codec instances
96pub struct CodecFactory;
97
98impl CodecFactory {
99    /// Create a codec instance from configuration
100    ///
101    /// # Errors
102    ///
103    /// Returns an error when the configuration is invalid, the codec feature
104    /// is disabled, or codec construction fails.
105    // Preserve the public by-value constructor in a build where every codec
106    // branch is compiled out; feature-enabled branches transfer ownership to
107    // their concrete codec constructors.
108    #[cfg_attr(
109        not(any(feature = "g711", feature = "g729", feature = "opus")),
110        allow(clippy::needless_pass_by_value)
111    )]
112    pub fn create(config: CodecConfig) -> Result<Box<dyn AudioCodec>> {
113        // Validate configuration first
114        config.validate()?;
115
116        match config.codec_type {
117            #[cfg(feature = "g711")]
118            CodecType::G711Pcmu => {
119                let codec = g711::G711Codec::new_pcmu(config)?;
120                Ok(Box::new(codec))
121            }
122
123            #[cfg(feature = "g711")]
124            CodecType::G711Pcma => {
125                let codec = g711::G711Codec::new_pcma(config)?;
126                Ok(Box::new(codec))
127            }
128
129            #[cfg(feature = "g729")]
130            CodecType::G729 | CodecType::G729A | CodecType::G729BA => {
131                let codec = g729::G729Codec::new(config)?;
132                Ok(Box::new(codec))
133            }
134
135            #[cfg(feature = "opus")]
136            CodecType::Opus => {
137                let codec = opus::OpusCodec::new(config)?;
138                Ok(Box::new(codec))
139            }
140
141            #[cfg(feature = "amr-nb")]
142            CodecType::AmrNb => {
143                let codec = amr::AmrCodec::new(&config)?;
144                Ok(Box::new(codec))
145            }
146
147            #[cfg(feature = "amr-wb")]
148            CodecType::AmrWb => {
149                let codec = amr::AmrCodec::new(&config)?;
150                Ok(Box::new(codec))
151            }
152
153            codec_type => Err(CodecError::feature_not_enabled(format!(
154                "Codec {codec_type} not enabled in build features"
155            ))),
156        }
157    }
158
159    /// Create a codec by name
160    ///
161    /// # Errors
162    ///
163    /// Returns an error when `name` is unknown, its feature is disabled, or
164    /// the configuration is invalid.
165    pub fn create_by_name(name: &str, config: CodecConfig) -> Result<Box<dyn AudioCodec>> {
166        let codec_type = match normalize_codec_name(name).as_str() {
167            "PCMU" => CodecType::G711Pcmu,
168            "PCMA" => CodecType::G711Pcma,
169            "G729" => CodecType::G729,
170            "G729A" => CodecType::G729A,
171            "G729AB" | "G729BA" => CodecType::G729BA,
172            "OPUS" => CodecType::Opus,
173            "AMR" => CodecType::AmrNb,
174            "AMR-WB" | "AMRWB" => CodecType::AmrWb,
175            _ => return Err(CodecError::unsupported_codec(name)),
176        };
177
178        let config = CodecConfig {
179            codec_type,
180            ..config
181        };
182
183        Self::create(config)
184    }
185
186    /// Create a codec by RTP payload type
187    ///
188    /// # Errors
189    ///
190    /// Returns an error when the payload type is unknown, its codec feature is
191    /// disabled, or the configuration is invalid.
192    pub fn create_by_payload_type(
193        payload_type: u8,
194        config: CodecConfig,
195    ) -> Result<Box<dyn AudioCodec>> {
196        let codec_type = match payload_type {
197            0 => CodecType::G711Pcmu,
198            8 => CodecType::G711Pcma,
199            18 => CodecType::G729,
200
201            _ => return Err(CodecError::unsupported_codec(format!("PT{payload_type}"))),
202        };
203
204        let config = CodecConfig {
205            codec_type,
206            ..config
207        };
208
209        Self::create(config)
210    }
211
212    /// Get all supported codec names
213    #[must_use]
214    pub fn supported_codecs() -> Vec<&'static str> {
215        vec![
216            #[cfg(feature = "g711")]
217            "PCMU",
218            #[cfg(feature = "g711")]
219            "PCMA",
220            #[cfg(feature = "g729")]
221            "G729",
222            #[cfg(feature = "g729")]
223            "G729A",
224            #[cfg(feature = "g729")]
225            "G729BA",
226            #[cfg(feature = "opus")]
227            "OPUS",
228            #[cfg(feature = "amr-nb")]
229            "AMR",
230            #[cfg(feature = "amr-wb")]
231            "AMR-WB",
232        ]
233    }
234
235    /// Check if a codec is supported
236    #[must_use]
237    pub fn is_supported(name: &str) -> bool {
238        let normalized = normalize_codec_name(name);
239        match normalized.as_str() {
240            #[cfg(feature = "g711")]
241            "PCMU" | "PCMA" => true,
242            #[cfg(feature = "g729")]
243            "G729" | "G729A" | "G729AB" | "G729BA" => true,
244            #[cfg(feature = "opus")]
245            "OPUS" => true,
246            #[cfg(feature = "amr-nb")]
247            "AMR" => true,
248            #[cfg(feature = "amr-wb")]
249            "AMR-WB" | "AMRWB" => true,
250            _ => false,
251        }
252    }
253}
254
255fn normalize_codec_name(name: &str) -> String {
256    name.to_ascii_uppercase().replace('.', "")
257}
258
259/// Codec registry for managing multiple codec instances
260pub struct CodecRegistry {
261    codecs: HashMap<String, Box<dyn AudioCodec>>,
262}
263
264impl CodecRegistry {
265    /// Create a new empty registry
266    #[must_use]
267    pub fn new() -> Self {
268        Self {
269            codecs: HashMap::new(),
270        }
271    }
272
273    /// Register a codec with a name
274    pub fn register(&mut self, name: String, codec: Box<dyn AudioCodec>) {
275        self.codecs.insert(name, codec);
276    }
277
278    /// Get a codec by name
279    #[must_use]
280    pub fn get(&self, name: &str) -> Option<&dyn AudioCodec> {
281        self.codecs.get(name).map(std::convert::AsRef::as_ref)
282    }
283
284    /// Get a mutable codec by name
285    pub fn get_mut(&mut self, name: &str) -> Option<&mut Box<dyn AudioCodec>> {
286        self.codecs.get_mut(name)
287    }
288
289    /// Remove a codec by name
290    pub fn remove(&mut self, name: &str) -> Option<Box<dyn AudioCodec>> {
291        self.codecs.remove(name)
292    }
293
294    /// List all registered codec names
295    #[must_use]
296    pub fn list_codecs(&self) -> Vec<&String> {
297        self.codecs.keys().collect()
298    }
299
300    /// Get the count of registered codecs
301    #[must_use]
302    pub fn len(&self) -> usize {
303        self.codecs.len()
304    }
305
306    /// Check if the registry is empty
307    #[must_use]
308    pub fn is_empty(&self) -> bool {
309        self.codecs.is_empty()
310    }
311
312    /// Clear all registered codecs
313    pub fn clear(&mut self) {
314        self.codecs.clear();
315    }
316}
317
318impl Default for CodecRegistry {
319    fn default() -> Self {
320        Self::new()
321    }
322}
323
324/// Codec capability information
325#[derive(Debug, Clone)]
326pub struct CodecCapabilities {
327    /// Available codec types
328    pub codec_types: Vec<CodecType>,
329    /// Codec information
330    pub codec_info: HashMap<CodecType, CodecInfo>,
331}
332
333/// Register the AMR variants enabled by feature flags.
334///
335/// Split out of [`CodecCapabilities::get_all`] to keep that function within the
336/// workspace line limit as codecs accumulate.
337#[cfg(any(feature = "amr-nb", feature = "amr-wb"))]
338fn add_amr_capabilities(
339    codec_types: &mut Vec<CodecType>,
340    codec_info: &mut HashMap<CodecType, CodecInfo>,
341) {
342    #[cfg(feature = "amr-nb")]
343    {
344        codec_types.push(CodecType::AmrNb);
345        codec_info.insert(
346            CodecType::AmrNb,
347            CodecInfo {
348                name: "AMR",
349                sample_rate: 8000,
350                channels: 1,
351                bitrate: CodecType::AmrNb.default_bitrate(),
352                frame_size: 160,
353                payload_type: None,
354            },
355        );
356    }
357
358    #[cfg(feature = "amr-wb")]
359    {
360        codec_types.push(CodecType::AmrWb);
361        codec_info.insert(
362            CodecType::AmrWb,
363            CodecInfo {
364                name: "AMR-WB",
365                sample_rate: 16000,
366                channels: 1,
367                bitrate: CodecType::AmrWb.default_bitrate(),
368                frame_size: 320,
369                payload_type: None,
370            },
371        );
372    }
373}
374
375impl CodecCapabilities {
376    /// Get capabilities for all supported codecs
377    #[must_use]
378    pub fn get_all() -> Self {
379        // Both values are populated by feature-gated blocks. In a deliberately
380        // codec-free build they remain empty and therefore need no mutation.
381        #[allow(unused_mut)]
382        let mut codec_types = Vec::new();
383        #[allow(unused_mut)]
384        let mut codec_info = HashMap::new();
385
386        #[cfg(feature = "g711")]
387        {
388            codec_types.push(CodecType::G711Pcmu);
389            codec_types.push(CodecType::G711Pcma);
390
391            codec_info.insert(
392                CodecType::G711Pcmu,
393                CodecInfo {
394                    name: "PCMU",
395                    sample_rate: 8000,
396                    channels: 1,
397                    bitrate: 64000,
398                    frame_size: 160,
399                    payload_type: Some(0),
400                },
401            );
402
403            codec_info.insert(
404                CodecType::G711Pcma,
405                CodecInfo {
406                    name: "PCMA",
407                    sample_rate: 8000,
408                    channels: 1,
409                    bitrate: 64000,
410                    frame_size: 160,
411                    payload_type: Some(8),
412                },
413            );
414        }
415
416        #[cfg(feature = "opus")]
417        {
418            codec_types.push(CodecType::Opus);
419            codec_info.insert(
420                CodecType::Opus,
421                CodecInfo {
422                    name: "opus",
423                    sample_rate: 48000,
424                    channels: 1,
425                    bitrate: 64000,
426                    frame_size: 960,
427                    payload_type: None,
428                },
429            );
430        }
431
432        #[cfg(any(feature = "amr-nb", feature = "amr-wb"))]
433        add_amr_capabilities(&mut codec_types, &mut codec_info);
434
435        #[cfg(feature = "g729")]
436        {
437            codec_types.push(CodecType::G729);
438            codec_types.push(CodecType::G729A);
439            codec_types.push(CodecType::G729BA);
440
441            codec_info.insert(
442                CodecType::G729,
443                CodecInfo {
444                    name: "G729",
445                    sample_rate: 8000,
446                    channels: 1,
447                    bitrate: 8000,
448                    frame_size: 80,
449                    payload_type: Some(18),
450                },
451            );
452            codec_info.insert(
453                CodecType::G729A,
454                CodecInfo {
455                    name: "G729A",
456                    sample_rate: 8000,
457                    channels: 1,
458                    bitrate: 8000,
459                    frame_size: 80,
460                    payload_type: Some(18),
461                },
462            );
463            codec_info.insert(
464                CodecType::G729BA,
465                CodecInfo {
466                    name: "G729BA",
467                    sample_rate: 8000,
468                    channels: 1,
469                    bitrate: 8000,
470                    frame_size: 80,
471                    payload_type: Some(18),
472                },
473            );
474        }
475
476        Self {
477            codec_types,
478            codec_info,
479        }
480    }
481
482    /// Check if a codec type is supported
483    #[must_use]
484    pub fn is_supported(&self, codec_type: CodecType) -> bool {
485        self.codec_types.contains(&codec_type)
486    }
487
488    /// Get information for a specific codec type
489    #[must_use]
490    pub fn get_info(&self, codec_type: CodecType) -> Option<&CodecInfo> {
491        self.codec_info.get(&codec_type)
492    }
493}
494
495#[cfg(test)]
496mod tests {
497    use super::*;
498
499    #[test]
500    fn test_codec_factory_supported_codecs() {
501        let supported = CodecFactory::supported_codecs();
502
503        #[cfg(any(
504            feature = "g711",
505            feature = "g729",
506            feature = "opus",
507            feature = "amr-nb",
508            feature = "amr-wb"
509        ))]
510        assert!(!supported.is_empty());
511
512        #[cfg(not(any(
513            feature = "g711",
514            feature = "g729",
515            feature = "opus",
516            feature = "amr-nb",
517            feature = "amr-wb"
518        )))]
519        assert!(supported.is_empty());
520
521        #[cfg(feature = "g711")]
522        {
523            assert!(supported.contains(&"PCMU"));
524            assert!(supported.contains(&"PCMA"));
525        }
526
527        #[cfg(feature = "amr-nb")]
528        assert!(supported.contains(&"AMR"));
529
530        #[cfg(feature = "amr-wb")]
531        assert!(supported.contains(&"AMR-WB"));
532    }
533
534    #[test]
535    fn test_codec_factory_is_supported() {
536        #[cfg(feature = "g711")]
537        {
538            assert!(CodecFactory::is_supported("PCMU"));
539            assert!(CodecFactory::is_supported("pcmu"));
540            assert!(CodecFactory::is_supported("PCMA"));
541        }
542
543        assert!(!CodecFactory::is_supported("UNSUPPORTED"));
544        assert!(!CodecFactory::is_supported("G722"));
545
546        #[cfg(feature = "opus")]
547        for name in ["opus", "Opus", "OPUS"] {
548            assert!(CodecFactory::is_supported(name));
549        }
550        #[cfg(not(feature = "opus"))]
551        for name in ["opus", "Opus", "OPUS"] {
552            assert!(!CodecFactory::is_supported(name));
553        }
554    }
555
556    #[test]
557    fn test_codec_registry() {
558        let mut registry = CodecRegistry::new();
559        assert!(registry.is_empty());
560        assert_eq!(registry.len(), 0);
561
562        #[cfg(feature = "g711")]
563        {
564            let config = CodecConfig::g711_pcmu();
565            let codec = CodecFactory::create(config).unwrap();
566            registry.register("test_pcmu".to_string(), codec);
567
568            assert_eq!(registry.len(), 1);
569            assert!(!registry.is_empty());
570            assert!(registry.get("test_pcmu").is_some());
571        }
572
573        registry.clear();
574        assert!(registry.is_empty());
575    }
576
577    #[test]
578    fn test_codec_capabilities() {
579        let caps = CodecCapabilities::get_all();
580
581        #[cfg(any(
582            feature = "g711",
583            feature = "g729",
584            feature = "opus",
585            feature = "amr-nb",
586            feature = "amr-wb"
587        ))]
588        {
589            assert!(!caps.codec_types.is_empty());
590            assert!(!caps.codec_info.is_empty());
591        }
592
593        #[cfg(not(any(
594            feature = "g711",
595            feature = "g729",
596            feature = "opus",
597            feature = "amr-nb",
598            feature = "amr-wb"
599        )))]
600        {
601            assert!(caps.codec_types.is_empty());
602            assert!(caps.codec_info.is_empty());
603        }
604
605        #[cfg(feature = "g711")]
606        {
607            assert!(caps.is_supported(CodecType::G711Pcmu));
608            assert!(caps.get_info(CodecType::G711Pcmu).is_some());
609        }
610
611        #[cfg(feature = "amr-nb")]
612        {
613            assert!(caps.is_supported(CodecType::AmrNb));
614            assert_eq!(caps.get_info(CodecType::AmrNb).unwrap().name, "AMR");
615        }
616
617        #[cfg(feature = "amr-wb")]
618        {
619            assert!(caps.is_supported(CodecType::AmrWb));
620            assert_eq!(caps.get_info(CodecType::AmrWb).unwrap().name, "AMR-WB");
621        }
622    }
623
624    #[test]
625    #[cfg(feature = "g711")]
626    fn test_codec_creation() {
627        let config = CodecConfig::g711_pcmu();
628        let codec = CodecFactory::create(config);
629        assert!(codec.is_ok());
630
631        let codec = codec.unwrap();
632        let info = codec.info();
633        assert_eq!(info.name, "PCMU");
634        assert_eq!(info.sample_rate, 8000);
635    }
636
637    #[test]
638    #[cfg(feature = "g711")]
639    fn test_codec_creation_by_name() {
640        let config = CodecConfig::new(CodecType::G711Pcmu);
641        let codec = CodecFactory::create_by_name("PCMU", config.clone());
642        assert!(codec.is_ok());
643
644        let codec = CodecFactory::create_by_name("UNKNOWN", config);
645        assert!(codec.is_err());
646    }
647
648    #[test]
649    #[cfg(feature = "g711")]
650    fn test_codec_creation_by_payload_type() {
651        let config = CodecConfig::new(CodecType::G711Pcmu);
652        let codec = CodecFactory::create_by_payload_type(0, config.clone());
653        assert!(codec.is_ok());
654
655        let codec = CodecFactory::create_by_payload_type(255, config);
656        assert!(codec.is_err());
657    }
658}