1#![cfg_attr(not(feature = "std"), no_std)]
2
3extern crate alloc;
7
8pub use error::CodecError;
9
10pub mod error;
11#[cfg(any(feature = "plc", feature = "opus", feature = "g729"))]
12mod fade;
13pub mod g722;
14#[cfg(feature = "g729")]
15pub mod g729;
16#[cfg(feature = "opus")]
17pub mod opus;
18pub mod pcma;
19pub mod pcmu;
20#[cfg(feature = "plc")]
21mod plc;
22pub mod resampler;
24pub mod resampler_fixed;
27pub mod telephone_event;
28
29#[cfg(feature = "std")]
30pub use resampler::Resampler;
31#[cfg(feature = "std")]
32pub use resampler::{BoxedResampler, resample};
33
34pub type Sample = i16;
35
36#[cfg(feature = "std")]
37pub type PcmBuf = Vec<Sample>;
38
39#[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
40pub enum CodecType {
41 PCMU,
42 PCMA,
43 G722,
44 #[cfg(feature = "g729")]
45 G729,
46 #[cfg(feature = "opus")]
47 Opus,
48 TelephoneEvent,
49}
50
51pub trait Decoder: Send + Sync {
58 fn decode_into(&mut self, data: &[u8], out: &mut [Sample]) -> Result<usize, CodecError>;
63
64 fn max_decode_samples(&self, n_bytes: usize) -> usize;
67
68 fn sample_rate(&self) -> u32;
70
71 fn channels(&self) -> u16;
73
74 fn enable_concealment(&mut self) -> bool {
81 false
82 }
83
84 fn conceal_into(&mut self, samples: usize, out: &mut [Sample]) -> Result<usize, CodecError> {
97 let _ = (samples, out);
98 Ok(0)
99 }
100
101 fn recover_into(
111 &mut self,
112 next: &[u8],
113 samples: usize,
114 out: &mut [Sample],
115 ) -> Result<usize, CodecError> {
116 let _ = next;
117 self.conceal_into(samples, out)
118 }
119
120 #[cfg(feature = "std")]
123 fn recover(&mut self, next: &[u8], samples: usize) -> PcmBuf {
124 let mut buf = vec![0i16; samples * self.channels() as usize];
125 match self.recover_into(next, samples, &mut buf) {
126 Ok(n) => {
127 buf.truncate(n);
128 buf
129 }
130 Err(_) => Vec::new(),
131 }
132 }
133
134 #[cfg(feature = "std")]
137 fn conceal(&mut self, samples: usize) -> PcmBuf {
138 let mut buf = vec![0i16; samples * self.channels() as usize];
139 match self.conceal_into(samples, &mut buf) {
140 Ok(n) => {
141 buf.truncate(n);
142 buf
143 }
144 Err(_) => Vec::new(),
145 }
146 }
147
148 #[cfg(feature = "std")]
150 fn decode(&mut self, data: &[u8]) -> PcmBuf {
151 let max = self.max_decode_samples(data.len());
152 let mut buf = vec![0i16; max];
153 match self.decode_into(data, &mut buf) {
154 Ok(n) => {
155 buf.truncate(n);
156 buf
157 }
158 Err(_) => Vec::new(),
159 }
160 }
161}
162
163pub trait Encoder: Send + Sync {
170 fn encode_into(&mut self, samples: &[Sample], out: &mut [u8]) -> Result<usize, CodecError>;
175
176 fn max_encode_bytes(&self, n_samples: usize) -> usize;
179
180 fn sample_rate(&self) -> u32;
182
183 fn channels(&self) -> u16;
185
186 #[cfg(feature = "std")]
188 fn encode(&mut self, samples: &[Sample]) -> Vec<u8> {
189 let max = self.max_encode_bytes(samples.len());
190 let mut buf = vec![0u8; max];
191 match self.encode_into(samples, &mut buf) {
192 Ok(n) => {
193 buf.truncate(n);
194 buf
195 }
196 Err(_) => Vec::new(),
197 }
198 }
199}
200
201#[cfg(feature = "std")]
202pub fn create_decoder(codec: CodecType) -> Box<dyn Decoder> {
203 match codec {
204 CodecType::PCMU => Box::new(pcmu::PcmuDecoder::new()),
205 CodecType::PCMA => Box::new(pcma::PcmaDecoder::new()),
206 CodecType::G722 => Box::new(g722::G722Decoder::new()),
207 #[cfg(feature = "g729")]
208 CodecType::G729 => Box::new(g729::G729Decoder::new()),
209 #[cfg(feature = "opus")]
210 CodecType::Opus => Box::new(opus::OpusDecoder::new_default()),
211 CodecType::TelephoneEvent => Box::new(telephone_event::TelephoneEventDecoder::new()),
212 }
213}
214
215#[cfg(feature = "std")]
216pub fn create_encoder(codec: CodecType) -> Box<dyn Encoder> {
217 match codec {
218 CodecType::PCMU => Box::new(pcmu::PcmuEncoder::new()),
219 CodecType::PCMA => Box::new(pcma::PcmaEncoder::new()),
220 CodecType::G722 => Box::new(g722::G722Encoder::new()),
221 #[cfg(feature = "g729")]
222 CodecType::G729 => Box::new(g729::G729Encoder::new()),
223 #[cfg(feature = "opus")]
224 CodecType::Opus => Box::new(opus::OpusEncoder::new_default()),
225 CodecType::TelephoneEvent => Box::new(telephone_event::TelephoneEventEncoder::new()),
226 }
227}
228
229#[cfg(all(feature = "std", feature = "opus"))]
230pub fn create_opus_encoder(
231 sample_rate: u32,
232 channels: u16,
233 application: opus::OpusApplication,
234) -> Box<dyn Encoder> {
235 Box::new(opus::OpusEncoder::new_with_application(
236 sample_rate,
237 channels,
238 application,
239 ))
240}
241
242#[cfg(all(feature = "std", feature = "opus"))]
243pub fn create_opus_decoder(sample_rate: u32, channels: u16) -> Box<dyn Decoder> {
244 Box::new(opus::OpusDecoder::new(sample_rate, channels))
245}
246
247impl CodecType {
248 pub fn mime_type(&self) -> &str {
249 match self {
250 CodecType::PCMU => "audio/PCMU",
251 CodecType::PCMA => "audio/PCMA",
252 CodecType::G722 => "audio/G722",
253 #[cfg(feature = "g729")]
254 CodecType::G729 => "audio/G729",
255 #[cfg(feature = "opus")]
256 CodecType::Opus => "audio/opus",
257 CodecType::TelephoneEvent => "audio/telephone-event",
258 }
259 }
260 pub fn rtpmap(&self) -> &str {
261 match self {
262 CodecType::PCMU => "PCMU/8000",
263 CodecType::PCMA => "PCMA/8000",
264 CodecType::G722 => "G722/8000",
265 #[cfg(feature = "g729")]
266 CodecType::G729 => "G729/8000",
267 #[cfg(feature = "opus")]
268 CodecType::Opus => "opus/48000/2",
269 CodecType::TelephoneEvent => "telephone-event/8000",
270 }
271 }
272 pub fn fmtp(&self) -> Option<&str> {
273 match self {
274 CodecType::PCMU => None,
275 CodecType::PCMA => None,
276 CodecType::G722 => None,
277 #[cfg(feature = "g729")]
278 CodecType::G729 => None,
279 #[cfg(feature = "opus")]
280 CodecType::Opus => Some("minptime=10;useinbandfec=1;stereo=1;sprop-stereo=1"),
281 CodecType::TelephoneEvent => Some("0-16"),
282 }
283 }
284
285 pub fn clock_rate(&self) -> u32 {
286 match self {
287 CodecType::PCMU => 8000,
288 CodecType::PCMA => 8000,
289 CodecType::G722 => 8000,
290 #[cfg(feature = "g729")]
291 CodecType::G729 => 8000,
292 #[cfg(feature = "opus")]
293 CodecType::Opus => 48000,
294 CodecType::TelephoneEvent => 8000,
295 }
296 }
297
298 pub fn channels(&self) -> u16 {
299 match self {
300 #[cfg(feature = "opus")]
301 CodecType::Opus => 2,
302 _ => 1,
303 }
304 }
305
306 pub fn payload_type(&self) -> u8 {
307 match self {
308 CodecType::PCMU => 0,
309 CodecType::PCMA => 8,
310 CodecType::G722 => 9,
311 #[cfg(feature = "g729")]
312 CodecType::G729 => 18,
313 #[cfg(feature = "opus")]
314 CodecType::Opus => 111,
315 CodecType::TelephoneEvent => 101,
316 }
317 }
318 pub fn samplerate(&self) -> u32 {
319 match self {
320 CodecType::PCMU => 8000,
321 CodecType::PCMA => 8000,
322 CodecType::G722 => 16000,
323 #[cfg(feature = "g729")]
324 CodecType::G729 => 8000,
325 #[cfg(feature = "opus")]
326 CodecType::Opus => 48000,
327 CodecType::TelephoneEvent => 8000,
328 }
329 }
330 pub fn is_audio(&self) -> bool {
331 match self {
332 CodecType::PCMU | CodecType::PCMA | CodecType::G722 => true,
333 #[cfg(feature = "g729")]
334 CodecType::G729 => true,
335 #[cfg(feature = "opus")]
336 CodecType::Opus => true,
337 _ => false,
338 }
339 }
340
341 pub fn is_silence_frame(&self, payload: &[u8]) -> bool {
354 match self {
355 #[cfg(feature = "opus")]
356 CodecType::Opus => !payload.is_empty() && payload.len() <= 2,
357 #[cfg(feature = "g729")]
358 CodecType::G729 => payload.len() % 10 == 2,
359 _ => {
360 let _ = payload;
361 false
362 }
363 }
364 }
365
366 pub fn is_dynamic(&self) -> bool {
367 match self {
368 #[cfg(feature = "opus")]
369 CodecType::Opus => true,
370 CodecType::TelephoneEvent => true,
371 _ => false,
372 }
373 }
374}
375
376impl TryFrom<u8> for CodecType {
377 type Error = CodecError;
378
379 fn try_from(value: u8) -> Result<Self, Self::Error> {
380 match value {
381 0 => Ok(CodecType::PCMU),
382 8 => Ok(CodecType::PCMA),
383 9 => Ok(CodecType::G722),
384 #[cfg(feature = "g729")]
385 18 => Ok(CodecType::G729), 101 => Ok(CodecType::TelephoneEvent),
388 #[cfg(feature = "opus")]
389 111 => Ok(CodecType::Opus), _ => Err(CodecError::InvalidCodecType),
391 }
392 }
393}
394
395impl TryFrom<&str> for CodecType {
396 type Error = CodecError;
397
398 fn try_from(name: &str) -> Result<Self, Self::Error> {
399 let b = name.as_bytes();
400 if b.eq_ignore_ascii_case(b"pcmu") || b.eq_ignore_ascii_case(b"ulaw") {
401 Ok(CodecType::PCMU)
402 } else if b.eq_ignore_ascii_case(b"pcma") || b.eq_ignore_ascii_case(b"alaw") {
403 Ok(CodecType::PCMA)
404 } else if b.eq_ignore_ascii_case(b"g722") {
405 Ok(CodecType::G722)
406 } else if cfg!(feature = "g729") && b.eq_ignore_ascii_case(b"g729") {
407 #[cfg(feature = "g729")]
408 {
409 Ok(CodecType::G729)
410 }
411 #[cfg(not(feature = "g729"))]
412 {
413 Err(CodecError::InvalidCodecName)
414 }
415 } else if cfg!(feature = "opus") && b.eq_ignore_ascii_case(b"opus") {
416 #[cfg(feature = "opus")]
417 {
418 Ok(CodecType::Opus)
419 }
420 #[cfg(not(feature = "opus"))]
421 {
422 Err(CodecError::InvalidCodecName)
423 }
424 } else if b.eq_ignore_ascii_case(b"telephone-event") {
425 Ok(CodecType::TelephoneEvent)
426 } else {
427 Err(CodecError::InvalidCodecName)
428 }
429 }
430}
431
432pub fn samples_to_bytes_into(samples: &[Sample], out: &mut [u8]) -> Result<usize, CodecError> {
441 let needed = core::mem::size_of_val(samples);
442 if out.len() < needed {
443 return Err(CodecError::BufferTooSmall);
444 }
445 if samples.is_empty() {
446 return Ok(0);
447 }
448 let dst_aligned = out
453 .as_mut_ptr()
454 .addr()
455 .is_multiple_of(core::mem::align_of::<Sample>());
456 #[cfg(target_endian = "little")]
457 if dst_aligned {
458 let dst = unsafe {
462 core::slice::from_raw_parts_mut(out.as_mut_ptr() as *mut Sample, samples.len())
463 };
464 dst.copy_from_slice(samples);
465 return Ok(needed);
466 }
467 for (i, s) in samples.iter().enumerate() {
468 let b = s.to_le_bytes();
469 out[2 * i] = b[0];
470 out[2 * i + 1] = b[1];
471 }
472 Ok(needed)
473}
474
475pub fn bytes_to_samples_into(u8_data: &[u8], out: &mut [Sample]) -> Result<usize, CodecError> {
480 let n = u8_data.len() / core::mem::size_of::<Sample>();
481 if out.len() < n {
482 return Err(CodecError::BufferTooSmall);
483 }
484 if n == 0 {
485 return Ok(0);
486 }
487 let src_aligned = u8_data
490 .as_ptr()
491 .addr()
492 .is_multiple_of(core::mem::align_of::<Sample>());
493 #[cfg(target_endian = "little")]
494 if src_aligned {
495 let src = unsafe { core::slice::from_raw_parts(u8_data.as_ptr() as *const Sample, n) };
497 out[..n].copy_from_slice(src);
498 return Ok(n);
499 }
500 for (i, chunk) in u8_data.chunks_exact(2).enumerate() {
501 out[i] = (chunk[0] as i16) | ((chunk[1] as i16) << 8);
502 }
503 Ok(n)
504}
505
506#[cfg(feature = "std")]
507pub fn samples_to_bytes(samples: &[Sample]) -> Vec<u8> {
508 let mut out = vec![0u8; core::mem::size_of_val(samples)];
509 let _ = samples_to_bytes_into(samples, &mut out);
510 out
511}
512
513#[cfg(feature = "std")]
514pub fn bytes_to_samples(u8_data: &[u8]) -> PcmBuf {
515 let n = u8_data.len() / core::mem::size_of::<Sample>();
516 let mut out = vec![0i16; n];
517 let _ = bytes_to_samples_into(u8_data, &mut out);
518 out
519}