edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 1 | //! Legacy audio decoders: IMA ADPCM (WAV `0x0011` and QuickTime `ima4`), |
| 2 | //! Microsoft ADPCM (`0x0002`) and G.711 A-law / mu-law, all delivering `s16`. |
| 3 | //! |
| 4 | //! Every block-based format here decodes a packet of whole blocks: the |
| 5 | //! container hands one block (WAV/AVI `nBlockAlign` bytes, or a run of 34-byte |
| 6 | //! QuickTime packets) per packet, and a ragged tail is dropped the way the |
| 7 | //! oracle's decoders drop it. Output is interleaved `i16`, bit-exact against |
| 8 | //! ffmpeg's `adpcm_ima_wav`, `adpcm_ima_qt`, `adpcm_ms`, `pcm_alaw` and |
| 9 | //! `pcm_mulaw`. |
| 10 | |
| 11 | #![forbid(unsafe_code)] |
| 12 | #![warn(missing_docs)] |
| 13 | |
| 14 | use ec_core::error::{Error, Result}; |
| 15 | use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; |
| 16 | use ec_core::packet::{Buf, Packet}; |
| 17 | use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters}; |
| 18 | |
| 19 | const STEP_TABLE: [i32; 89] = [ |
| 20 | 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, |
| 21 | 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, |
| 22 | 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, |
| 23 | 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, |
| 24 | 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, |
| 25 | 32767, |
| 26 | ]; |
| 27 | const INDEX_TABLE: [i32; 8] = [-1, -1, -1, -1, 2, 4, 6, 8]; |
| 28 | |
| 29 | const MS_COEF1: [i32; 7] = [256, 512, 0, 192, 240, 460, 392]; |
| 30 | const MS_COEF2: [i32; 7] = [0, -256, 0, 64, 0, -208, -232]; |
| 31 | const MS_ADAPT: [i32; 16] = [ |
| 32 | 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230, |
| 33 | ]; |
| 34 | |
| 35 | /// Which format a decoder reads. |
| 36 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 37 | pub enum Kind { |
| 38 | /// IMA ADPCM in WAV/AVI (`0x0011`). |
| 39 | ImaWav, |
| 40 | /// Microsoft ADPCM (`0x0002`). |
| 41 | MsAdpcm, |
| 42 | /// QuickTime IMA4. |
| 43 | ImaQt, |
| 44 | /// G.711 A-law. |
| 45 | Alaw, |
| 46 | /// G.711 mu-law. |
| 47 | Mulaw, |
| 48 | } |
| 49 | |
| 50 | impl Kind { |
| 51 | /// The decoder kind for a codec id, if this crate decodes it. |
| 52 | pub fn of(codec: CodecId) -> Option<Kind> { |
| 53 | Some(match codec { |
| 54 | CodecId::ImaAdpcmWav => Kind::ImaWav, |
| 55 | CodecId::MsAdpcm => Kind::MsAdpcm, |
| 56 | CodecId::ImaAdpcmQt => Kind::ImaQt, |
| 57 | CodecId::PcmAlaw => Kind::Alaw, |
| 58 | CodecId::PcmMulaw => Kind::Mulaw, |
| 59 | _ => return None, |
| 60 | }) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | fn clip16(v: i32) -> i32 { |
| 65 | v.clamp(-32768, 32767) |
| 66 | } |
| 67 | |
| 68 | #[derive(Clone, Copy, Debug, Default)] |
| 69 | struct Ima { |
| 70 | predictor: i32, |
| 71 | index: i32, |
| 72 | } |
| 73 | |
| 74 | impl Ima { |
| 75 | /// One nibble, bitwise step accumulation (ffmpeg's QT and 4-bit WAV path). |
| 76 | fn expand(&mut self, nibble: u8) -> i16 { |
| 77 | let step = STEP_TABLE[self.index as usize]; |
| 78 | let mut diff = step >> 3; |
| 79 | if nibble & 4 != 0 { |
| 80 | diff += step; |
| 81 | } |
| 82 | if nibble & 2 != 0 { |
| 83 | diff += step >> 1; |
| 84 | } |
| 85 | if nibble & 1 != 0 { |
| 86 | diff += step >> 2; |
| 87 | } |
| 88 | self.predictor = clip16(if nibble & 8 != 0 { |
| 89 | self.predictor - diff |
| 90 | } else { |
| 91 | self.predictor + diff |
| 92 | }); |
| 93 | self.index = (self.index + INDEX_TABLE[usize::from(nibble & 7)]).clamp(0, 88); |
| 94 | self.predictor as i16 |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | #[derive(Clone, Copy, Default)] |
| 99 | struct Ms { |
| 100 | c1: i32, |
| 101 | c2: i32, |
| 102 | delta: i32, |
| 103 | s1: i32, |
| 104 | s2: i32, |
| 105 | } |
| 106 | |
| 107 | impl Ms { |
| 108 | fn expand(&mut self, nibble: u8) -> i16 { |
| 109 | let mut p = self |
| 110 | .s1 |
| 111 | .wrapping_mul(self.c1) |
| 112 | .wrapping_add(self.s2.wrapping_mul(self.c2)) |
| 113 | / 256; |
| 114 | let n = i32::from(nibble); |
| 115 | p = p.wrapping_add((if n & 8 != 0 { n - 16 } else { n }).wrapping_mul(self.delta)); |
| 116 | self.s2 = self.s1; |
| 117 | self.s1 = clip16(p); |
| 118 | self.delta = (MS_ADAPT[usize::from(nibble)].wrapping_mul(self.delta) >> 8) |
| 119 | .clamp(16, i32::MAX / 768); |
| 120 | self.s1 as i16 |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | fn alaw(v: u8) -> i16 { |
| 125 | let a = v ^ 0x55; |
| 126 | let mut t = i32::from(a & 0x7f); |
| 127 | if t < 16 { |
| 128 | t = (t << 4) + 8; |
| 129 | } else { |
| 130 | let seg = t >> 4; |
| 131 | t = ((t & 0x0f) << 4) + 0x108; |
| 132 | t <<= seg - 1; |
| 133 | } |
| 134 | (if a & 0x80 != 0 { t } else { -t }) as i16 |
| 135 | } |
| 136 | |
| 137 | fn mulaw(v: u8) -> i16 { |
| 138 | let u = !v; |
| 139 | let mut t = (i32::from(u & 0x0f) << 3) + 0x84; |
| 140 | t <<= (u & 0x70) >> 4; |
| 141 | (if u & 0x80 != 0 { 0x84 - t } else { t - 0x84 }) as i16 |
| 142 | } |
| 143 | |
| 144 | /// A decoder for one stream of any [`Kind`]. |
| 145 | #[derive(Debug)] |
| 146 | pub struct PcmExtDecoder { |
| 147 | kind: Kind, |
| 148 | channels: usize, |
| 149 | sample_rate: u32, |
| 150 | coefs: Vec<(i32, i32)>, |
| 151 | params: CodecParameters, |
| 152 | out: Vec<i16>, |
| 153 | /// IMA4 running state per channel, kept across packets the way the |
| 154 | /// oracle keeps it (a header that agrees with it does not reset it). |
| 155 | qt: Vec<Ima>, |
| 156 | pending: Option<AudioFrame>, |
| 157 | drained: bool, |
| 158 | } |
| 159 | |
| 160 | impl PcmExtDecoder { |
| 161 | /// A decoder for the stream `params` describes. For MS ADPCM the |
| 162 | /// extradata is the `fmt ` tail (samples per block, coefficient count and |
| 163 | /// pairs); without one the standard seven pairs are used. |
| 164 | pub fn from_parameters(params: CodecParameters) -> Result<PcmExtDecoder> { |
| 165 | let kind = Kind::of(params.codec) |
| 166 | .ok_or_else(|| Error::corrupt("ec-pcm-ext: not one of its codecs"))?; |
| 167 | let audio = params |
| 168 | .audio() |
| 169 | .ok_or_else(|| Error::corrupt("ec-pcm-ext: a non-audio stream"))?; |
| 170 | let channels = audio.layout.channel_count().max(1); |
| 171 | let sample_rate = audio.sample_rate; |
| 172 | let mut coefs: Vec<(i32, i32)> = MS_COEF1.iter().copied().zip(MS_COEF2).collect(); |
| 173 | if kind == Kind::MsAdpcm |
| 174 | && let Some(x) = params.extradata.as_deref() |
| 175 | && x.len() >= 4 |
| 176 | { |
| 177 | let n = usize::from(u16::from_le_bytes([x[2], x[3]])); |
| 178 | if n > 0 && x.len() >= 4 + n * 4 { |
| 179 | coefs = (0..n) |
| 180 | .map(|i| { |
| 181 | let b = &x[4 + i * 4..]; |
| 182 | ( |
| 183 | i32::from(i16::from_le_bytes([b[0], b[1]])), |
| 184 | i32::from(i16::from_le_bytes([b[2], b[3]])), |
| 185 | ) |
| 186 | }) |
| 187 | .collect(); |
| 188 | } |
| 189 | } |
| 190 | if kind == Kind::MsAdpcm && channels > 2 { |
| 191 | return Err(Error::unsupported( |
| 192 | "MS ADPCM with more than two channels", |
| 193 | "the format is mono or stereo", |
| 194 | )); |
| 195 | } |
| 196 | let mut p = params; |
| 197 | p.media = MediaParameters::Audio(AudioParameters { |
| 198 | sample_rate, |
| 199 | layout: ChannelLayout::from_count(channels), |
| 200 | format: Some(SampleFormat::S16), |
| 201 | bits_per_sample: Some(16), |
| 202 | }); |
| 203 | Ok(PcmExtDecoder { |
| 204 | kind, |
| 205 | channels, |
| 206 | sample_rate, |
| 207 | coefs, |
| 208 | params: p, |
| 209 | out: Vec::new(), |
| 210 | qt: vec![Ima::default(); channels], |
| 211 | pending: None, |
| 212 | drained: false, |
| 213 | }) |
| 214 | } |
| 215 | |
| 216 | /// Decode one packet into interleaved `i16`. The slice is valid until the |
| 217 | /// next call. |
| 218 | pub fn decode(&mut self, data: &[u8]) -> Result<&[i16]> { |
| 219 | self.out.clear(); |
| 220 | let ch = self.channels; |
| 221 | match self.kind { |
| 222 | Kind::Alaw => self.out.extend(data.iter().map(|&b| alaw(b))), |
| 223 | Kind::Mulaw => self.out.extend(data.iter().map(|&b| mulaw(b))), |
| 224 | Kind::ImaWav => { |
| 225 | if data.len() < 4 * ch { |
| 226 | return Err(Error::corrupt("IMA ADPCM: a block shorter than its header")); |
| 227 | } |
| 228 | let groups = (data.len() - 4 * ch) / (4 * ch); |
| 229 | let n = 1 + groups * 8; |
| 230 | let mut st = vec![Ima::default(); ch]; |
| 231 | self.out.resize(n * ch, 0); |
| 232 | for (c, s) in st.iter_mut().enumerate() { |
| 233 | let h = &data[c * 4..]; |
| 234 | s.predictor = i32::from(i16::from_le_bytes([h[0], h[1]])); |
| 235 | s.index = i32::from(i16::from_le_bytes([h[2], h[3]])); |
| 236 | if !(0..=88).contains(&s.index) { |
| 237 | self.out.clear(); |
| 238 | return Err(Error::corrupt("IMA ADPCM: step index out of range")); |
| 239 | } |
| 240 | self.out[c] = s.predictor as i16; |
| 241 | } |
| 242 | let body = &data[4 * ch..]; |
| 243 | for g in 0..groups { |
| 244 | for (c, s) in st.iter_mut().enumerate() { |
| 245 | let src = &body[(g * ch + c) * 4..][..4]; |
| 246 | for (m, &b) in src.iter().enumerate() { |
| 247 | let at = 1 + g * 8 + m * 2; |
| 248 | self.out[at * ch + c] = s.expand(b & 15); |
| 249 | self.out[(at + 1) * ch + c] = s.expand(b >> 4); |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | Kind::ImaQt => { |
| 255 | let blocks = data.len() / (34 * ch); |
| 256 | self.out.resize(blocks * 64 * ch, 0); |
| 257 | for b in 0..blocks { |
| 258 | for c in 0..ch { |
| 259 | let src = &data[(b * ch + c) * 34..][..34]; |
| 260 | let h = u16::from_be_bytes([src[0], src[1]]); |
| 261 | let mut s = Ima { |
| 262 | predictor: i32::from((h & 0xFF80) as i16), |
| 263 | index: i32::from(h & 0x7F), |
| 264 | }; |
| 265 | if s.index > 88 { |
| 266 | self.out.clear(); |
| 267 | return Err(Error::corrupt("IMA4: step index out of range")); |
| 268 | } |
| 269 | // The header carries only the top 9 bits of the |
| 270 | // predictor: when the step index agrees with the |
| 271 | // running state and the predictor is the truncation of |
| 272 | // it, the running (full precision) value stands. |
| 273 | let run = self.qt[c]; |
| 274 | if run.index == s.index && (0..=0x7f).contains(&(run.predictor - s.predictor)) { |
| 275 | s.predictor = run.predictor; |
| 276 | } |
| 277 | for (m, &v) in src[2..].iter().enumerate() { |
| 278 | let at = b * 64 + m * 2; |
| 279 | self.out[at * ch + c] = s.expand(v & 15); |
| 280 | self.out[(at + 1) * ch + c] = s.expand(v >> 4); |
| 281 | } |
| 282 | self.qt[c] = s; |
| 283 | } |
| 284 | } |
| 285 | } |
| 286 | Kind::MsAdpcm => { |
| 287 | if ch > 2 { |
| 288 | return Err(Error::unsupported("MS ADPCM", "more than two channels")); |
| 289 | } |
| 290 | if data.len() < 7 * ch { |
| 291 | return Err(Error::corrupt("MS ADPCM: a block shorter than its header")); |
| 292 | } |
| 293 | let mut st = [Ms::default(); 2]; |
| 294 | let mut at = 0; |
| 295 | for s in st.iter_mut().take(ch) { |
| 296 | let bp = usize::from(data[at]); |
| 297 | at += 1; |
| 298 | let &(c1, c2) = self |
| 299 | .coefs |
| 300 | .get(bp) |
| 301 | .ok_or_else(|| Error::corrupt("MS ADPCM: block predictor out of range"))?; |
| 302 | s.c1 = c1; |
| 303 | s.c2 = c2; |
| 304 | } |
| 305 | let rd = |at: &mut usize| { |
| 306 | let v = i32::from(i16::from_le_bytes([data[*at], data[*at + 1]])); |
| 307 | *at += 2; |
| 308 | v |
| 309 | }; |
| 310 | for s in st.iter_mut().take(ch) { |
| 311 | s.delta = rd(&mut at); |
| 312 | } |
| 313 | for s in st.iter_mut().take(ch) { |
| 314 | s.s1 = rd(&mut at); |
| 315 | } |
| 316 | for s in st.iter_mut().take(ch) { |
| 317 | s.s2 = rd(&mut at); |
| 318 | } |
| 319 | for s in st.iter().take(ch) { |
| 320 | self.out.push(s.s2 as i16); |
| 321 | } |
| 322 | for s in st.iter().take(ch) { |
| 323 | self.out.push(s.s1 as i16); |
| 324 | } |
| 325 | let stereo = ch == 2; |
| 326 | for &b in &data[at..] { |
| 327 | self.out.push(st[0].expand(b >> 4)); |
| 328 | self.out.push(st[usize::from(stereo)].expand(b & 15)); |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | Ok(&self.out) |
| 333 | } |
| 334 | |
| 335 | /// Sample rate the stream declared. |
| 336 | pub fn sample_rate(&self) -> u32 { |
| 337 | self.sample_rate |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | impl Decoder for PcmExtDecoder { |
| 342 | fn codec_parameters(&self) -> &CodecParameters { |
| 343 | &self.params |
| 344 | } |
| 345 | |
| 346 | fn send_packet(&mut self, packet: &Packet) -> Result<()> { |
| 347 | self.decode(&packet.data)?; |
| 348 | let channels = self.channels; |
| 349 | let mut bytes = Vec::with_capacity(self.out.len() * 2); |
| 350 | for &s in &self.out { |
| 351 | bytes.extend_from_slice(&s.to_ne_bytes()); |
| 352 | } |
| 353 | let mut frame = AudioFrame::try_new( |
| 354 | SampleFormat::S16, |
| 355 | false, |
| 356 | ChannelLayout::from_count(channels), |
| 357 | self.sample_rate, |
| 358 | self.out.len() / channels, |
| 359 | vec![Buf::from_vec(bytes)], |
| 360 | )?; |
| 361 | frame.pts = packet |
| 362 | .pts |
| 363 | .map(|ticks| ec_core::timebase::Timestamp::new(ticks, packet.time_base)); |
| 364 | self.pending = Some(frame); |
| 365 | Ok(()) |
| 366 | } |
| 367 | |
| 368 | fn receive_frame(&mut self) -> Result<Frame> { |
| 369 | match self.pending.take() { |
| 370 | Some(frame) => Ok(Frame::Audio(frame)), |
| 371 | None if self.drained => Err(Error::Eof), |
| 372 | None => Err(Error::NeedMore), |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | fn flush(&mut self) -> Result<()> { |
| 377 | self.drained = true; |
| 378 | Ok(()) |
| 379 | } |
| 380 | |
| 381 | fn reset(&mut self) { |
| 382 | self.qt.iter_mut().for_each(|s| *s = Ima::default()); |
| 383 | self.pending = None; |
| 384 | self.drained = false; |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | #[cfg(test)] |
| 389 | mod tests { |
| 390 | use super::*; |
| 391 | |
| 392 | #[test] |
| 393 | fn g711_anchor_values() { |
| 394 | assert_eq!(alaw(0xD5), 8); |
| 395 | assert_eq!(alaw(0x55), -8); |
| 396 | assert_eq!(mulaw(0xFF), 0); |
| 397 | assert_eq!(mulaw(0x00), -32124); |
| 398 | assert_eq!(mulaw(0x80), 32124); |
| 399 | } |
| 400 | } |