| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | use ec_core::{ |
| 18 | AudioParameters, BitWriter, Buf, ChannelLayout, CodecId, CodecParameters, Encoder, Error, |
| 19 | Frame, MediaParameters, Packet, Result, SampleFormat, TimeBase, |
| 20 | }; |
| 21 | use ec_dsp::Mdct; |
| 22 | |
| 23 | use crate::bitalloc::{self, Allocation, BitAllocParams, Channel}; |
| 24 | use crate::bsi::Acmod; |
| 25 | use crate::exps::Strategy; |
| 26 | use crate::transform::Imdct; |
| 27 | use crate::tables::{BIT_RATE_KBPS, FRAME_SIZE_WORDS, QNTZTAB, QUANT_LEVELS, SAMPLE_RATE, WINDOW}; |
| 28 | |
| 29 | |
| 30 | const FRAME_SAMPLES: usize = 1536; |
| 31 | |
| 32 | const BLOCKS: usize = 6; |
| 33 | |
| 34 | const COEFFS: usize = 256; |
| 35 | |
| 36 | |
| 37 | |
| 38 | const MIN_KBPS_PER_CHANNEL: u32 = 32; |
| 39 | |
| 40 | const BA_PARAMS: BitAllocParams = BitAllocParams { sdcycod: 2, fdcycod: 1, sgaincod: 1, dbpbcod: 2, floorcod: 7 }; |
| 41 | |
| 42 | const FGAINCOD: u8 = 4; |
| 43 | |
| 44 | |
| 45 | const RESEND_STEPS: u8 = 2; |
| 46 | |
| 47 | const TRANSIENT_RATIO: f32 = 8.0; |
| 48 | |
| 49 | |
| 50 | const TRANSIENT_FLOOR: f32 = 1e-2; |
| 51 | |
| 52 | const LFE_ENDMANT: usize = 7; |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | const FORWARD_GAIN: f32 = -2.0 / 512.0; |
| 58 | |
| 59 | |
| 60 | const SHORT_GAIN: f32 = 1.0 / 128.0; |
| 61 | |
| 62 | |
| 63 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 64 | pub struct EncoderConfig { |
| 65 | |
| 66 | pub sample_rate: u32, |
| 67 | |
| 68 | pub channels: u16, |
| 69 | |
| 70 | pub bitrate_kbps: u32, |
| 71 | } |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | fn channel_order(acmod: Acmod, nfchans: usize, lfeon: bool) -> Vec<Option<usize>> { |
| 80 | let mut order: Vec<Option<usize>> = match acmod { |
| 81 | Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => { |
| 82 | let mut v = vec![Some(0), Some(2), Some(1)]; |
| 83 | v.extend((3..nfchans).map(Some)); |
| 84 | v |
| 85 | } |
| 86 | _ => (0..nfchans).map(Some).collect(), |
| 87 | }; |
| 88 | if lfeon { |
| 89 | let fronts = match acmod { |
| 90 | Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3, |
| 91 | Acmod::Mono => 1, |
| 92 | _ => 2, |
| 93 | }; |
| 94 | order.insert(fronts.min(order.len()), None); |
| 95 | } |
| 96 | order |
| 97 | } |
| 98 | |
| 99 | |
| 100 | fn acmod_for(channels: u16) -> Result<(Acmod, bool)> { |
| 101 | Ok(match channels { |
| 102 | 1 => (Acmod::Mono, false), |
| 103 | 2 => (Acmod::Stereo, false), |
| 104 | 3 => (Acmod::Surround3_0, false), |
| 105 | 4 => (Acmod::Surround2_2, false), |
| 106 | 5 => (Acmod::Surround3_2, false), |
| 107 | 6 => (Acmod::Surround3_2, true), |
| 108 | other => { |
| 109 | return Err(Error::unsupported( |
| 110 | format!("{other} channels"), |
| 111 | "this encoder codes 1 to 6 channels (6 is 3/2 + LFE)", |
| 112 | )); |
| 113 | } |
| 114 | }) |
| 115 | } |
| 116 | |
| 117 | |
| 118 | |
| 119 | fn crc16(data: &[u8]) -> u16 { |
| 120 | let mut crc: u16 = 0; |
| 121 | for &byte in data { |
| 122 | crc ^= (byte as u16) << 8; |
| 123 | for _ in 0..8 { |
| 124 | crc = if crc & 0x8000 != 0 { |
| 125 | (crc << 1) ^ 0x8005 |
| 126 | } else { |
| 127 | crc << 1 |
| 128 | }; |
| 129 | } |
| 130 | } |
| 131 | crc |
| 132 | } |
| 133 | |
| 134 | |
| 135 | |
| 136 | fn quantize_index(levels: u32, value: f32) -> u32 { |
| 137 | let k = ((value * levels as f32 + (levels as f32 - 1.0)) / 2.0).round(); |
| 138 | k.clamp(0.0, (levels - 1) as f32) as u32 |
| 139 | } |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | |
| 147 | |
| 148 | |
| 149 | fn write_mantissas(w: &mut BitWriter, values: &[(u8, f32)]) { |
| 150 | let mut left = [0usize; 16]; |
| 151 | for (i, &(bap, value)) in values.iter().enumerate() { |
| 152 | let (levels, bits, size, radix) = match bap { |
| 153 | 0 => continue, |
| 154 | 1 => (QUANT_LEVELS[1], 5, 3, 3), |
| 155 | 2 => (QUANT_LEVELS[2], 7, 3, 5), |
| 156 | 4 => (QUANT_LEVELS[4], 7, 2, 11), |
| 157 | 3 | 5 => { |
| 158 | let bits = QNTZTAB[bap as usize]; |
| 159 | w.write_bits(quantize_index(QUANT_LEVELS[bap as usize], value), bits); |
| 160 | continue; |
| 161 | } |
| 162 | _ => { |
| 163 | |
| 164 | let bits = QNTZTAB[(bap as usize).min(15)]; |
| 165 | let scale = (1u32 << (bits - 1)) as f32; |
| 166 | let signed = (value * scale).round().clamp(-scale, scale - 1.0) as i32; |
| 167 | w.write_signed(signed, bits); |
| 168 | continue; |
| 169 | } |
| 170 | }; |
| 171 | if left[bap as usize] == 0 { |
| 172 | let mut code = 0u32; |
| 173 | let mut members = values[i..].iter().filter(|v| v.0 == bap).map(|v| quantize_index(levels, v.1)); |
| 174 | for _ in 0..size { |
| 175 | code = code * radix + members.next().unwrap_or((levels - 1) / 2); |
| 176 | } |
| 177 | w.write_bits(code, bits); |
| 178 | left[bap as usize] = size; |
| 179 | } |
| 180 | left[bap as usize] -= 1; |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | fn smooth_exps(exps: &mut [u8]) { |
| 194 | exps[0] = exps[0].min(15); |
| 195 | for i in (0..exps.len() - 1).rev() { |
| 196 | exps[i] = exps[i].min(exps[i + 1] + 2); |
| 197 | } |
| 198 | for i in 1..exps.len() { |
| 199 | exps[i] = exps[i].min(exps[i - 1] + 2); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | fn write_exp_groups(w: &mut BitWriter, sent: &[u8]) { |
| 208 | w.write_bits(u32::from(sent[0]), 4); |
| 209 | let mut prev = i32::from(sent[0]); |
| 210 | for grp in sent[1..].as_chunks::<3>().0 { |
| 211 | let mut code = 0u32; |
| 212 | for &v in grp { |
| 213 | let diff = i32::from(v) - prev; |
| 214 | debug_assert!((-2..=2).contains(&diff)); |
| 215 | code = code * 5 + (diff + 2) as u32; |
| 216 | prev = i32::from(v); |
| 217 | } |
| 218 | w.write_bits(code, 7); |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | |
| 223 | pub struct Ac3Encoder { |
| 224 | config: EncoderConfig, |
| 225 | params: CodecParameters, |
| 226 | acmod: Acmod, |
| 227 | lfeon: bool, |
| 228 | nfchans: usize, |
| 229 | |
| 230 | |
| 231 | coded: usize, |
| 232 | fscod: usize, |
| 233 | frmsizecod: u8, |
| 234 | frame_bytes: usize, |
| 235 | order: Vec<Option<usize>>, |
| 236 | mdct: Mdct<f32>, |
| 237 | window: [f32; 512], |
| 238 | |
| 239 | |
| 240 | |
| 241 | short_basis: Vec<f32>, |
| 242 | chbwcod: u32, |
| 243 | fbw_endmant: usize, |
| 244 | stats: EncodeStats, |
| 245 | |
| 246 | history: Vec<[f32; COEFFS]>, |
| 247 | pcm: Vec<f32>, |
| 248 | packets: std::collections::VecDeque<Vec<u8>>, |
| 249 | finished: bool, |
| 250 | } |
| 251 | |
| 252 | impl Ac3Encoder { |
| 253 | |
| 254 | pub fn new(config: EncoderConfig) -> Result<Ac3Encoder> { |
| 255 | let (acmod, lfeon) = acmod_for(config.channels)?; |
| 256 | let nfchans = acmod.nfchans(); |
| 257 | let coded = nfchans + usize::from(lfeon); |
| 258 | let fscod = SAMPLE_RATE[..3] |
| 259 | .iter() |
| 260 | .position(|&r| r == config.sample_rate) |
| 261 | .ok_or_else(|| { |
| 262 | Error::unsupported( |
| 263 | format!("{} Hz", config.sample_rate), |
| 264 | "AC-3 codes 48000, 44100 or 32000 Hz", |
| 265 | ) |
| 266 | })?; |
| 267 | let kbps = config.bitrate_kbps.max(MIN_KBPS_PER_CHANNEL * coded as u32); |
| 268 | let idx = BIT_RATE_KBPS |
| 269 | .iter() |
| 270 | .enumerate() |
| 271 | .min_by_key(|&(_, &k)| k.abs_diff(kbps)) |
| 272 | .map(|(i, _)| i) |
| 273 | .unwrap_or(0); |
| 274 | let frmsizecod = (idx * 2) as u8; |
| 275 | let frame_bytes = usize::from(FRAME_SIZE_WORDS[frmsizecod as usize][fscod]) * 2; |
| 276 | |
| 277 | let mut window = [0.0f32; 512]; |
| 278 | for i in 0..256 { |
| 279 | window[i] = WINDOW[i]; |
| 280 | window[511 - i] = WINDOW[i]; |
| 281 | } |
| 282 | |
| 283 | let mut imdct = Imdct::new(); |
| 284 | let mut short_basis = vec![0.0f32; COEFFS * 512]; |
| 285 | for k in 0..COEFFS { |
| 286 | let mut spec = [0.0f32; COEFFS]; |
| 287 | spec[k] = 1.0; |
| 288 | let (mut delay, mut out) = ([0.0f32; 256], [0.0f32; 256]); |
| 289 | imdct.block(&spec, true, &mut delay, &mut out); |
| 290 | let row = &mut short_basis[k * 512..(k + 1) * 512]; |
| 291 | for n in 0..256 { |
| 292 | row[n] = out[n] / 2.0; |
| 293 | row[256 + n] = delay[n]; |
| 294 | } |
| 295 | } |
| 296 | let chbwcod = chbwcod_for(BIT_RATE_KBPS[idx], nfchans); |
| 297 | |
| 298 | let mut params = CodecParameters::new(CodecId::Ac3); |
| 299 | params.media = MediaParameters::Audio(AudioParameters { |
| 300 | sample_rate: config.sample_rate, |
| 301 | layout: ChannelLayout::from_count(coded), |
| 302 | format: Some(SampleFormat::F32), |
| 303 | bits_per_sample: None, |
| 304 | }); |
| 305 | |
| 306 | Ok(Ac3Encoder { |
| 307 | order: channel_order(acmod, nfchans, lfeon), |
| 308 | config, |
| 309 | params, |
| 310 | acmod, |
| 311 | lfeon, |
| 312 | nfchans, |
| 313 | coded, |
| 314 | fscod, |
| 315 | frmsizecod, |
| 316 | frame_bytes, |
| 317 | mdct: Mdct::new(512), |
| 318 | window, |
| 319 | short_basis, |
| 320 | chbwcod, |
| 321 | fbw_endmant: (chbwcod as usize + 12) * 3 + 37, |
| 322 | stats: EncodeStats::default(), |
| 323 | history: vec![[0.0; COEFFS]; coded], |
| 324 | pcm: Vec::new(), |
| 325 | packets: std::collections::VecDeque::new(), |
| 326 | finished: false, |
| 327 | }) |
| 328 | } |
| 329 | |
| 330 | |
| 331 | pub fn codec_parameters(&self) -> &CodecParameters { |
| 332 | &self.params |
| 333 | } |
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | |
| 339 | pub fn encoder_delay(&self) -> usize { |
| 340 | COEFFS |
| 341 | } |
| 342 | |
| 343 | |
| 344 | pub fn stats(&self) -> EncodeStats { |
| 345 | self.stats |
| 346 | } |
| 347 | |
| 348 | |
| 349 | |
| 350 | pub fn push_pcm_f32(&mut self, interleaved: &[f32]) -> Result<()> { |
| 351 | self.pcm.extend_from_slice(interleaved); |
| 352 | self.drain(); |
| 353 | Ok(()) |
| 354 | } |
| 355 | |
| 356 | |
| 357 | |
| 358 | |
| 359 | pub fn finish(&mut self) { |
| 360 | let need = FRAME_SAMPLES * self.coded; |
| 361 | if !self.pcm.is_empty() || self.stats.frames > 0 { |
| 362 | self.pcm.resize(self.pcm.len() + COEFFS * self.coded, 0.0); |
| 363 | let padded = self.pcm.len().div_ceil(need) * need; |
| 364 | self.pcm.resize(padded, 0.0); |
| 365 | } |
| 366 | self.drain(); |
| 367 | self.finished = true; |
| 368 | } |
| 369 | |
| 370 | fn drain(&mut self) { |
| 371 | let need = FRAME_SAMPLES * self.coded; |
| 372 | let rest = self.pcm.split_off(self.pcm.len() / need * need); |
| 373 | let full = std::mem::replace(&mut self.pcm, rest); |
| 374 | for block in full.chunks_exact(need) { |
| 375 | let packet = self.encode_frame(block); |
| 376 | self.packets.push_back(packet); |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | |
| 381 | |
| 382 | pub fn next_packet(&mut self) -> Result<Vec<u8>> { |
| 383 | match self.packets.pop_front() { |
| 384 | Some(p) => Ok(p), |
| 385 | None if self.finished => Err(Error::Eof), |
| 386 | None => Err(Error::NeedMore), |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | |
| 391 | |
| 392 | fn encode_frame(&mut self, interleaved: &[f32]) -> Vec<u8> { |
| 393 | |
| 394 | |
| 395 | let mut coeffs = vec![vec![[0.0f32; COEFFS]; self.coded]; BLOCKS]; |
| 396 | let mut blksw = vec![vec![false; self.coded]; BLOCKS]; |
| 397 | for ch in 0..self.coded { |
| 398 | let slot = if ch < self.nfchans { |
| 399 | self.order.iter().position(|&s| s == Some(ch)).unwrap() |
| 400 | } else { |
| 401 | self.order.iter().position(|&s| s.is_none()).unwrap() |
| 402 | }; |
| 403 | for blk in 0..BLOCKS { |
| 404 | let mut window_in = [0.0f32; 512]; |
| 405 | window_in[..256].copy_from_slice(&self.history[ch]); |
| 406 | for n in 0..256 { |
| 407 | window_in[256 + n] = interleaved[(blk * 256 + n) * self.coded + slot]; |
| 408 | } |
| 409 | |
| 410 | let short = ch < self.nfchans && is_transient(&window_in); |
| 411 | blksw[blk][ch] = short; |
| 412 | let mut spectrum = [0.0f32; COEFFS]; |
| 413 | if short { |
| 414 | self.forward_short(&window_in, &mut spectrum); |
| 415 | } else { |
| 416 | self.mdct |
| 417 | .forward_windowed(&window_in, &self.window, &mut spectrum); |
| 418 | for v in &mut spectrum { |
| 419 | |
| 420 | |
| 421 | *v *= FORWARD_GAIN; |
| 422 | } |
| 423 | } |
| 424 | self.history[ch].copy_from_slice(&window_in[256..]); |
| 425 | coeffs[blk][ch] = spectrum; |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | let endmant: Vec<usize> = (0..self.coded) |
| 430 | .map(|ch| if ch < self.nfchans { self.fbw_endmant } else { LFE_ENDMANT }) |
| 431 | .collect(); |
| 432 | let budget_bits = self.frame_bytes as u64 * 8 - 2 - 16 ; |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | |
| 440 | let mut chosen: Option<(BitWriter, Plan, u8)> = None; |
| 441 | for conservative in [false, true] { |
| 442 | let plan = self.plan(&coeffs, &blksw, &endmant, conservative); |
| 443 | let fits = |c: u8, f: u8| { |
| 444 | let bap = self.allocate(&plan, &endmant, c, f); |
| 445 | let w = self.write_frame(&coeffs, &plan, &endmant, &bap, c, f); |
| 446 | (w.bit_len() <= budget_bits).then_some(w) |
| 447 | }; |
| 448 | if fits(0, 0).is_none() { |
| 449 | continue; |
| 450 | } |
| 451 | let (mut lo, mut hi) = (0u8, 63u8); |
| 452 | while lo < hi { |
| 453 | let mid = (lo + hi).div_ceil(2); |
| 454 | if fits(mid, 0).is_some() { lo = mid } else { hi = mid - 1 } |
| 455 | } |
| 456 | let c = lo; |
| 457 | let (mut lo, mut hi) = (0u8, 15u8); |
| 458 | while lo < hi { |
| 459 | let mid = (lo + hi).div_ceil(2); |
| 460 | if fits(c, mid).is_some() { lo = mid } else { hi = mid - 1 } |
| 461 | } |
| 462 | chosen = Some((fits(c, lo).unwrap(), plan, c)); |
| 463 | break; |
| 464 | } |
| 465 | let (w, plan, csnroffst) = chosen.unwrap_or_else(|| { |
| 466 | |
| 467 | |
| 468 | |
| 469 | |
| 470 | debug_assert!(false, "side information does not fit the frame"); |
| 471 | let plan = self.plan(&coeffs, &blksw, &endmant, true); |
| 472 | let bap = self.allocate(&plan, &endmant, 0, 0); |
| 473 | (self.write_frame(&coeffs, &plan, &endmant, &bap, 0, 0), plan, 0) |
| 474 | }); |
| 475 | |
| 476 | self.stats.frames += 1; |
| 477 | self.stats.csnroffst_sum += u64::from(csnroffst); |
| 478 | self.stats.bits_used += w.bit_len(); |
| 479 | self.stats.bits_budget += budget_bits; |
| 480 | for blk in 0..BLOCKS { |
| 481 | for ch in 0..self.nfchans { |
| 482 | self.stats.blksw_blocks += u64::from(blksw[blk][ch]); |
| 483 | match plan.strategy[blk][ch] { |
| 484 | Strategy::Reuse => self.stats.reuse += 1, |
| 485 | Strategy::D15 => self.stats.d15 += 1, |
| 486 | Strategy::D25 => self.stats.d25 += 1, |
| 487 | Strategy::D45 => self.stats.d45 += 1, |
| 488 | } |
| 489 | } |
| 490 | } |
| 491 | self.finish_frame(w) |
| 492 | } |
| 493 | |
| 494 | |
| 495 | |
| 496 | |
| 497 | fn forward_short(&self, window_in: &[f32; 512], spectrum: &mut [f32; COEFFS]) { |
| 498 | for (k, out) in spectrum.iter_mut().enumerate() { |
| 499 | let row = &self.short_basis[k * 512..(k + 1) * 512]; |
| 500 | *out = SHORT_GAIN * row.iter().zip(window_in).map(|(a, b)| a * b).sum::<f32>(); |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | |
| 505 | |
| 506 | |
| 507 | |
| 508 | |
| 509 | |
| 510 | |
| 511 | |
| 512 | |
| 513 | |
| 514 | |
| 515 | |
| 516 | fn plan(&self, coeffs: &[Vec<[f32; COEFFS]>], blksw: &[Vec<bool>], endmant: &[usize], conservative: bool) -> Plan { |
| 517 | let ideal: Vec<Vec<[u8; COEFFS]>> = coeffs |
| 518 | .iter() |
| 519 | .map(|blk| (0..self.coded).map(|ch| ideal_exps(&blk[ch], endmant[ch])).collect()) |
| 520 | .collect(); |
| 521 | let mut plan = Plan { |
| 522 | blksw: blksw.to_vec(), |
| 523 | strategy: vec![vec![Strategy::Reuse; self.coded]; BLOCKS], |
| 524 | sent: vec![vec![Vec::new(); self.coded]; BLOCKS], |
| 525 | exps: vec![vec![[24u8; COEFFS]; self.coded]; BLOCKS], |
| 526 | }; |
| 527 | for ch in 0..self.coded { |
| 528 | let mut starts = vec![0usize]; |
| 529 | if !conservative { |
| 530 | for blk in 1..BLOCKS { |
| 531 | let last = *starts.last().unwrap(); |
| 532 | if blksw[blk][ch] != blksw[blk - 1][ch] |
| 533 | || envelope_moved(&ideal[blk][ch], &ideal[last][ch], endmant[ch]) |
| 534 | { |
| 535 | starts.push(blk); |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | for (i, &start) in starts.iter().enumerate() { |
| 540 | let end = starts.get(i + 1).copied().unwrap_or(BLOCKS); |
| 541 | let mut env = ideal[start][ch]; |
| 542 | for blk in start + 1..end { |
| 543 | for bin in 0..endmant[ch] { |
| 544 | env[bin] = env[bin].min(ideal[blk][ch][bin]); |
| 545 | } |
| 546 | } |
| 547 | let strategy = if ch >= self.nfchans { |
| 548 | Strategy::D15 |
| 549 | } else if blksw[start][ch] { |
| 550 | |
| 551 | |
| 552 | |
| 553 | |
| 554 | |
| 555 | Strategy::D25 |
| 556 | } else if conservative || end - start >= 3 { |
| 557 | Strategy::D45 |
| 558 | } else { |
| 559 | Strategy::D25 |
| 560 | }; |
| 561 | let (sent, exps) = plan_exponents(&env, endmant[ch], strategy); |
| 562 | plan.strategy[start][ch] = strategy; |
| 563 | plan.sent[start][ch] = sent; |
| 564 | for blk in start..end { |
| 565 | plan.exps[blk][ch] = exps; |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 | plan |
| 570 | } |
| 571 | |
| 572 | |
| 573 | fn allocate(&self, plan: &Plan, endmant: &[usize], csnroffst: u8, fsnroffst: u8) -> Vec<Vec<[u8; COEFFS]>> { |
| 574 | let snroffset = (((i32::from(csnroffst) - 15) << 4) + i32::from(fsnroffst)) << 2; |
| 575 | |
| 576 | |
| 577 | if csnroffst == 0 && fsnroffst == 0 { |
| 578 | return vec![vec![[0u8; COEFFS]; self.coded]; BLOCKS]; |
| 579 | } |
| 580 | let mut out: Vec<Vec<[u8; COEFFS]>> = Vec::with_capacity(BLOCKS); |
| 581 | for blk in 0..BLOCKS { |
| 582 | let baps = (0..self.coded) |
| 583 | .map(|ch| { |
| 584 | if blk > 0 && plan.strategy[blk][ch] == Strategy::Reuse { |
| 585 | return out[blk - 1][ch]; |
| 586 | } |
| 587 | let kind = if ch < self.nfchans { Channel::Fbw } else { Channel::Lfe }; |
| 588 | let alloc = Allocation { |
| 589 | fscod: self.fscod, |
| 590 | params: BA_PARAMS, |
| 591 | range: (0, endmant[ch]), |
| 592 | fgaincod: FGAINCOD, |
| 593 | snroffset, |
| 594 | kind, |
| 595 | dba: None, |
| 596 | high_efficiency: false, |
| 597 | }; |
| 598 | let mut bap = [0u8; COEFFS]; |
| 599 | bitalloc::compute(&alloc, &plan.exps[blk][ch], &mut bap); |
| 600 | bap |
| 601 | }) |
| 602 | .collect(); |
| 603 | out.push(baps); |
| 604 | } |
| 605 | out |
| 606 | } |
| 607 | |
| 608 | |
| 609 | |
| 610 | |
| 611 | |
| 612 | |
| 613 | |
| 614 | fn write_frame( |
| 615 | &self, |
| 616 | coeffs: &[Vec<[f32; COEFFS]>], |
| 617 | plan: &Plan, |
| 618 | endmant: &[usize], |
| 619 | bap: &[Vec<[u8; COEFFS]>], |
| 620 | csnroffst: u8, |
| 621 | fsnroffst: u8, |
| 622 | ) -> BitWriter { |
| 623 | let mut w = BitWriter::with_capacity(self.frame_bytes); |
| 624 | |
| 625 | |
| 626 | w.write_bits(0x0B77, 16); |
| 627 | w.write_bits(0, 16); |
| 628 | w.write_bits(self.fscod as u32, 2); |
| 629 | w.write_bits(u32::from(self.frmsizecod), 6); |
| 630 | |
| 631 | |
| 632 | w.write_bits(8, 5); |
| 633 | w.write_bits(0, 3); |
| 634 | w.write_bits(u32::from(self.acmod.code()), 3); |
| 635 | if self.acmod.code() & 1 != 0 && self.acmod.code() != 1 { |
| 636 | w.write_bits(1, 2); |
| 637 | } |
| 638 | if self.acmod.code() & 4 != 0 { |
| 639 | w.write_bits(1, 2); |
| 640 | } |
| 641 | if self.acmod == Acmod::Stereo { |
| 642 | w.write_bits(0, 2); |
| 643 | } |
| 644 | w.write_bit(self.lfeon); |
| 645 | w.write_bits(31, 5); |
| 646 | w.write_bit(false); |
| 647 | w.write_bit(false); |
| 648 | w.write_bit(false); |
| 649 | w.write_bit(false); |
| 650 | w.write_bit(false); |
| 651 | w.write_bit(false); |
| 652 | w.write_bit(false); |
| 653 | w.write_bit(false); |
| 654 | |
| 655 | for blk in 0..BLOCKS { |
| 656 | self.write_block(&mut w, blk, coeffs, plan, endmant, bap, csnroffst, fsnroffst); |
| 657 | } |
| 658 | w |
| 659 | } |
| 660 | |
| 661 | #[allow(clippy::too_many_arguments)] |
| 662 | fn write_block( |
| 663 | &self, |
| 664 | w: &mut BitWriter, |
| 665 | blk: usize, |
| 666 | coeffs: &[Vec<[f32; COEFFS]>], |
| 667 | plan: &Plan, |
| 668 | endmant: &[usize], |
| 669 | bap: &[Vec<[u8; COEFFS]>], |
| 670 | csnroffst: u8, |
| 671 | fsnroffst: u8, |
| 672 | ) { |
| 673 | let first = blk == 0; |
| 674 | for ch in 0..self.nfchans { |
| 675 | w.write_bit(plan.blksw[blk][ch]); |
| 676 | } |
| 677 | for _ in 0..self.nfchans { |
| 678 | w.write_bit(false); |
| 679 | } |
| 680 | w.write_bit(false); |
| 681 | w.write_bit(first); |
| 682 | if first { |
| 683 | w.write_bit(false); |
| 684 | } |
| 685 | if self.acmod == Acmod::Stereo { |
| 686 | w.write_bit(false); |
| 687 | } |
| 688 | for ch in 0..self.nfchans { |
| 689 | w.write_bits(strategy_code(plan.strategy[blk][ch]), 2); |
| 690 | } |
| 691 | if self.lfeon { |
| 692 | w.write_bit(plan.strategy[blk][self.nfchans] != Strategy::Reuse); |
| 693 | } |
| 694 | for ch in 0..self.nfchans { |
| 695 | if plan.strategy[blk][ch] != Strategy::Reuse { |
| 696 | w.write_bits(self.chbwcod, 6); |
| 697 | } |
| 698 | } |
| 699 | for ch in 0..self.nfchans { |
| 700 | if plan.strategy[blk][ch] != Strategy::Reuse { |
| 701 | write_exp_groups(w, &plan.sent[blk][ch]); |
| 702 | w.write_bits(0, 2); |
| 703 | } |
| 704 | } |
| 705 | if self.lfeon && plan.strategy[blk][self.nfchans] != Strategy::Reuse { |
| 706 | write_exp_groups(w, &plan.sent[blk][self.nfchans]); |
| 707 | } |
| 708 | |
| 709 | |
| 710 | |
| 711 | w.write_bit(first); |
| 712 | if first { |
| 713 | w.write_bits(u32::from(BA_PARAMS.sdcycod), 2); |
| 714 | w.write_bits(u32::from(BA_PARAMS.fdcycod), 2); |
| 715 | w.write_bits(u32::from(BA_PARAMS.sgaincod), 2); |
| 716 | w.write_bits(u32::from(BA_PARAMS.dbpbcod), 2); |
| 717 | w.write_bits(u32::from(BA_PARAMS.floorcod), 3); |
| 718 | } |
| 719 | w.write_bit(first); |
| 720 | if first { |
| 721 | w.write_bits(u32::from(csnroffst), 6); |
| 722 | for _ in 0..self.coded { |
| 723 | w.write_bits(u32::from(fsnroffst), 4); |
| 724 | w.write_bits(u32::from(FGAINCOD), 3); |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | w.write_bit(false); |
| 729 | w.write_bit(false); |
| 730 | |
| 731 | let values: Vec<(u8, f32)> = (0..self.coded) |
| 732 | .flat_map(|ch| (0..endmant[ch]).map(move |bin| (ch, bin))) |
| 733 | .map(|(ch, bin)| (bap[blk][ch][bin], coeffs[blk][ch][bin] * scale(plan.exps[blk][ch][bin]))) |
| 734 | .collect(); |
| 735 | write_mantissas(w, &values); |
| 736 | } |
| 737 | |
| 738 | |
| 739 | |
| 740 | |
| 741 | fn finish_frame(&self, mut w: BitWriter) -> Vec<u8> { |
| 742 | w.write_bit(false); |
| 743 | w.write_bit(false); |
| 744 | while (w.bit_len() as usize) < self.frame_bytes * 8 - 16 { |
| 745 | w.write_bit(false); |
| 746 | } |
| 747 | w.write_bits(0, 16); |
| 748 | w.align_to_byte(); |
| 749 | let mut bytes = w.into_bytes(); |
| 750 | bytes.resize(self.frame_bytes, 0); |
| 751 | |
| 752 | |
| 753 | let frame_size_58 = ((self.frame_bytes >> 2) + (self.frame_bytes >> 4)) << 1; |
| 754 | let crc1 = crc16(&bytes[4..frame_size_58]); |
| 755 | bytes[2..4].copy_from_slice(&crc1.to_be_bytes()); |
| 756 | let crc2 = crc16(&bytes[2..self.frame_bytes - 2]); |
| 757 | bytes[self.frame_bytes - 2..].copy_from_slice(&crc2.to_be_bytes()); |
| 758 | bytes |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | |
| 763 | |
| 764 | struct Plan { |
| 765 | |
| 766 | blksw: Vec<Vec<bool>>, |
| 767 | |
| 768 | strategy: Vec<Vec<Strategy>>, |
| 769 | |
| 770 | |
| 771 | sent: Vec<Vec<Vec<u8>>>, |
| 772 | |
| 773 | |
| 774 | exps: Vec<Vec<[u8; COEFFS]>>, |
| 775 | } |
| 776 | |
| 777 | |
| 778 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 779 | pub struct EncodeStats { |
| 780 | |
| 781 | pub frames: u64, |
| 782 | |
| 783 | pub blksw_blocks: u64, |
| 784 | |
| 785 | pub d15: u64, |
| 786 | |
| 787 | pub d25: u64, |
| 788 | |
| 789 | pub d45: u64, |
| 790 | |
| 791 | pub reuse: u64, |
| 792 | |
| 793 | pub csnroffst_sum: u64, |
| 794 | |
| 795 | pub bits_used: u64, |
| 796 | |
| 797 | pub bits_budget: u64, |
| 798 | } |
| 799 | |
| 800 | |
| 801 | fn strategy_code(strategy: Strategy) -> u32 { |
| 802 | match strategy { |
| 803 | Strategy::Reuse => 0, |
| 804 | Strategy::D15 => 1, |
| 805 | Strategy::D25 => 2, |
| 806 | Strategy::D45 => 3, |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | |
| 811 | |
| 812 | |
| 813 | |
| 814 | fn chbwcod_for(kbps: u32, nfchans: usize) -> u32 { |
| 815 | match kbps / nfchans as u32 { |
| 816 | 80.. => 60, |
| 817 | 56.. => 48, |
| 818 | 40.. => 40, |
| 819 | 28.. => 32, |
| 820 | _ => 24, |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | |
| 825 | |
| 826 | |
| 827 | |
| 828 | |
| 829 | |
| 830 | fn is_transient(window_in: &[f32; 512]) -> bool { |
| 831 | let mut energy = [0.0f32; 8]; |
| 832 | for (i, seg) in energy.iter_mut().enumerate() { |
| 833 | *seg = (i * 64..(i + 1) * 64) |
| 834 | .map(|n| { |
| 835 | let d = window_in[n] - window_in[n.saturating_sub(1)]; |
| 836 | d * d |
| 837 | }) |
| 838 | .sum(); |
| 839 | } |
| 840 | (4..8).any(|j| { |
| 841 | let before = energy[..j].iter().copied().fold(0.0f32, f32::max); |
| 842 | energy[j] > TRANSIENT_FLOOR && energy[j] > TRANSIENT_RATIO * before |
| 843 | }) |
| 844 | } |
| 845 | |
| 846 | |
| 847 | |
| 848 | |
| 849 | fn ideal_exps(coeffs: &[f32; COEFFS], endmant: usize) -> [u8; COEFFS] { |
| 850 | let mut e = [24u8; COEFFS]; |
| 851 | for bin in 0..endmant { |
| 852 | let mag = coeffs[bin].abs(); |
| 853 | e[bin] = if mag <= 0.0 { 24 } else { (-mag.log2()).floor().clamp(0.0, 24.0) as u8 }; |
| 854 | } |
| 855 | e |
| 856 | } |
| 857 | |
| 858 | |
| 859 | |
| 860 | |
| 861 | |
| 862 | |
| 863 | fn envelope_moved(a: &[u8; COEFFS], b: &[u8; COEFFS], endmant: usize) -> bool { |
| 864 | let loudest = a[..endmant].iter().min().unwrap().min(b[..endmant].iter().min().unwrap()); |
| 865 | a[..endmant].chunks(12).zip(b[..endmant].chunks(12)).any(|(x, y)| { |
| 866 | let (px, py) = (*x.iter().min().unwrap(), *y.iter().min().unwrap()); |
| 867 | px.min(py) <= loudest + 10 && px.abs_diff(py) > RESEND_STEPS |
| 868 | }) |
| 869 | } |
| 870 | |
| 871 | |
| 872 | |
| 873 | |
| 874 | |
| 875 | |
| 876 | fn plan_exponents(ideal: &[u8; COEFFS], endmant: usize, strategy: Strategy) -> (Vec<u8>, [u8; COEFFS]) { |
| 877 | let gs = strategy.group_size(); |
| 878 | let ngrps = strategy.fbw_groups(endmant); |
| 879 | let mut sent = vec![ideal[0].min(15)]; |
| 880 | for g in 0..ngrps * 3 { |
| 881 | let lo = 1 + g * gs; |
| 882 | let hi = (lo + gs).min(endmant); |
| 883 | sent.push(if lo < hi { *ideal[lo..hi].iter().min().unwrap() } else { 24 }); |
| 884 | } |
| 885 | smooth_exps(&mut sent); |
| 886 | let mut exps = [24u8; COEFFS]; |
| 887 | exps[0] = sent[0]; |
| 888 | for g in 0..ngrps * 3 { |
| 889 | for bin in 1 + g * gs..(1 + (g + 1) * gs).min(COEFFS) { |
| 890 | exps[bin] = sent[g + 1]; |
| 891 | } |
| 892 | } |
| 893 | (sent, exps) |
| 894 | } |
| 895 | |
| 896 | |
| 897 | |
| 898 | |
| 899 | fn scale(exponent: u8) -> f32 { |
| 900 | f32::from_bits(127u32.wrapping_add(u32::from(exponent)) << 23) |
| 901 | } |
| 902 | |
| 903 | |
| 904 | fn floats(plane: &Buf, count: usize) -> Vec<f32> { |
| 905 | plane |
| 906 | .as_chunks::<4>() |
| 907 | .0 |
| 908 | .iter() |
| 909 | .take(count) |
| 910 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 911 | .collect() |
| 912 | } |
| 913 | |
| 914 | impl Encoder for Ac3Encoder { |
| 915 | fn codec_parameters(&self) -> &CodecParameters { |
| 916 | &self.params |
| 917 | } |
| 918 | |
| 919 | fn send_frame(&mut self, frame: &Frame) -> Result<()> { |
| 920 | let Frame::Audio(audio) = frame else { |
| 921 | return Err(Error::corrupt("video frame pushed into an audio encoder")); |
| 922 | }; |
| 923 | if audio.format != SampleFormat::F32 { |
| 924 | return Err(Error::unsupported( |
| 925 | format!("{:?} input", audio.format), |
| 926 | "this encoder takes 32-bit float samples", |
| 927 | )); |
| 928 | } |
| 929 | let channels = self.coded; |
| 930 | let interleaved = if audio.planar { |
| 931 | let mut out = vec![0.0f32; audio.samples * channels]; |
| 932 | for (c, plane) in audio.data.iter().enumerate().take(channels) { |
| 933 | for (n, v) in floats(plane, audio.samples).into_iter().enumerate() { |
| 934 | out[n * channels + c] = v; |
| 935 | } |
| 936 | } |
| 937 | out |
| 938 | } else { |
| 939 | floats(&audio.data[0], audio.samples * channels) |
| 940 | }; |
| 941 | self.push_pcm_f32(&interleaved) |
| 942 | } |
| 943 | |
| 944 | fn receive_packet(&mut self) -> Result<Packet> { |
| 945 | let data = self.next_packet()?; |
| 946 | let base = TimeBase::new(1, i64::from(self.config.sample_rate)); |
| 947 | let mut packet = Packet::new(0, base, data); |
| 948 | packet.duration = Some(FRAME_SAMPLES as i64); |
| 949 | Ok(packet) |
| 950 | } |
| 951 | |
| 952 | fn flush(&mut self) -> Result<()> { |
| 953 | self.finish(); |
| 954 | Ok(()) |
| 955 | } |
| 956 | } |
| 957 | |
| 958 | #[cfg(test)] |
| 959 | mod tests { |
| 960 | use super::*; |
| 961 | |
| 962 | fn lcg(seed: &mut u64) -> f32 { |
| 963 | *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); |
| 964 | ((*seed >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0 |
| 965 | } |
| 966 | |
| 967 | |
| 968 | fn direct_forward(x: &[f32; 512], window: &[f32; 512]) -> [f32; COEFFS] { |
| 969 | let mut out = [0.0f32; COEFFS]; |
| 970 | for (k, o) in out.iter_mut().enumerate() { |
| 971 | let mut acc = 0.0f64; |
| 972 | for n in 0..512 { |
| 973 | let arg = 2.0 * std::f64::consts::PI / 512.0 * (n as f64 + 0.5 + 128.0) * (k as f64 + 0.5); |
| 974 | acc += f64::from(x[n] * window[n]) * arg.cos(); |
| 975 | } |
| 976 | *o = acc as f32; |
| 977 | } |
| 978 | out |
| 979 | } |
| 980 | |
| 981 | |
| 982 | |
| 983 | |
| 984 | |
| 985 | fn tdac_pattern(pattern: [bool; 7], forward: impl Fn(&[f32; 512], bool) -> [f32; COEFFS]) -> (f32, f64) { |
| 986 | let mut seed = 7u64; |
| 987 | let signal: Vec<f32> = (0..256 * 8).map(|_| lcg(&mut seed)).collect(); |
| 988 | let mut imdct = Imdct::new(); |
| 989 | let mut delay = [0.0f32; 256]; |
| 990 | let mut out = [0.0f32; 256]; |
| 991 | let mut worst = 0.0f32; |
| 992 | let (mut dot, mut nrm) = (0.0f64, 0.0f64); |
| 993 | for (blk, &short) in pattern.iter().enumerate() { |
| 994 | let mut x = [0.0f32; 512]; |
| 995 | x.copy_from_slice(&signal[blk * 256..blk * 256 + 512]); |
| 996 | let spec = forward(&x, short); |
| 997 | imdct.block(&spec, short, &mut delay, &mut out); |
| 998 | if blk > 0 { |
| 999 | |
| 1000 | for n in 0..256 { |
| 1001 | worst = worst.max((out[n] - signal[blk * 256 + n]).abs()); |
| 1002 | dot += f64::from(out[n] * signal[blk * 256 + n]); |
| 1003 | nrm += f64::from(signal[blk * 256 + n] * signal[blk * 256 + n]); |
| 1004 | } |
| 1005 | } |
| 1006 | } |
| 1007 | (worst, dot / nrm) |
| 1008 | } |
| 1009 | |
| 1010 | fn tdac(forward: impl Fn(&[f32; 512]) -> [f32; COEFFS]) -> f32 { |
| 1011 | let (worst, gain) = tdac_pattern([false; 7], |x, _| forward(x)); |
| 1012 | assert!((gain - 1.0).abs() < 1e-4, "least-squares gain out/in = {gain}"); |
| 1013 | worst |
| 1014 | } |
| 1015 | |
| 1016 | #[test] |
| 1017 | fn tdac_short_forward_reconstructs_against_long_and_short_neighbours() { |
| 1018 | let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap(); |
| 1019 | let window = enc.window; |
| 1020 | let basis = enc.short_basis.clone(); |
| 1021 | let cell = std::cell::RefCell::new(&mut enc.mdct); |
| 1022 | let (worst, gain) = tdac_pattern([false, true, true, false, true, false, true], |x, short| { |
| 1023 | let mut s = [0.0f32; COEFFS]; |
| 1024 | if short { |
| 1025 | for (k, out) in s.iter_mut().enumerate() { |
| 1026 | let row = &basis[k * 512..(k + 1) * 512]; |
| 1027 | *out = SHORT_GAIN * row.iter().zip(x).map(|(a, b)| a * b).sum::<f32>(); |
| 1028 | } |
| 1029 | } else { |
| 1030 | cell.borrow_mut().forward_windowed(x, &window, &mut s); |
| 1031 | for v in &mut s { |
| 1032 | *v *= FORWARD_GAIN; |
| 1033 | } |
| 1034 | } |
| 1035 | s |
| 1036 | }); |
| 1037 | let (w2, g2) = tdac_pattern([true; 7], |x, _| { |
| 1038 | let mut s = [0.0f32; COEFFS]; |
| 1039 | for (k, out) in s.iter_mut().enumerate() { |
| 1040 | let row = &basis[k * 512..(k + 1) * 512]; |
| 1041 | *out = SHORT_GAIN * row.iter().zip(x).map(|(a, b)| a * b).sum::<f32>(); |
| 1042 | } |
| 1043 | s |
| 1044 | }); |
| 1045 | eprintln!("all-short: worst {w2} gain {g2}; mixed: worst {worst} gain {gain}"); |
| 1046 | assert!((gain - 1.0).abs() < 1e-4, "least-squares gain out/in = {gain}"); |
| 1047 | assert!(worst < 1e-4, "short forward + Imdct TDAC error {worst}"); |
| 1048 | } |
| 1049 | |
| 1050 | fn encode_one(pcm: &[f32]) -> EncodeStats { |
| 1051 | let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 96 }).unwrap(); |
| 1052 | enc.push_pcm_f32(pcm).unwrap(); |
| 1053 | enc.stats() |
| 1054 | } |
| 1055 | |
| 1056 | #[test] |
| 1057 | fn stationary_tone_plans_one_d45_set_and_reuses_it() { |
| 1058 | let pcm: Vec<f32> = (0..FRAME_SAMPLES * 2) |
| 1059 | .map(|n| 0.5 * (2.0 * std::f32::consts::PI * 1000.0 * n as f32 / 48000.0).sin()) |
| 1060 | .collect(); |
| 1061 | let stats = encode_one(&pcm); |
| 1062 | assert_eq!(stats.frames, 2); |
| 1063 | |
| 1064 | |
| 1065 | |
| 1066 | assert!(stats.blksw_blocks <= 1, "{stats:?}"); |
| 1067 | assert!(stats.d45 >= 1 && stats.d15 == 0 && stats.d25 <= 1, "{stats:?}"); |
| 1068 | assert!(stats.reuse >= 5, "{stats:?}"); |
| 1069 | assert!(stats.bits_used * 10 > stats.bits_budget * 9, "rate loop left bits unused: {stats:?}"); |
| 1070 | } |
| 1071 | |
| 1072 | #[test] |
| 1073 | fn a_click_switches_to_short_blocks_and_d25() { |
| 1074 | let mut pcm = vec![0.0f32; FRAME_SAMPLES]; |
| 1075 | for n in 0..FRAME_SAMPLES { |
| 1076 | pcm[n] = 0.01 * ((n as f32) * 0.3).sin(); |
| 1077 | } |
| 1078 | pcm[256 * 3 + 100] = 0.9; |
| 1079 | pcm[256 * 3 + 101] = -0.9; |
| 1080 | let stats = encode_one(&pcm); |
| 1081 | assert_eq!(stats.blksw_blocks, 1, "{stats:?}"); |
| 1082 | assert!(stats.d25 >= 1 && stats.d15 == 0, "{stats:?}"); |
| 1083 | } |
| 1084 | |
| 1085 | #[test] |
| 1086 | fn smoothed_exponents_never_rise_and_always_fit_the_group_coding() { |
| 1087 | let mut e = [24u8; COEFFS]; |
| 1088 | e[100] = 1; |
| 1089 | e[0] = 20; |
| 1090 | let ideal = e; |
| 1091 | smooth_exps(&mut e); |
| 1092 | assert!(e.iter().zip(&ideal).all(|(s, i)| s <= i)); |
| 1093 | assert!(e.windows(2).all(|w| (i32::from(w[0]) - i32::from(w[1])).abs() <= 2)); |
| 1094 | assert_eq!((e[0], e[99], e[100], e[101]), (15, 3, 1, 3)); |
| 1095 | let mut again = e; |
| 1096 | smooth_exps(&mut again); |
| 1097 | assert_eq!(again, e); |
| 1098 | } |
| 1099 | |
| 1100 | #[test] |
| 1101 | fn tdac_direct_forward_reconstructs() { |
| 1102 | let enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap(); |
| 1103 | let window = enc.window; |
| 1104 | |
| 1105 | let err = tdac(|x| { |
| 1106 | let mut s = direct_forward(x, &window); |
| 1107 | for v in &mut s { |
| 1108 | *v *= -2.0 / 512.0; |
| 1109 | } |
| 1110 | s |
| 1111 | }); |
| 1112 | assert!(err < 1e-4, "direct forward + Imdct TDAC error {err}"); |
| 1113 | } |
| 1114 | |
| 1115 | #[test] |
| 1116 | fn tdac_ec_dsp_forward_reconstructs() { |
| 1117 | let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap(); |
| 1118 | let window = enc.window; |
| 1119 | let cell = std::cell::RefCell::new(&mut enc.mdct); |
| 1120 | let err = tdac(|x| { |
| 1121 | let mut s = [0.0f32; COEFFS]; |
| 1122 | cell.borrow_mut().forward_windowed(x, &window, &mut s); |
| 1123 | for v in &mut s { |
| 1124 | *v *= FORWARD_GAIN; |
| 1125 | } |
| 1126 | s |
| 1127 | }); |
| 1128 | assert!(err < 1e-4, "ec_dsp forward + Imdct TDAC error {err}"); |
| 1129 | } |
| 1130 | } |