Skip to main content

audio_codec/
g729.rs

1use super::{CodecError, Decoder, Encoder, Sample};
2use crate::fade;
3
4const L_FRAME: usize = 80; // 10ms frame at 8kHz
5const L_FRAME_COMPRESSED: usize = 10; // G.729 frame size in bytes
6/// An Annex B SID frame, ending a payload after any speech frames
7/// (RFC 3551 §4.5.6).
8const L_SID: usize = 2;
9
10/// G.729 audio decoder using g729-sys
11pub struct G729Decoder {
12    decoder: g729_sys::Decoder,
13    /// G.729's frame erasure concealment (§4.4) decays on its own but
14    /// settles some 30 dB down rather than at silence; it's faded on top
15    /// like the other codecs' (see [`crate::fade`]).
16    loss: fade::LossFade,
17}
18
19impl Default for G729Decoder {
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25impl G729Decoder {
26    /// Create a new G.729 decoder instance.
27    pub fn new() -> Self {
28        Self {
29            decoder: g729_sys::Decoder::new(),
30            loss: fade::LossFade::default(),
31        }
32    }
33}
34
35unsafe impl Send for G729Decoder {}
36unsafe impl Sync for G729Decoder {}
37
38impl Decoder for G729Decoder {
39    fn decode_into(&mut self, data: &[u8], out: &mut [Sample]) -> Result<usize, CodecError> {
40        if data.is_empty() {
41            return Ok(0);
42        }
43
44        // 10-byte speech frames of 80 samples each, then possibly a SID
45        // frame, which decodes to 80 samples of comfort noise (Annex B)
46        if out.len() < self.max_decode_samples(data.len()) {
47            return Err(CodecError::BufferTooSmall);
48        }
49        let mut written = 0usize;
50        let (frames, rest) = data.as_chunks::<L_FRAME_COMPRESSED>();
51        for frame in frames {
52            // g729-sys: decode(payload, frame_erased, is_sid, rfc3389)
53            let decoded = self.decoder.decode(frame, false, false, false);
54            out[written..written + L_FRAME].copy_from_slice(&decoded);
55            written += L_FRAME;
56        }
57        if rest.len() == L_SID {
58            let decoded = self.decoder.decode(rest, false, true, false);
59            out[written..written + L_FRAME].copy_from_slice(&decoded);
60            written += L_FRAME;
61        }
62        self.loss.end_loss(&mut out[..written], 1, 8000);
63
64        Ok(written)
65    }
66
67    fn max_decode_samples(&self, n_bytes: usize) -> usize {
68        let sid = usize::from(n_bytes % L_FRAME_COMPRESSED == L_SID);
69        (n_bytes / L_FRAME_COMPRESSED + sid) * L_FRAME
70    }
71
72    fn sample_rate(&self) -> u32 {
73        8000 // G.729 operates at 8kHz
74    }
75
76    fn channels(&self) -> u16 {
77        1 // G.729 is always mono
78    }
79
80    /// G.729's concealment is part of the decoder: always on.
81    fn enable_concealment(&mut self) -> bool {
82        true
83    }
84
85    /// Conceals with G.729's frame erasure concealment (§4.4): the last
86    /// spectral envelope and pitch carry on with their gains attenuated,
87    /// the decoder's predictors kept in step, so the packets after the loss
88    /// decode close to what the sender encoded. In DTX, after a SID frame,
89    /// it carries on the comfort noise instead (Annex B). Faded through a
90    /// long loss like the other codecs: full level for 10 ms, silence at
91    /// 60 ms. `samples` must be a multiple of 80 (10 ms); others fail with
92    /// `InvalidInput`.
93    fn conceal_into(&mut self, samples: usize, out: &mut [Sample]) -> Result<usize, CodecError> {
94        if !samples.is_multiple_of(L_FRAME) {
95            return Err(CodecError::InvalidInput);
96        }
97        if out.len() < samples {
98            return Err(CodecError::BufferTooSmall);
99        }
100        for frame in out[..samples].as_chunks_mut::<L_FRAME>().0 {
101            *frame = self.decoder.decode(&[], true, false, false);
102        }
103        self.loss.fade(&mut out[..samples], 1, 8000);
104        Ok(samples)
105    }
106}
107
108/// G.729 audio encoder using g729-sys
109pub struct G729Encoder {
110    encoder: g729_sys::Encoder,
111}
112
113impl Default for G729Encoder {
114    fn default() -> Self {
115        Self::new()
116    }
117}
118
119impl G729Encoder {
120    /// Create a new G.729 encoder instance.
121    ///
122    /// Annex B (VAD/DTX) is disabled by default.
123    pub fn new() -> Self {
124        Self {
125            encoder: g729_sys::Encoder::new(false),
126        }
127    }
128
129    /// Create a new G.729 encoder with explicit VAD/DTX control.
130    pub fn with_vad(enable_vad: bool) -> Self {
131        Self {
132            encoder: g729_sys::Encoder::new(enable_vad),
133        }
134    }
135}
136
137unsafe impl Send for G729Encoder {}
138unsafe impl Sync for G729Encoder {}
139
140impl Encoder for G729Encoder {
141    fn encode_into(&mut self, samples: &[Sample], out: &mut [u8]) -> Result<usize, CodecError> {
142        if samples.is_empty() {
143            return Ok(0);
144        }
145
146        let mut written = 0usize;
147        let mut pos = 0usize;
148        let mut frame_arr = [0i16; L_FRAME];
149        let mut packet = [0u8; L_FRAME_COMPRESSED];
150
151        while pos + L_FRAME <= samples.len() {
152            frame_arr.copy_from_slice(&samples[pos..pos + L_FRAME]);
153            let n = self.encoder.encode_into(&frame_arr, &mut packet);
154            let n = n as usize;
155            if out.len() < written + n {
156                return Err(CodecError::BufferTooSmall);
157            }
158            out[written..written + n].copy_from_slice(&packet[..n]);
159            written += n;
160            pos += L_FRAME;
161        }
162
163        Ok(written)
164    }
165
166    fn max_encode_bytes(&self, n_samples: usize) -> usize {
167        (n_samples / L_FRAME) * L_FRAME_COMPRESSED
168    }
169
170    fn sample_rate(&self) -> u32 {
171        8000 // G.729 operates at 8kHz
172    }
173
174    fn channels(&self) -> u16 {
175        1 // G.729 is always mono
176    }
177}