Skip to main content

codec_core/codecs/g711/
mod.rs

1//! G.711 Audio Codec Implementation
2//!
3//! This module implements the G.711 codec with both μ-law (PCMU) and A-law (PCMA)
4//! variants. G.711 is the standard codec for telephony systems.
5//!
6//! ## Features
7//!
8//! - ITU-T G.711 compliant implementation
9//! - Both A-law and μ-law encoding/decoding
10//! - Simple single-sample functions
11//! - Lookup table optimized for performance
12//!
13//! ## Usage
14//!
15//! ### Direct Function Calls
16//!
17//! ```rust
18//! use codec_core::codecs::g711::{alaw_compress, alaw_expand, ulaw_compress, ulaw_expand};
19//!
20//! // Single sample processing
21//! let sample = 1024i16;
22//! let alaw_encoded = alaw_compress(sample);
23//! let alaw_decoded = alaw_expand(alaw_encoded);
24//!
25//! let ulaw_encoded = ulaw_compress(sample);
26//! let ulaw_decoded = ulaw_expand(ulaw_encoded);
27//! ```
28//!
29//! ### Processing Multiple Samples
30//!
31//! ```rust
32//! use codec_core::codecs::g711::{alaw_compress, alaw_expand};
33//!
34//! let samples = vec![0i16, 100, -100, 1000, -1000];
35//! let encoded: Vec<u8> = samples.iter().map(|&s| alaw_compress(s)).collect();
36//! let decoded: Vec<i16> = encoded.iter().map(|&e| alaw_expand(e)).collect();
37//! ```
38//!
39//! ### Using the `G711Codec` Struct
40//!
41//! ```rust
42//! use codec_core::codecs::g711::{G711Codec, G711Variant};
43//! use codec_core::types::{AudioCodec, CodecConfig, CodecType, SampleRate};
44//!
45//! // Create μ-law codec
46//! let config = CodecConfig::new(CodecType::G711Pcmu)
47//!     .with_sample_rate(SampleRate::Rate8000)
48//!     .with_channels(1);
49//! let mut codec = G711Codec::new_pcmu(config)?;
50//!
51//! // Or create A-law codec directly
52//! let mut alaw_codec = G711Codec::new(G711Variant::ALaw);
53//!
54//! // Encode/decode
55//! let samples = vec![0i16; 160]; // 20ms at 8kHz
56//! let encoded = codec.encode(&samples)?;
57//! let decoded = codec.decode(&encoded)?;
58//! # Ok::<(), Box<dyn std::error::Error>>(())
59//! ```
60
61use crate::error::CodecError;
62use crate::utils::tables::{
63    decode_alaw_table, decode_mulaw_table, encode_alaw_table, encode_mulaw_table,
64};
65
66use super::g711_reference as reference;
67
68#[cfg(test)]
69pub mod tests;
70
71// Re-export the core functions
72pub use reference::{alaw_compress, alaw_expand, ulaw_compress, ulaw_expand};
73
74/// G.711 codec implementation
75pub struct G711Codec {
76    variant: G711Variant,
77    frame_size: usize,
78}
79
80/// G.711 codec variants
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum G711Variant {
83    /// A-law (PCMA) - Used primarily in Europe
84    ALaw,
85    /// μ-law (PCMU) - Used primarily in North America and Japan
86    MuLaw,
87}
88
89impl G711Codec {
90    /// Create a new G.711 codec with the specified variant
91    #[must_use]
92    #[allow(clippy::needless_pass_by_value)]
93    pub const fn new(variant: G711Variant) -> Self {
94        Self {
95            variant,
96            frame_size: 160, // Default 20ms at 8kHz
97        }
98    }
99
100    /// Create a new G.711 codec with configuration
101    ///
102    /// # Errors
103    ///
104    /// Returns an error when the configuration uses a sample rate, channel
105    /// count, or frame duration unsupported by G.711.
106    #[allow(
107        clippy::cast_possible_truncation,
108        clippy::cast_sign_loss,
109        clippy::needless_pass_by_value
110    )]
111    pub fn new_with_config(
112        variant: G711Variant,
113        config: crate::types::CodecConfig,
114    ) -> Result<Self, CodecError> {
115        // Validate sample rate
116        if config.sample_rate.hz() != 8000 {
117            return Err(CodecError::InvalidSampleRate {
118                rate: config.sample_rate.hz(),
119                supported: vec![8000],
120            });
121        }
122
123        // Validate channels
124        if config.channels != 1 {
125            return Err(CodecError::InvalidChannelCount {
126                channels: config.channels,
127                supported: vec![1],
128            });
129        }
130
131        // Calculate frame size from config
132        let frame_size = config.frame_size_ms.map_or(160, |frame_ms| {
133            let samples_per_ms = 8000.0 / 1000.0; // 8 samples per ms at 8kHz
134            (samples_per_ms * frame_ms) as usize
135        });
136
137        // Validate frame size
138        let valid_sizes = [80, 160, 240, 320];
139        if !valid_sizes.contains(&frame_size) {
140            return Err(CodecError::InvalidFrameSize {
141                expected: 160,
142                actual: frame_size,
143            });
144        }
145
146        Ok(Self {
147            variant,
148            frame_size,
149        })
150    }
151
152    /// Create a new G.711 μ-law (PCMU) codec
153    ///
154    /// # Errors
155    ///
156    /// Returns an error when `config` is not a supported G.711 configuration.
157    pub fn new_pcmu(config: crate::types::CodecConfig) -> Result<Self, CodecError> {
158        Self::new_with_config(G711Variant::MuLaw, config)
159    }
160
161    /// Create a new G.711 A-law (PCMA) codec
162    ///
163    /// # Errors
164    ///
165    /// Returns an error when `config` is not a supported G.711 configuration.
166    pub fn new_pcma(config: crate::types::CodecConfig) -> Result<Self, CodecError> {
167        Self::new_with_config(G711Variant::ALaw, config)
168    }
169
170    /// Get the codec variant
171    #[must_use]
172    pub const fn variant(&self) -> G711Variant {
173        self.variant
174    }
175
176    /// Compress samples using the configured variant
177    ///
178    /// # Errors
179    ///
180    /// This implementation is infallible; the result type is retained for API
181    /// compatibility with other codecs.
182    pub fn compress(&self, samples: &[i16]) -> Result<Vec<u8>, CodecError> {
183        match self.variant {
184            G711Variant::ALaw => Ok(samples
185                .iter()
186                .map(|&sample| encode_alaw_table(sample))
187                .collect()),
188            G711Variant::MuLaw => Ok(samples
189                .iter()
190                .map(|&sample| encode_mulaw_table(sample))
191                .collect()),
192        }
193    }
194
195    /// Expand samples using the configured variant
196    ///
197    /// # Errors
198    ///
199    /// This implementation is infallible; the result type is retained for API
200    /// compatibility with other codecs.
201    pub fn expand(&self, compressed: &[u8]) -> Result<Vec<i16>, CodecError> {
202        match self.variant {
203            G711Variant::ALaw => Ok(compressed
204                .iter()
205                .map(|&sample| decode_alaw_table(sample))
206                .collect()),
207            G711Variant::MuLaw => Ok(compressed
208                .iter()
209                .map(|&sample| decode_mulaw_table(sample))
210                .collect()),
211        }
212    }
213
214    /// Compress samples using A-law
215    ///
216    /// # Errors
217    ///
218    /// This implementation is infallible; the result type is retained for API
219    /// compatibility.
220    pub fn compress_alaw(&self, samples: &[i16]) -> Result<Vec<u8>, CodecError> {
221        Ok(samples
222            .iter()
223            .map(|&sample| encode_alaw_table(sample))
224            .collect())
225    }
226
227    /// Expand A-law samples
228    ///
229    /// # Errors
230    ///
231    /// This implementation is infallible; the result type is retained for API
232    /// compatibility.
233    pub fn expand_alaw(&self, compressed: &[u8]) -> Result<Vec<i16>, CodecError> {
234        Ok(compressed
235            .iter()
236            .map(|&sample| decode_alaw_table(sample))
237            .collect())
238    }
239
240    /// Compress samples using μ-law
241    ///
242    /// # Errors
243    ///
244    /// This implementation is infallible; the result type is retained for API
245    /// compatibility.
246    pub fn compress_ulaw(&self, samples: &[i16]) -> Result<Vec<u8>, CodecError> {
247        Ok(samples
248            .iter()
249            .map(|&sample| encode_mulaw_table(sample))
250            .collect())
251    }
252
253    /// Expand μ-law samples
254    ///
255    /// # Errors
256    ///
257    /// This implementation is infallible; the result type is retained for API
258    /// compatibility.
259    pub fn expand_ulaw(&self, compressed: &[u8]) -> Result<Vec<i16>, CodecError> {
260        Ok(compressed
261            .iter()
262            .map(|&sample| decode_mulaw_table(sample))
263            .collect())
264    }
265}
266
267// Implement AudioCodec trait for backward compatibility
268impl crate::types::AudioCodec for G711Codec {
269    fn encode(&mut self, samples: &[i16]) -> Result<Vec<u8>, CodecError> {
270        self.compress(samples)
271    }
272
273    fn decode(&mut self, data: &[u8]) -> Result<Vec<i16>, CodecError> {
274        self.expand(data)
275    }
276
277    fn info(&self) -> crate::types::CodecInfo {
278        let (name, payload_type) = match self.variant {
279            G711Variant::ALaw => ("PCMA", Some(8)),
280            G711Variant::MuLaw => ("PCMU", Some(0)),
281        };
282
283        crate::types::CodecInfo {
284            name,
285            sample_rate: 8000,
286            channels: 1,
287            bitrate: 64000,
288            frame_size: self.frame_size,
289            payload_type,
290        }
291    }
292
293    fn reset(&mut self) -> Result<(), CodecError> {
294        // G.711 is stateless, no reset needed
295        Ok(())
296    }
297
298    fn frame_size(&self) -> usize {
299        self.frame_size
300    }
301
302    fn supports_variable_frame_size(&self) -> bool {
303        true
304    }
305}
306
307// Implement AudioCodecExt trait for additional functionality
308impl crate::types::AudioCodecExt for G711Codec {
309    fn encode_to_buffer(
310        &mut self,
311        samples: &[i16],
312        output: &mut [u8],
313    ) -> Result<usize, CodecError> {
314        if output.len() < samples.len() {
315            return Err(CodecError::BufferTooSmall {
316                needed: samples.len(),
317                actual: output.len(),
318            });
319        }
320
321        match self.variant {
322            G711Variant::ALaw => {
323                for (byte, &sample) in output.iter_mut().zip(samples) {
324                    *byte = encode_alaw_table(sample);
325                }
326            }
327            G711Variant::MuLaw => {
328                for (byte, &sample) in output.iter_mut().zip(samples) {
329                    *byte = encode_mulaw_table(sample);
330                }
331            }
332        }
333
334        Ok(samples.len())
335    }
336
337    fn decode_to_buffer(&mut self, data: &[u8], output: &mut [i16]) -> Result<usize, CodecError> {
338        if output.len() < data.len() {
339            return Err(CodecError::BufferTooSmall {
340                needed: data.len(),
341                actual: output.len(),
342            });
343        }
344
345        match self.variant {
346            G711Variant::ALaw => {
347                for (sample, &encoded) in output.iter_mut().zip(data) {
348                    *sample = decode_alaw_table(encoded);
349                }
350            }
351            G711Variant::MuLaw => {
352                for (sample, &encoded) in output.iter_mut().zip(data) {
353                    *sample = decode_mulaw_table(encoded);
354                }
355            }
356        }
357
358        Ok(data.len())
359    }
360
361    fn max_encoded_size(&self, input_samples: usize) -> usize {
362        input_samples // G.711 has 1:1 sample to byte ratio
363    }
364
365    fn max_decoded_size(&self, input_bytes: usize) -> usize {
366        input_bytes // G.711 has 1:1 byte to sample ratio
367    }
368}
369
370/// Initialize G.711 lookup tables (stub for compatibility)
371pub const fn init_tables() {
372    // No initialization needed with our implementation
373}