1use bytes::Bytes;
4
5use crate::error::{AudioError, AudioResult};
6use crate::frame::AudioFrame;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10pub enum AudioFormat {
11 #[default]
13 Pcm16,
14 Opus,
16 Mp3,
18 Wav,
20 Flac,
22 Ogg,
24}
25
26impl AudioFormat {
27 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 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
56pub fn decode(data: &[u8], format: AudioFormat) -> AudioResult<AudioFrame> {
61 match format {
62 AudioFormat::Pcm16 => {
63 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
71pub 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
83fn 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 buf.extend_from_slice(b"RIFF");
96 buf.extend_from_slice(&file_size.to_le_bytes());
97 buf.extend_from_slice(b"WAVE");
98 buf.extend_from_slice(b"fmt ");
100 buf.extend_from_slice(&16u32.to_le_bytes()); buf.extend_from_slice(&1u16.to_le_bytes()); 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 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
115fn 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 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 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 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}