Skip to main content

adk_audio/
codec.rs

1//! Audio codec conversion between PCM16 internal format and external formats.
2
3use bytes::Bytes;
4
5use crate::error::{AudioError, AudioResult};
6use crate::frame::AudioFrame;
7
8/// Supported audio formats for encode/decode at transport edges.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10pub enum AudioFormat {
11    /// Raw PCM-16 LE (internal format, no header).
12    #[default]
13    Pcm16,
14    /// Opus codec (not yet implemented).
15    Opus,
16    /// MP3 format.
17    Mp3,
18    /// WAV (RIFF) format.
19    Wav,
20    /// FLAC lossless format.
21    Flac,
22    /// Ogg container format.
23    Ogg,
24}
25
26impl AudioFormat {
27    /// Returns `true` if this format has a working `encode()` implementation.
28    ///
29    /// Currently only `Pcm16` and `Wav` support encoding.
30    pub fn supports_encode(&self) -> bool {
31        match self {
32            AudioFormat::Pcm16 => true,
33            AudioFormat::Wav => true,
34            AudioFormat::Opus => false,
35            AudioFormat::Mp3 => false,
36            AudioFormat::Flac => false,
37            AudioFormat::Ogg => false,
38        }
39    }
40
41    /// Returns `true` if this format has a working `decode()` implementation.
42    ///
43    /// Currently only `Pcm16` and `Wav` support decoding.
44    pub fn supports_decode(&self) -> bool {
45        match self {
46            AudioFormat::Pcm16 => true,
47            AudioFormat::Wav => true,
48            AudioFormat::Opus => false,
49            AudioFormat::Mp3 => false,
50            AudioFormat::Flac => false,
51            AudioFormat::Ogg => false,
52        }
53    }
54}
55
56/// Decode encoded bytes into a PCM16 `AudioFrame`.
57///
58/// Currently supports WAV and raw PCM16. Other formats return
59/// `AudioError::Codec`.
60pub fn decode(data: &[u8], format: AudioFormat) -> AudioResult<AudioFrame> {
61    match format {
62        AudioFormat::Pcm16 => {
63            // Raw PCM16 — assume 16kHz mono (caller should know the format)
64            Ok(AudioFrame::new(Bytes::copy_from_slice(data), 16000, 1))
65        }
66        AudioFormat::Wav => decode_wav(data),
67        _ => Err(AudioError::Codec(format!("decoding {format:?} is not yet supported"))),
68    }
69}
70
71/// Encode an `AudioFrame` to the target format.
72///
73/// Currently supports WAV and raw PCM16. Other formats return
74/// `AudioError::Codec`.
75pub fn encode(frame: &AudioFrame, format: AudioFormat) -> AudioResult<Bytes> {
76    match format {
77        AudioFormat::Pcm16 => Ok(frame.data.clone()),
78        AudioFormat::Wav => encode_wav(frame),
79        _ => Err(AudioError::Codec(format!("encoding {format:?} is not yet supported"))),
80    }
81}
82
83/// Encode an `AudioFrame` as a RIFF WAV file.
84fn encode_wav(frame: &AudioFrame) -> AudioResult<Bytes> {
85    let data_len = frame.data.len() as u32;
86    let channels = frame.channels as u16;
87    let sample_rate = frame.sample_rate;
88    let bits_per_sample: u16 = 16;
89    let byte_rate = sample_rate * u32::from(channels) * u32::from(bits_per_sample) / 8;
90    let block_align = channels * bits_per_sample / 8;
91    let file_size = 36 + data_len;
92
93    let mut buf = Vec::with_capacity(44 + frame.data.len());
94    // RIFF header
95    buf.extend_from_slice(b"RIFF");
96    buf.extend_from_slice(&file_size.to_le_bytes());
97    buf.extend_from_slice(b"WAVE");
98    // fmt sub-chunk
99    buf.extend_from_slice(b"fmt ");
100    buf.extend_from_slice(&16u32.to_le_bytes()); // sub-chunk size
101    buf.extend_from_slice(&1u16.to_le_bytes()); // PCM format
102    buf.extend_from_slice(&channels.to_le_bytes());
103    buf.extend_from_slice(&sample_rate.to_le_bytes());
104    buf.extend_from_slice(&byte_rate.to_le_bytes());
105    buf.extend_from_slice(&block_align.to_le_bytes());
106    buf.extend_from_slice(&bits_per_sample.to_le_bytes());
107    // data sub-chunk
108    buf.extend_from_slice(b"data");
109    buf.extend_from_slice(&data_len.to_le_bytes());
110    buf.extend_from_slice(&frame.data);
111
112    Ok(Bytes::from(buf))
113}
114
115/// Decode a RIFF WAV file into an `AudioFrame`.
116///
117/// Walks the RIFF chunks for `fmt ` and `data` rather than reading fixed offsets, so a file
118/// with other chunks first — CoreAudio writes `JUNK` before `fmt ` and `FLLR` before `data`
119/// — decodes like a canonical 44-byte header.
120fn decode_wav(data: &[u8]) -> AudioResult<AudioFrame> {
121    if data.len() < 12 {
122        return Err(AudioError::Codec("WAV data too short for header".into()));
123    }
124    if &data[0..4] != b"RIFF" || &data[8..12] != b"WAVE" {
125        return Err(AudioError::Codec("invalid WAV header".into()));
126    }
127    // (sample_rate, channels) from the `fmt ` chunk, which precedes `data`.
128    let mut format = None;
129    let mut offset = 12usize;
130    while let Some(header) = offset.checked_add(8).and_then(|end| data.get(offset..end)) {
131        let chunk_size = u32::from_le_bytes([header[4], header[5], header[6], header[7]]) as usize;
132        let start = offset + 8;
133        // A streamed WAV can declare a placeholder size; the bytes present count.
134        let end = start.saturating_add(chunk_size).min(data.len());
135        let body = &data[start..end];
136        match &header[0..4] {
137            b"fmt " => {
138                if body.len() < 16 {
139                    return Err(AudioError::Codec(format!(
140                        "WAV fmt chunk too short: {} bytes, expected at least 16",
141                        body.len()
142                    )));
143                }
144                let channels = u16::from_le_bytes([body[2], body[3]]);
145                let sample_rate = u32::from_le_bytes([body[4], body[5], body[6], body[7]]);
146                let bits_per_sample = u16::from_le_bytes([body[14], body[15]]);
147                if bits_per_sample != 16 {
148                    return Err(AudioError::Codec(format!(
149                        "unsupported bits per sample: {bits_per_sample}, expected 16"
150                    )));
151                }
152                let channels = u8::try_from(channels).ok().filter(|&c| c > 0).ok_or_else(|| {
153                    AudioError::Codec(format!(
154                        "unsupported channel count: {channels}, expected 1 to 255"
155                    ))
156                })?;
157                format = Some((sample_rate, channels));
158            }
159            b"data" => {
160                let (sample_rate, channels) = format.ok_or_else(|| {
161                    AudioError::Codec("WAV data chunk comes before the fmt chunk".into())
162                })?;
163                return Ok(AudioFrame::new(Bytes::copy_from_slice(body), sample_rate, channels));
164            }
165            _ => {}
166        }
167        // Chunks are padded to an even length.
168        offset = start.saturating_add(chunk_size).saturating_add(chunk_size % 2);
169    }
170    Err(AudioError::Codec(
171        if format.is_some() { "WAV data chunk not found" } else { "WAV fmt chunk not found" }
172            .into(),
173    ))
174}