| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use ec_core::error::{Error, Result}; |
| 11 | use ec_core::frame::{Frame, SampleFormat}; |
| 12 | use ec_core::packet::Packet; |
| 13 | use ec_core::registry::{CodecId, CodecParameters, Decoder}; |
| 14 | |
| 15 | |
| 16 | enum Inner { |
| 17 | Flac(Box<ec_flac::FlacDecoder>), |
| 18 | Mp3(Box<ec_mp3::Mp3Decoder>), |
| 19 | Vorbis(Box<ec_vorbis::VorbisDecoder>), |
| 20 | Ac3(Box<ec_ac3::Ac3Decoder>), |
| 21 | Aac(Box<ec_aac::AacDecoder>), |
| 22 | Alac(Box<ec_alac::AlacDecoder>), |
| 23 | Opus(Box<ec_opus::MultistreamDecoder>), |
| 24 | |
| 25 | Pcm(CodecId), |
| 26 | } |
| 27 | |
| 28 | |
| 29 | pub struct AudioDecoder { |
| 30 | inner: Inner, |
| 31 | codec: CodecId, |
| 32 | channels: usize, |
| 33 | sample_rate: u32, |
| 34 | } |
| 35 | |
| 36 | impl std::fmt::Debug for AudioDecoder { |
| 37 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 38 | f.debug_struct("AudioDecoder") |
| 39 | .field("codec", &self.codec.name()) |
| 40 | .field("channels", &self.channels) |
| 41 | .field("sample_rate", &self.sample_rate) |
| 42 | .finish() |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | impl AudioDecoder { |
| 47 | |
| 48 | pub fn new(params: &CodecParameters) -> Result<AudioDecoder> { |
| 49 | let audio = params |
| 50 | .audio() |
| 51 | .ok_or_else(|| Error::corrupt("a decoder was asked for on a non-audio stream"))?; |
| 52 | let channels = audio.layout.channel_count().max(1); |
| 53 | let sample_rate = audio.sample_rate; |
| 54 | let extradata = params.extradata.as_deref(); |
| 55 | let inner = match params.codec { |
| 56 | CodecId::Flac => { |
| 57 | let mut params = params.clone(); |
| 58 | params.extradata = flac_stream_info(extradata.unwrap_or_default()) |
| 59 | .map(ec_core::packet::Buf::copy_from_slice); |
| 60 | Inner::Flac(Box::new(ec_flac::FlacDecoder::new(params)?)) |
| 61 | } |
| 62 | CodecId::Mp3 => Inner::Mp3(Box::new(ec_mp3::Mp3Decoder::new(params.clone())?)), |
| 63 | CodecId::Vorbis => { |
| 64 | let data = extradata.ok_or_else(|| { |
| 65 | Error::corrupt("a Vorbis stream with no header triplet in its extradata") |
| 66 | })?; |
| 67 | let headers = ec_ogg::xiph_unlace(data)?; |
| 68 | Inner::Vorbis(Box::new(ec_vorbis::VorbisDecoder::new(&headers)?)) |
| 69 | } |
| 70 | CodecId::Ac3 | CodecId::EAc3 => Inner::Ac3(Box::new(ec_ac3::Ac3Decoder::new())), |
| 71 | CodecId::Aac => { |
| 72 | let decoder = match extradata { |
| 73 | Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)?, |
| 74 | |
| 75 | None => ec_aac::AacDecoder::new(), |
| 76 | }; |
| 77 | Inner::Aac(Box::new(decoder)) |
| 78 | } |
| 79 | CodecId::Alac => Inner::Alac(Box::new(ec_alac::AlacDecoder::from_parameters( |
| 80 | params.clone(), |
| 81 | )?)), |
| 82 | CodecId::Opus => { |
| 83 | let head = extradata.unwrap_or_default(); |
| 84 | let (streams, coupled, mapping) = opus_layout(head, channels)?; |
| 85 | |
| 86 | |
| 87 | Inner::Opus(Box::new(ec_opus::MultistreamDecoder::try_with_rate( |
| 88 | 48_000, streams, coupled, &mapping, |
| 89 | )?)) |
| 90 | } |
| 91 | codec if is_pcm(codec) => Inner::Pcm(codec), |
| 92 | codec => { |
| 93 | return Err(Error::unsupported( |
| 94 | format!("the {} track", codec.name()), |
| 95 | match codec.media_type() { |
| 96 | ec_core::MediaType::Audio => { |
| 97 | "no decoder for it exists in this family (yet)" |
| 98 | } |
| 99 | _ => "this is an audio probe; picture and subtitles decode elsewhere", |
| 100 | }, |
| 101 | )); |
| 102 | } |
| 103 | }; |
| 104 | Ok(AudioDecoder { |
| 105 | inner, |
| 106 | codec: params.codec, |
| 107 | channels, |
| 108 | sample_rate: match params.codec { |
| 109 | CodecId::Opus => 48_000, |
| 110 | _ => sample_rate, |
| 111 | }, |
| 112 | }) |
| 113 | } |
| 114 | |
| 115 | |
| 116 | pub fn codec(&self) -> CodecId { |
| 117 | self.codec |
| 118 | } |
| 119 | |
| 120 | |
| 121 | pub fn channels(&self) -> usize { |
| 122 | self.channels |
| 123 | } |
| 124 | |
| 125 | |
| 126 | pub fn sample_rate(&self) -> u32 { |
| 127 | self.sample_rate |
| 128 | } |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | pub fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> Result<()> { |
| 136 | out.clear(); |
| 137 | match &mut self.inner { |
| 138 | Inner::Flac(d) => drain(d.as_mut(), packet, out)?, |
| 139 | Inner::Mp3(d) => drain(d.as_mut(), packet, out)?, |
| 140 | Inner::Vorbis(d) => drain(d.as_mut(), packet, out)?, |
| 141 | Inner::Ac3(d) => drain(d.as_mut(), packet, out)?, |
| 142 | Inner::Aac(d) => { |
| 143 | let audio = d.decode(&packet.data, packet.pts)?; |
| 144 | self.channels = usize::from(audio.channels).max(1); |
| 145 | if audio.sample_rate > 0 { |
| 146 | self.sample_rate = audio.sample_rate; |
| 147 | } |
| 148 | out.extend_from_slice(&audio.samples); |
| 149 | } |
| 150 | Inner::Alac(d) => { |
| 151 | let scale = match d.cookie().sample_format() { |
| 152 | SampleFormat::S16 => 1.0 / 32768.0, |
| 153 | _ => 1.0 / 2147483648.0, |
| 154 | }; |
| 155 | out.extend(d.decode(&packet.data)?.iter().map(|&s| s as f32 * scale)); |
| 156 | } |
| 157 | Inner::Opus(d) => { |
| 158 | let samples = d.decode_packet(&packet.data)?; |
| 159 | out.extend_from_slice(&samples); |
| 160 | } |
| 161 | Inner::Pcm(codec) => pcm(*codec, &packet.data, out), |
| 162 | } |
| 163 | Ok(()) |
| 164 | } |
| 165 | |
| 166 | |
| 167 | pub fn reset(&mut self) { |
| 168 | match &mut self.inner { |
| 169 | Inner::Flac(d) => d.reset(), |
| 170 | Inner::Mp3(d) => d.reset(), |
| 171 | Inner::Vorbis(d) => d.reset(), |
| 172 | Inner::Ac3(d) => d.reset(), |
| 173 | Inner::Aac(d) => **d = ec_aac::AacDecoder::new(), |
| 174 | Inner::Alac(d) => d.reset(), |
| 175 | Inner::Opus(d) => d.reset(), |
| 176 | Inner::Pcm(_) => {} |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | fn flac_stream_info(data: &[u8]) -> Option<&[u8]> { |
| 190 | if data.len() == 34 { |
| 191 | return Some(data); |
| 192 | } |
| 193 | for at in 0..data.len().saturating_sub(38).min(16) { |
| 194 | let head = &data[at..at + 4]; |
| 195 | let len = u32::from_be_bytes([0, head[1], head[2], head[3]]); |
| 196 | if head[0] & 0x7f == 0 && len == 34 { |
| 197 | return data.get(at + 4..at + 38); |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | |
| 202 | None |
| 203 | } |
| 204 | |
| 205 | |
| 206 | fn is_pcm(codec: CodecId) -> bool { |
| 207 | matches!( |
| 208 | codec, |
| 209 | CodecId::PcmU8 |
| 210 | | CodecId::PcmS16Le |
| 211 | | CodecId::PcmS16Be |
| 212 | | CodecId::PcmS24Le |
| 213 | | CodecId::PcmS32Le |
| 214 | | CodecId::PcmF32Le |
| 215 | ) |
| 216 | } |
| 217 | |
| 218 | |
| 219 | |
| 220 | fn drain(decoder: &mut dyn Decoder, packet: &Packet, out: &mut Vec<f32>) -> Result<()> { |
| 221 | decoder.send_packet(packet)?; |
| 222 | loop { |
| 223 | match decoder.receive_frame() { |
| 224 | Ok(Frame::Audio(frame)) => interleave(&frame, out), |
| 225 | Ok(Frame::Video(_)) => { |
| 226 | return Err(Error::corrupt("an audio decoder produced a picture")); |
| 227 | } |
| 228 | Err(e) if e.is_need_more() || e.is_eof() => return Ok(()), |
| 229 | Err(e) => return Err(e), |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | |
| 235 | fn interleave(frame: &ec_core::AudioFrame, out: &mut Vec<f32>) { |
| 236 | let channels = frame.channels().max(1); |
| 237 | let width = frame.format.bytes_per_sample(); |
| 238 | let read = |plane: &[u8], i: usize| -> f32 { |
| 239 | let at = i * width; |
| 240 | let b = &plane[at..at + width]; |
| 241 | match frame.format { |
| 242 | SampleFormat::U8 => (f32::from(b[0]) - 128.0) / 128.0, |
| 243 | SampleFormat::S16 => f32::from(i16::from_ne_bytes([b[0], b[1]])) / 32768.0, |
| 244 | SampleFormat::S32 => i32::from_ne_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2147483648.0, |
| 245 | SampleFormat::F32 => f32::from_ne_bytes([b[0], b[1], b[2], b[3]]), |
| 246 | SampleFormat::F64 => { |
| 247 | f64::from_ne_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32 |
| 248 | } |
| 249 | } |
| 250 | }; |
| 251 | match frame.planar { |
| 252 | false => { |
| 253 | let Some(plane) = frame.data.first() else { |
| 254 | return; |
| 255 | }; |
| 256 | let n = (plane.len() / width).min(frame.samples * channels); |
| 257 | out.extend((0..n).map(|i| read(plane, i))); |
| 258 | } |
| 259 | true => { |
| 260 | for i in 0..frame.samples { |
| 261 | for c in 0..channels { |
| 262 | let Some(plane) = frame.data.get(c) else { |
| 263 | continue; |
| 264 | }; |
| 265 | if (i + 1) * width <= plane.len() { |
| 266 | out.push(read(plane, i)); |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | |
| 275 | fn pcm(codec: CodecId, data: &[u8], out: &mut Vec<f32>) { |
| 276 | match codec { |
| 277 | CodecId::PcmU8 => out.extend(data.iter().map(|&b| (f32::from(b) - 128.0) / 128.0)), |
| 278 | CodecId::PcmS16Le => out.extend( |
| 279 | data.chunks_exact(2) |
| 280 | .map(|c| f32::from(i16::from_le_bytes([c[0], c[1]])) / 32768.0), |
| 281 | ), |
| 282 | CodecId::PcmS16Be => out.extend( |
| 283 | data.chunks_exact(2) |
| 284 | .map(|c| f32::from(i16::from_be_bytes([c[0], c[1]])) / 32768.0), |
| 285 | ), |
| 286 | |
| 287 | CodecId::PcmS24Le => out.extend(data.chunks_exact(3).map(|c| { |
| 288 | let v = i32::from_le_bytes([0, c[0], c[1], c[2]]); |
| 289 | v as f32 / 2147483648.0 |
| 290 | })), |
| 291 | CodecId::PcmS32Le => out.extend( |
| 292 | data.chunks_exact(4) |
| 293 | .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as f32 / 2147483648.0), |
| 294 | ), |
| 295 | CodecId::PcmF32Le => out.extend( |
| 296 | data.chunks_exact(4) |
| 297 | .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), |
| 298 | ), |
| 299 | _ => {} |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | |
| 304 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | pub fn opus_layout(head: &[u8], channels: usize) -> Result<(usize, usize, Vec<u8>)> { |
| 310 | let channels = channels.max(1); |
| 311 | let family = head.get(18).copied().unwrap_or(0); |
| 312 | if family == 0 || head.len() < 21 { |
| 313 | let coupled = usize::from(channels >= 2); |
| 314 | let mapping: Vec<u8> = (0..channels.min(2) as u8).collect(); |
| 315 | return Ok((channels.min(2) - coupled, coupled, mapping)); |
| 316 | } |
| 317 | let streams = usize::from(head[19]); |
| 318 | let coupled = usize::from(head[20]); |
| 319 | let mapping = head |
| 320 | .get(21..21 + channels) |
| 321 | .ok_or_else(|| { |
| 322 | Error::corrupt(format!( |
| 323 | "an OpusHead claiming {channels} channels with a {}-byte mapping table", |
| 324 | head.len().saturating_sub(21) |
| 325 | )) |
| 326 | })? |
| 327 | .to_vec(); |
| 328 | Ok((streams, coupled, mapping)) |
| 329 | } |
| 330 | |
| 331 | |
| 332 | pub fn opus_pre_skip(head: &[u8]) -> u64 { |
| 333 | match head.get(10..12) { |
| 334 | Some(b) => u64::from(u16::from_le_bytes([b[0], b[1]])), |
| 335 | None => 0, |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | #[cfg(test)] |
| 340 | mod tests { |
| 341 | use super::*; |
| 342 | |
| 343 | #[test] |
| 344 | fn opus_layouts_come_off_the_head_or_are_implied() { |
| 345 | |
| 346 | let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00"; |
| 347 | assert_eq!(opus_layout(head, 2).unwrap(), (1, 1, vec![0, 1])); |
| 348 | assert_eq!(opus_layout(head, 1).unwrap(), (1, 0, vec![0])); |
| 349 | assert_eq!(opus_pre_skip(head), 312); |
| 350 | |
| 351 | |
| 352 | let mut six = head[..18].to_vec(); |
| 353 | six.extend_from_slice(&[1, 4, 2, 0, 4, 1, 2, 3, 5]); |
| 354 | assert_eq!( |
| 355 | opus_layout(&six, 6).unwrap(), |
| 356 | (4, 2, vec![0, 4, 1, 2, 3, 5]) |
| 357 | ); |
| 358 | |
| 359 | assert!(opus_layout(&six[..23], 6).is_err()); |
| 360 | } |
| 361 | |
| 362 | #[test] |
| 363 | fn pcm_reads_every_width_at_full_scale() { |
| 364 | let mut out = Vec::new(); |
| 365 | pcm(CodecId::PcmS16Le, &[0x00, 0x80, 0xff, 0x7f], &mut out); |
| 366 | assert_eq!(out, vec![-1.0, 32767.0 / 32768.0]); |
| 367 | out.clear(); |
| 368 | pcm(CodecId::PcmU8, &[0, 128, 255], &mut out); |
| 369 | assert_eq!(out[0], -1.0); |
| 370 | assert_eq!(out[1], 0.0); |
| 371 | out.clear(); |
| 372 | |
| 373 | pcm(CodecId::PcmS24Le, &[0x00, 0x00, 0x80], &mut out); |
| 374 | assert_eq!(out, vec![-1.0]); |
| 375 | } |
| 376 | } |