| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | use ec_core::{ |
| 43 | AudioParameters, Buf, CodecId, CodecParameters, Encoder, Error, Frame, MediaParameters, Packet, |
| 44 | Result, SampleFormat, TimeBase, |
| 45 | }; |
| 46 | use ec_dsp::Mdct; |
| 47 | |
| 48 | use crate::bits::{BitsOut, float32_pack}; |
| 49 | use crate::codebook::{CodebookSpec, ilog, lookup1_values}; |
| 50 | use crate::decode::channel_map; |
| 51 | use crate::floor::render_floor1; |
| 52 | use crate::setup::Floor1; |
| 53 | use crate::window::Windows; |
| 54 | |
| 55 | |
| 56 | const BLOCK_LONG: usize = 2048; |
| 57 | |
| 58 | const BLOCK_SHORT: usize = 256; |
| 59 | |
| 60 | const HALF_LONG: usize = BLOCK_LONG / 2; |
| 61 | |
| 62 | const HALF_SHORT: usize = BLOCK_SHORT / 2; |
| 63 | |
| 64 | const PARTITION_LONG: usize = 16; |
| 65 | |
| 66 | const PARTITION_SHORT: usize = 16; |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | const FLOOR_POINTS_LONG: usize = 12; |
| 72 | |
| 73 | const FLOOR_POINTS_SHORT: usize = 8; |
| 74 | |
| 75 | const FLOOR_CLASS_DIM: usize = 4; |
| 76 | |
| 77 | const CLASSES: usize = 9; |
| 78 | |
| 79 | const CLASS_RANGE: [i32; CLASSES] = [0, 1, 2, 4, 8, 16, 32, 64, 127]; |
| 80 | |
| 81 | const RESIDUE_BOOK_DIM: [usize; CLASSES] = [0, 4, 2, 2, 1, 1, 1, 1, 1]; |
| 82 | |
| 83 | |
| 84 | const RATE_TARGET_SCALE: f64 = 0.97; |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | const HEADROOM_RANGE: f64 = 36.0; |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | const HEADROOM_RANGE_SHORT: f64 = 42.0; |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | const CO_MASK_RANGE: f64 = 50.0; |
| 105 | |
| 106 | |
| 107 | |
| 108 | const MASKING_OFFSET_DB: f64 = 9.0; |
| 109 | |
| 110 | |
| 111 | const NOISE_NORMALISE_MIN_RATIO: f32 = 0.5; |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | const CO_MASK_RANGE_SHORT: f64 = f64::INFINITY; |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | const POINT_STEREO_HZ: f64 = 4_000.0; |
| 124 | |
| 125 | const HEADROOM_SHORT_MIN: f64 = 42.0; |
| 126 | |
| 127 | |
| 128 | const TICK: usize = BLOCK_SHORT / 4; |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | const SHORT_RUN: u8 = 16; |
| 136 | |
| 137 | const MODE_SHORT: u32 = 0; |
| 138 | |
| 139 | const MODE_LONG: u32 = 1; |
| 140 | |
| 141 | |
| 142 | const TRANSIENT_RATIO: f64 = 14.0; |
| 143 | |
| 144 | |
| 145 | |
| 146 | const TRANSIENT_FLOOR: f64 = 1e-6; |
| 147 | |
| 148 | const TRANSIENT_HISTORY: usize = 4; |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | const PREROLL: usize = HALF_LONG; |
| 154 | |
| 155 | |
| 156 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 157 | pub struct EncoderConfig { |
| 158 | |
| 159 | pub sample_rate: u32, |
| 160 | |
| 161 | pub channels: u16, |
| 162 | |
| 163 | pub bitrate_bps: i32, |
| 164 | |
| 165 | |
| 166 | pub quality: f32, |
| 167 | } |
| 168 | |
| 169 | impl Default for EncoderConfig { |
| 170 | fn default() -> EncoderConfig { |
| 171 | EncoderConfig { |
| 172 | sample_rate: 48_000, |
| 173 | channels: 2, |
| 174 | bitrate_bps: 128_000, |
| 175 | quality: 0.5, |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | |
| 181 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 182 | pub struct EncodedPacket { |
| 183 | |
| 184 | pub data: Vec<u8>, |
| 185 | |
| 186 | pub granule: i64, |
| 187 | |
| 188 | pub samples: i64, |
| 189 | } |
| 190 | |
| 191 | |
| 192 | |
| 193 | #[derive(Debug, Clone, Copy)] |
| 194 | struct BlockPlan { |
| 195 | is_long: bool, |
| 196 | prev_long: bool, |
| 197 | next_long: bool, |
| 198 | } |
| 199 | |
| 200 | |
| 201 | #[derive(Debug, Clone, Copy)] |
| 202 | enum Sched { |
| 203 | |
| 204 | |
| 205 | Steady, |
| 206 | |
| 207 | ShortRun(u8), |
| 208 | |
| 209 | TransitionIn, |
| 210 | } |
| 211 | |
| 212 | |
| 213 | struct BlockConfig { |
| 214 | half: usize, |
| 215 | partition: usize, |
| 216 | floor: Floor1, |
| 217 | ath: Vec<f64>, |
| 218 | bark: Vec<f64>, |
| 219 | |
| 220 | range: f64, |
| 221 | |
| 222 | co_mask: f64, |
| 223 | } |
| 224 | |
| 225 | |
| 226 | pub struct VorbisEncoder { |
| 227 | config: EncoderConfig, |
| 228 | params: CodecParameters, |
| 229 | |
| 230 | to_vorbis: Vec<usize>, |
| 231 | headers: Vec<Vec<u8>>, |
| 232 | long: BlockConfig, |
| 233 | short: BlockConfig, |
| 234 | floor_book: CodebookSpec, |
| 235 | class_book: CodebookSpec, |
| 236 | residue_books: Vec<CodebookSpec>, |
| 237 | |
| 238 | coupling: Vec<(usize, usize)>, |
| 239 | mdct_long: Mdct<f32>, |
| 240 | mdct_short: Mdct<f32>, |
| 241 | windows: Windows, |
| 242 | |
| 243 | |
| 244 | buffer: Vec<Vec<f32>>, |
| 245 | |
| 246 | fed: i64, |
| 247 | |
| 248 | blocks_emitted: i64, |
| 249 | |
| 250 | |
| 251 | |
| 252 | centre: i64, |
| 253 | |
| 254 | prev_n: usize, |
| 255 | |
| 256 | granule: i64, |
| 257 | scheduler: Sched, |
| 258 | |
| 259 | headroom: f64, |
| 260 | finished: bool, |
| 261 | packets: std::collections::VecDeque<EncodedPacket>, |
| 262 | } |
| 263 | |
| 264 | impl VorbisEncoder { |
| 265 | |
| 266 | pub fn new(config: EncoderConfig) -> Result<VorbisEncoder> { |
| 267 | let channels = usize::from(config.channels); |
| 268 | if channels == 0 || channels > 255 { |
| 269 | return Err(Error::unsupported( |
| 270 | format!("{channels} channels"), |
| 271 | "Vorbis states a channel count in one byte", |
| 272 | )); |
| 273 | } |
| 274 | if config.sample_rate == 0 { |
| 275 | return Err(Error::corrupt("encoder sample rate of zero")); |
| 276 | } |
| 277 | let (layout, to_ec) = channel_map(channels); |
| 278 | let mut to_vorbis = vec![0usize; channels]; |
| 279 | for (vorbis, &ec) in to_ec.iter().enumerate() { |
| 280 | to_vorbis[ec] = vorbis; |
| 281 | } |
| 282 | |
| 283 | |
| 284 | let coupling = match channels { |
| 285 | 2 => vec![(0usize, 1usize)], |
| 286 | _ => Vec::new(), |
| 287 | }; |
| 288 | |
| 289 | let floor_book = design_floor_book(); |
| 290 | let class_book = design_class_book(); |
| 291 | let residue_books = design_residue_books(); |
| 292 | let long = build_block_config( |
| 293 | HALF_LONG, |
| 294 | PARTITION_LONG, |
| 295 | FLOOR_POINTS_LONG, |
| 296 | HEADROOM_RANGE, |
| 297 | CO_MASK_RANGE, |
| 298 | &config, |
| 299 | ); |
| 300 | let short = build_block_config( |
| 301 | HALF_SHORT, |
| 302 | PARTITION_SHORT, |
| 303 | FLOOR_POINTS_SHORT, |
| 304 | HEADROOM_RANGE_SHORT, |
| 305 | CO_MASK_RANGE_SHORT, |
| 306 | &config, |
| 307 | ); |
| 308 | |
| 309 | let headers = write_headers( |
| 310 | &config, |
| 311 | channels, |
| 312 | HeaderSetup { |
| 313 | long: &long, |
| 314 | short: &short, |
| 315 | floor_book: &floor_book, |
| 316 | class_book: &class_book, |
| 317 | residue_books: &residue_books, |
| 318 | coupling: &coupling, |
| 319 | }, |
| 320 | ); |
| 321 | let params = CodecParameters { |
| 322 | codec: CodecId::Vorbis, |
| 323 | media: MediaParameters::Audio(AudioParameters { |
| 324 | sample_rate: config.sample_rate, |
| 325 | layout, |
| 326 | format: Some(SampleFormat::F32), |
| 327 | bits_per_sample: None, |
| 328 | }), |
| 329 | extradata: Some(Buf::from_vec(lace(&headers))), |
| 330 | }; |
| 331 | |
| 332 | let quality = f64::from(config.quality.clamp(0.0, 1.0)); |
| 333 | Ok(VorbisEncoder { |
| 334 | mdct_long: Mdct::new(BLOCK_LONG), |
| 335 | mdct_short: Mdct::new(BLOCK_SHORT), |
| 336 | windows: Windows::new(BLOCK_SHORT, BLOCK_LONG), |
| 337 | buffer: vec![vec![0.0; PREROLL]; channels], |
| 338 | fed: 0, |
| 339 | blocks_emitted: 0, |
| 340 | centre: -(HALF_LONG as i64), |
| 341 | prev_n: BLOCK_LONG, |
| 342 | granule: 0, |
| 343 | scheduler: Sched::Steady, |
| 344 | headroom: 4.0 + 26.0 * quality, |
| 345 | finished: false, |
| 346 | packets: std::collections::VecDeque::new(), |
| 347 | config, |
| 348 | params, |
| 349 | to_vorbis, |
| 350 | headers, |
| 351 | long, |
| 352 | short, |
| 353 | floor_book, |
| 354 | class_book, |
| 355 | residue_books, |
| 356 | coupling, |
| 357 | }) |
| 358 | } |
| 359 | |
| 360 | |
| 361 | pub fn headers(&self) -> Vec<&[u8]> { |
| 362 | self.headers.iter().map(|h| &h[..]).collect() |
| 363 | } |
| 364 | |
| 365 | |
| 366 | pub fn extradata(&self) -> Vec<u8> { |
| 367 | lace(&self.headers) |
| 368 | } |
| 369 | |
| 370 | |
| 371 | pub fn parameters(&self) -> &CodecParameters { |
| 372 | &self.params |
| 373 | } |
| 374 | |
| 375 | |
| 376 | pub fn push_planar(&mut self, channels: &[&[f32]]) -> Result<()> { |
| 377 | if channels.len() != usize::from(self.config.channels) { |
| 378 | return Err(Error::corrupt(format!( |
| 379 | "{} channels pushed into a {}-channel encoder", |
| 380 | channels.len(), |
| 381 | self.config.channels |
| 382 | ))); |
| 383 | } |
| 384 | if self.finished { |
| 385 | return Err(Error::corrupt("samples pushed after finish")); |
| 386 | } |
| 387 | let samples = channels.first().map_or(0, |c| c.len()); |
| 388 | for (ec, data) in channels.iter().enumerate() { |
| 389 | if data.len() != samples { |
| 390 | return Err(Error::corrupt("channels of different lengths")); |
| 391 | } |
| 392 | self.buffer[self.to_vorbis[ec]].extend_from_slice(data); |
| 393 | } |
| 394 | self.fed += samples as i64; |
| 395 | self.encode_ready(); |
| 396 | Ok(()) |
| 397 | } |
| 398 | |
| 399 | |
| 400 | pub fn push_interleaved(&mut self, samples: &[f32]) -> Result<()> { |
| 401 | let channels = usize::from(self.config.channels); |
| 402 | if !samples.len().is_multiple_of(channels) { |
| 403 | return Err(Error::corrupt("interleaved push is not a whole frame")); |
| 404 | } |
| 405 | if self.finished { |
| 406 | return Err(Error::corrupt("samples pushed after finish")); |
| 407 | } |
| 408 | for (i, &value) in samples.iter().enumerate() { |
| 409 | self.buffer[self.to_vorbis[i % channels]].push(value); |
| 410 | } |
| 411 | self.fed += (samples.len() / channels) as i64; |
| 412 | self.encode_ready(); |
| 413 | Ok(()) |
| 414 | } |
| 415 | |
| 416 | |
| 417 | pub fn finish(&mut self) { |
| 418 | if self.finished { |
| 419 | return; |
| 420 | } |
| 421 | self.finished = true; |
| 422 | |
| 423 | |
| 424 | |
| 425 | |
| 426 | let needed = PREROLL + self.fed.max(0) as usize + 2 * BLOCK_LONG; |
| 427 | for channel in &mut self.buffer { |
| 428 | if channel.len() < needed { |
| 429 | channel.resize(needed, 0.0); |
| 430 | } |
| 431 | } |
| 432 | self.encode_ready(); |
| 433 | } |
| 434 | |
| 435 | |
| 436 | pub fn next_packet(&mut self) -> Result<EncodedPacket> { |
| 437 | match self.packets.pop_front() { |
| 438 | Some(packet) => Ok(packet), |
| 439 | None if self.finished => Err(Error::Eof), |
| 440 | None => Err(Error::NeedMore), |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | |
| 445 | |
| 446 | fn peek_plan(&self) -> BlockPlan { |
| 447 | match self.scheduler { |
| 448 | Sched::Steady => BlockPlan { |
| 449 | is_long: true, |
| 450 | prev_long: true, |
| 451 | next_long: !self.transient_ahead(), |
| 452 | }, |
| 453 | Sched::ShortRun(_) => BlockPlan { |
| 454 | is_long: false, |
| 455 | prev_long: true, |
| 456 | next_long: true, |
| 457 | }, |
| 458 | Sched::TransitionIn => BlockPlan { |
| 459 | is_long: true, |
| 460 | prev_long: false, |
| 461 | next_long: true, |
| 462 | }, |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | |
| 467 | fn commit_plan(&mut self, plan: BlockPlan) { |
| 468 | self.scheduler = match self.scheduler { |
| 469 | Sched::Steady if !plan.next_long => Sched::ShortRun(SHORT_RUN), |
| 470 | Sched::Steady => Sched::Steady, |
| 471 | Sched::ShortRun(remaining) if remaining > 1 => Sched::ShortRun(remaining - 1), |
| 472 | Sched::ShortRun(_) => Sched::TransitionIn, |
| 473 | Sched::TransitionIn => Sched::Steady, |
| 474 | }; |
| 475 | } |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | |
| 484 | fn transient_ahead(&self) -> bool { |
| 485 | |
| 486 | |
| 487 | if self.centre == -(HALF_LONG as i64) { |
| 488 | return false; |
| 489 | } |
| 490 | let candidate_centre = self.centre + (self.prev_n + BLOCK_LONG) as i64 / 4; |
| 491 | let lookahead_centre = candidate_centre + BLOCK_LONG as i64 / 2; |
| 492 | let window_start = lookahead_centre - HALF_LONG as i64; |
| 493 | let buffer_start = window_start + PREROLL as i64; |
| 494 | if buffer_start < 0 || self.buffer[0].len() < (buffer_start as usize) + BLOCK_LONG { |
| 495 | return false; |
| 496 | } |
| 497 | let ticks = BLOCK_LONG / TICK; |
| 498 | let energy = |t: usize| -> f64 { |
| 499 | let start = buffer_start as usize + t * TICK; |
| 500 | let mut sum = 0.0f64; |
| 501 | for channel in &self.buffer { |
| 502 | for &s in &channel[start..start + TICK] { |
| 503 | sum += f64::from(s) * f64::from(s); |
| 504 | } |
| 505 | } |
| 506 | sum |
| 507 | }; |
| 508 | |
| 509 | |
| 510 | let floor = TRANSIENT_FLOOR * (TICK * self.buffer.len()) as f64; |
| 511 | for t in ticks / 2..ticks { |
| 512 | |
| 513 | |
| 514 | |
| 515 | let previous = (t.saturating_sub(TRANSIENT_HISTORY)..t) |
| 516 | .map(energy) |
| 517 | .fold(0.0f64, f64::max); |
| 518 | let current = energy(t); |
| 519 | if current > floor && current > previous * TRANSIENT_RATIO { |
| 520 | return true; |
| 521 | } |
| 522 | } |
| 523 | false |
| 524 | } |
| 525 | |
| 526 | |
| 527 | fn encode_ready(&mut self) { |
| 528 | let channels = usize::from(self.config.channels); |
| 529 | loop { |
| 530 | if self.finished && self.blocks_emitted > 0 && self.granule >= self.fed { |
| 531 | break; |
| 532 | } |
| 533 | let plan = self.peek_plan(); |
| 534 | let n = if plan.is_long { |
| 535 | BLOCK_LONG |
| 536 | } else { |
| 537 | BLOCK_SHORT |
| 538 | }; |
| 539 | let half = if plan.is_long { HALF_LONG } else { HALF_SHORT }; |
| 540 | let centre = self.centre + (self.prev_n + n) as i64 / 4; |
| 541 | let window_start = centre - (n / 2) as i64; |
| 542 | let buffer_start = window_start + PREROLL as i64; |
| 543 | if buffer_start < 0 || self.buffer[0].len() < buffer_start as usize + n { |
| 544 | break; |
| 545 | } |
| 546 | |
| 547 | |
| 548 | if !self.finished |
| 549 | && matches!(self.scheduler, Sched::Steady) |
| 550 | && self.buffer[0].len() < buffer_start as usize + n + BLOCK_LONG |
| 551 | { |
| 552 | break; |
| 553 | } |
| 554 | let granule = match self.finished { |
| 555 | true => centre.min(self.fed), |
| 556 | false => centre, |
| 557 | }; |
| 558 | let data = self.encode_block(buffer_start as usize, n, half, plan, channels); |
| 559 | self.packets.push_back(EncodedPacket { |
| 560 | data, |
| 561 | granule, |
| 562 | samples: (granule - self.granule).max(0), |
| 563 | }); |
| 564 | self.granule = granule; |
| 565 | self.centre = centre; |
| 566 | self.prev_n = n; |
| 567 | self.blocks_emitted += 1; |
| 568 | self.commit_plan(plan); |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | |
| 573 | fn encode_block( |
| 574 | &mut self, |
| 575 | start: usize, |
| 576 | n: usize, |
| 577 | half: usize, |
| 578 | plan: BlockPlan, |
| 579 | channels: usize, |
| 580 | ) -> Vec<u8> { |
| 581 | let bc = if plan.is_long { |
| 582 | &self.long |
| 583 | } else { |
| 584 | &self.short |
| 585 | }; |
| 586 | let partition = bc.partition; |
| 587 | let scale = 2.0 / half as f32; |
| 588 | let window = self |
| 589 | .windows |
| 590 | .get(plan.is_long, plan.prev_long, plan.next_long) |
| 591 | .to_vec(); |
| 592 | |
| 593 | let mut spectra: Vec<Vec<f32>> = Vec::with_capacity(channels); |
| 594 | let mut block = vec![0.0f32; n]; |
| 595 | for channel in 0..channels { |
| 596 | block.copy_from_slice(&self.buffer[channel][start..start + n]); |
| 597 | let mut coefficients = vec![0.0f32; half]; |
| 598 | let mdct = if plan.is_long { |
| 599 | &mut self.mdct_long |
| 600 | } else { |
| 601 | &mut self.mdct_short |
| 602 | }; |
| 603 | mdct.forward_windowed(&block, &window, &mut coefficients); |
| 604 | for value in coefficients.iter_mut() { |
| 605 | *value *= scale; |
| 606 | } |
| 607 | spectra.push(coefficients); |
| 608 | } |
| 609 | |
| 610 | |
| 611 | |
| 612 | |
| 613 | |
| 614 | |
| 615 | |
| 616 | |
| 617 | |
| 618 | |
| 619 | let limit = CLASS_RANGE[CLASSES - 1]; |
| 620 | |
| 621 | |
| 622 | |
| 623 | let transient_headroom = if self.config.bitrate_bps >= 128_000 { |
| 624 | 54.0 |
| 625 | } else { |
| 626 | HEADROOM_SHORT_MIN |
| 627 | }; |
| 628 | let headroom = match plan.is_long && plan.prev_long && plan.next_long { |
| 629 | true => self.headroom, |
| 630 | false => self.headroom.max(transient_headroom), |
| 631 | }; |
| 632 | let mut lift: Vec<Vec<f64>> = vec![vec![1.0; bc.floor.x_list.len()]; channels]; |
| 633 | |
| 634 | let spans: Vec<(usize, usize)> = bc |
| 635 | .floor |
| 636 | .x_list |
| 637 | .iter() |
| 638 | .map(|&x| { |
| 639 | let below = bc |
| 640 | .floor |
| 641 | .x_list |
| 642 | .iter() |
| 643 | .filter(|&&o| o < x) |
| 644 | .max() |
| 645 | .map_or(0, |&o| o as usize); |
| 646 | let above = bc |
| 647 | .floor |
| 648 | .x_list |
| 649 | .iter() |
| 650 | .filter(|&&o| o > x) |
| 651 | .min() |
| 652 | .map_or(half, |&o| o as usize); |
| 653 | (below, above) |
| 654 | }) |
| 655 | .collect(); |
| 656 | let mut passes = 0; |
| 657 | let steady = plan.is_long && plan.prev_long && plan.next_long; |
| 658 | let masking_offset = if !steady && self.config.bitrate_bps >= 128_000 { |
| 659 | 0.0 |
| 660 | } else { |
| 661 | MASKING_OFFSET_DB |
| 662 | }; |
| 663 | let (floor_values, quantised) = loop { |
| 664 | let mut curves: Vec<Vec<f32>> = vec![Vec::new(); channels]; |
| 665 | let mut floor_values: Vec<Vec<i32>> = vec![Vec::new(); channels]; |
| 666 | let mut fit = |group: &[usize]| { |
| 667 | let group_spectra: Vec<&Vec<f32>> = group.iter().map(|&c| &spectra[c]).collect(); |
| 668 | let mut peaks = peaks_of(&bc.floor, half, &group_spectra); |
| 669 | for &c in group { |
| 670 | for (peak, &boost) in peaks.iter_mut().zip(&lift[c]) { |
| 671 | *peak *= boost; |
| 672 | } |
| 673 | } |
| 674 | let (y, step2) = fit_floor( |
| 675 | &bc.floor, |
| 676 | &bc.ath, |
| 677 | &bc.bark, |
| 678 | headroom, |
| 679 | bc.range, |
| 680 | bc.co_mask, |
| 681 | masking_offset, |
| 682 | &peaks, |
| 683 | ); |
| 684 | let mut curve = vec![0.0f32; half]; |
| 685 | render_floor1(&bc.floor, &y, &step2, &mut curve); |
| 686 | for &c in group { |
| 687 | curves[c] = curve.clone(); |
| 688 | floor_values[c] = y.clone(); |
| 689 | } |
| 690 | }; |
| 691 | let mut coded = vec![false; channels]; |
| 692 | for &(magnitude, angle) in &self.coupling { |
| 693 | fit(&[magnitude, angle]); |
| 694 | coded[magnitude] = true; |
| 695 | coded[angle] = true; |
| 696 | } |
| 697 | for channel in (0..channels).filter(|&c| !coded[c]) { |
| 698 | fit(&[channel]); |
| 699 | } |
| 700 | |
| 701 | |
| 702 | |
| 703 | |
| 704 | |
| 705 | let mut quantised: Vec<Vec<i32>> = (0..channels) |
| 706 | .map(|channel| { |
| 707 | spectra[channel] |
| 708 | .iter() |
| 709 | .zip(curves[channel].iter()) |
| 710 | .map(|(&value, &floor)| { |
| 711 | if floor <= 0.0 || value.abs() <= floor { |
| 712 | 0 |
| 713 | } else { |
| 714 | (value / floor).round() as i32 |
| 715 | } |
| 716 | }) |
| 717 | .collect::<Vec<i32>>() |
| 718 | }) |
| 719 | .collect(); |
| 720 | for channel in 0..channels { |
| 721 | for (band, values) in quantised[channel].chunks_mut(partition).enumerate() { |
| 722 | if values.iter().any(|&value| value != 0) { |
| 723 | continue; |
| 724 | } |
| 725 | let start = band * partition; |
| 726 | let end = (start + values.len()).min(half); |
| 727 | let mut peak = (NOISE_NORMALISE_MIN_RATIO, 0usize, 0i32); |
| 728 | for bin in start..end { |
| 729 | let floor = curves[channel][bin]; |
| 730 | if floor <= 0.0 { |
| 731 | continue; |
| 732 | } |
| 733 | let value = spectra[channel][bin]; |
| 734 | let ratio = value.abs() / floor; |
| 735 | if ratio > peak.0 { |
| 736 | peak = (ratio, bin - start, value.signum() as i32); |
| 737 | } |
| 738 | } |
| 739 | if peak.2 != 0 { |
| 740 | values[peak.1] = peak.2; |
| 741 | } |
| 742 | } |
| 743 | } |
| 744 | for &(magnitude, angle) in &self.coupling { |
| 745 | let mut left = std::mem::take(&mut quantised[magnitude]); |
| 746 | let mut right = std::mem::take(&mut quantised[angle]); |
| 747 | let cutoff = if self.config.bitrate_bps >= 128_000 { |
| 748 | 6_000.0 |
| 749 | } else { |
| 750 | POINT_STEREO_HZ |
| 751 | }; |
| 752 | let point = match self.headroom < bc.range { |
| 753 | true => (cutoff / (f64::from(self.config.sample_rate) * 0.5) * half as f64) |
| 754 | as usize, |
| 755 | false => half, |
| 756 | }; |
| 757 | for (bin, (l, r)) in left.iter_mut().zip(right.iter_mut()).enumerate() { |
| 758 | let (m, a) = couple(*l, *r); |
| 759 | *l = m; |
| 760 | *r = if bin < point { |
| 761 | a |
| 762 | } else { |
| 763 | let delta = (spectra[magnitude][bin] - spectra[angle][bin]).abs(); |
| 764 | if delta > curves[magnitude][bin].max(curves[angle][bin]) { |
| 765 | a.signum() |
| 766 | } else { |
| 767 | 0 |
| 768 | } |
| 769 | }; |
| 770 | } |
| 771 | quantised[magnitude] = left; |
| 772 | quantised[angle] = right; |
| 773 | } |
| 774 | let mut clamps = false; |
| 775 | for (channel, values) in quantised.iter().enumerate() { |
| 776 | for (bin, &value) in values.iter().enumerate() { |
| 777 | if value.abs() <= limit { |
| 778 | continue; |
| 779 | } |
| 780 | clamps = true; |
| 781 | let excess = f64::from(value.abs()) / f64::from(limit) * 1.05; |
| 782 | for (point, &(below, above)) in spans.iter().enumerate() { |
| 783 | if bin >= below && bin <= above { |
| 784 | lift[channel][point] = lift[channel][point].max(excess); |
| 785 | } |
| 786 | } |
| 787 | } |
| 788 | } |
| 789 | passes += 1; |
| 790 | |
| 791 | if !clamps || passes == 8 { |
| 792 | for channel in quantised.iter_mut() { |
| 793 | for value in channel.iter_mut() { |
| 794 | *value = (*value).clamp(-limit, limit); |
| 795 | } |
| 796 | } |
| 797 | break (floor_values, quantised); |
| 798 | } |
| 799 | }; |
| 800 | |
| 801 | let mut out = BitsOut::new(); |
| 802 | out.bit(false); |
| 803 | let mode = if plan.is_long { MODE_LONG } else { MODE_SHORT }; |
| 804 | out.write(mode, 1); |
| 805 | if plan.is_long { |
| 806 | out.bit(plan.prev_long); |
| 807 | out.bit(plan.next_long); |
| 808 | } |
| 809 | for values in floor_values.iter().take(channels) { |
| 810 | write_floor(&mut out, &bc.floor, &self.floor_book, values); |
| 811 | } |
| 812 | write_residue( |
| 813 | &mut out, |
| 814 | &quantised, |
| 815 | half, |
| 816 | partition, |
| 817 | &self.class_book, |
| 818 | &self.residue_books, |
| 819 | ); |
| 820 | let bits = out.len(); |
| 821 | let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre; |
| 822 | self.update_rate(bits, half, channels, delta); |
| 823 | out.finish() |
| 824 | } |
| 825 | |
| 826 | |
| 827 | |
| 828 | |
| 829 | |
| 830 | |
| 831 | |
| 832 | |
| 833 | |
| 834 | |
| 835 | |
| 836 | fn update_rate(&mut self, bits: u64, half: usize, channels: usize, delta: i64) { |
| 837 | if self.config.bitrate_bps <= 0 || delta <= 0 { |
| 838 | return; |
| 839 | } |
| 840 | let target = f64::from(self.config.bitrate_bps) * RATE_TARGET_SCALE * delta as f64 |
| 841 | / f64::from(self.config.sample_rate); |
| 842 | let coefficients = (half * channels) as f64; |
| 843 | let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0); |
| 844 | |
| 845 | |
| 846 | |
| 847 | |
| 848 | |
| 849 | self.headroom = (self.headroom + step).clamp(-24.0, 84.0); |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | |
| 854 | |
| 855 | |
| 856 | |
| 857 | |
| 858 | fn peaks_of(floor: &Floor1, half: usize, spectra: &[&Vec<f32>]) -> Vec<f64> { |
| 859 | let x = &floor.x_list; |
| 860 | x.iter() |
| 861 | .map(|¢re| { |
| 862 | let below = x.iter().filter(|&&o| o < centre).max().copied(); |
| 863 | let above = x.iter().filter(|&&o| o > centre).min().copied(); |
| 864 | let lo = below.map_or(0, |b| ((b + centre) / 2) as usize); |
| 865 | let hi = above.map_or(half, |a| ((a + centre) / 2) as usize + 1); |
| 866 | let lo = lo.min(half - 1); |
| 867 | let hi = hi.clamp(lo + 1, half); |
| 868 | let mut peak = 0.0f64; |
| 869 | for spectrum in spectra { |
| 870 | for &value in &spectrum[lo..hi] { |
| 871 | peak = peak.max(f64::from(value.abs())); |
| 872 | } |
| 873 | } |
| 874 | peak |
| 875 | }) |
| 876 | .collect() |
| 877 | } |
| 878 | |
| 879 | |
| 880 | |
| 881 | |
| 882 | |
| 883 | |
| 884 | |
| 885 | fn fit_floor( |
| 886 | floor: &Floor1, |
| 887 | ath: &[f64], |
| 888 | bark: &[f64], |
| 889 | headroom: f64, |
| 890 | range: f64, |
| 891 | co_mask: f64, |
| 892 | masking_offset: f64, |
| 893 | peaks: &[f64], |
| 894 | ) -> (Vec<i32>, Vec<bool>) { |
| 895 | let db: Vec<f64> = peaks |
| 896 | .iter() |
| 897 | .map(|&peak| 20.0 * (peak.max(1e-9)).log10()) |
| 898 | .collect(); |
| 899 | let mut spread = db.clone(); |
| 900 | let order = &floor.sorted; |
| 901 | for window in order.windows(2) { |
| 902 | let (previous, current) = (window[0], window[1]); |
| 903 | spread[current] = spread[current].max(spread[previous] - 12.0); |
| 904 | } |
| 905 | for window in order.windows(2).rev() { |
| 906 | let (current, next) = (window[0], window[1]); |
| 907 | spread[current] = spread[current].max(spread[next] - 24.0); |
| 908 | } |
| 909 | for (source, &level) in db.iter().enumerate() { |
| 910 | for (target, masked) in spread.iter_mut().enumerate() { |
| 911 | let distance = (bark[target] - bark[source]).abs(); |
| 912 | if distance > 0.25 { |
| 913 | continue; |
| 914 | } |
| 915 | let slope = if bark[target] >= bark[source] { |
| 916 | 48.0 |
| 917 | } else { |
| 918 | 80.0 |
| 919 | }; |
| 920 | *masked = (*masked).max(level - slope * distance); |
| 921 | } |
| 922 | } |
| 923 | let loudest = db.iter().copied().fold(f64::MIN, f64::max); |
| 924 | let target: Vec<f64> = spread |
| 925 | .iter() |
| 926 | .zip(ath.iter()) |
| 927 | .map(|(&level, &threshold)| { |
| 928 | let threshold = threshold.max(loudest - co_mask); |
| 929 | let offset = (masking_offset - (headroom - range).max(0.0)).max(0.0); |
| 930 | (level - headroom.min(range) + offset) |
| 931 | .max(threshold - (headroom - range).max(0.0)) |
| 932 | }) |
| 933 | .collect(); |
| 934 | let y: Vec<i32> = target |
| 935 | .iter() |
| 936 | .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255)) |
| 937 | .collect(); |
| 938 | fold_floor(floor, &y) |
| 939 | } |
| 940 | |
| 941 | |
| 942 | |
| 943 | fn fold_floor(floor: &Floor1, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) { |
| 944 | let values = wanted.len(); |
| 945 | let range = 256i32; |
| 946 | let mut final_y = vec![0i32; values]; |
| 947 | let mut step2 = vec![false; values]; |
| 948 | final_y[0] = wanted[0]; |
| 949 | final_y[1] = wanted[1]; |
| 950 | step2[0] = true; |
| 951 | step2[1] = true; |
| 952 | for i in 2..values { |
| 953 | let (low, high) = floor.neighbours[i]; |
| 954 | let predicted = predict( |
| 955 | floor.x_list[low], |
| 956 | final_y[low], |
| 957 | floor.x_list[high], |
| 958 | final_y[high], |
| 959 | floor.x_list[i], |
| 960 | ); |
| 961 | let value = fold(predicted, wanted[i], range); |
| 962 | if value != 0 { |
| 963 | step2[low] = true; |
| 964 | step2[high] = true; |
| 965 | step2[i] = true; |
| 966 | } |
| 967 | final_y[i] = wanted[i]; |
| 968 | } |
| 969 | (final_y, step2) |
| 970 | } |
| 971 | |
| 972 | |
| 973 | |
| 974 | fn write_floor(out: &mut BitsOut, floor: &Floor1, floor_book: &CodebookSpec, y: &[i32]) { |
| 975 | out.bit(true); |
| 976 | out.write(y[0] as u32, 8); |
| 977 | out.write(y[1] as u32, 8); |
| 978 | for i in 2..y.len() { |
| 979 | let (low, high) = floor.neighbours[i]; |
| 980 | let predicted = predict( |
| 981 | floor.x_list[low], |
| 982 | y[low], |
| 983 | floor.x_list[high], |
| 984 | y[high], |
| 985 | floor.x_list[i], |
| 986 | ); |
| 987 | let value = fold(predicted, y[i], 256); |
| 988 | floor_book.write(out, value as usize); |
| 989 | } |
| 990 | } |
| 991 | |
| 992 | |
| 993 | |
| 994 | fn write_residue( |
| 995 | out: &mut BitsOut, |
| 996 | quantised: &[Vec<i32>], |
| 997 | half: usize, |
| 998 | partition: usize, |
| 999 | class_book: &CodebookSpec, |
| 1000 | residue_books: &[CodebookSpec], |
| 1001 | ) { |
| 1002 | let channels = quantised.len(); |
| 1003 | let total = half * channels; |
| 1004 | let mut interleaved = vec![0i32; total]; |
| 1005 | for (i, slot) in interleaved.iter_mut().enumerate() { |
| 1006 | *slot = quantised[i % channels][i / channels]; |
| 1007 | } |
| 1008 | let partitions = total / partition; |
| 1009 | let classes: Vec<usize> = (0..partitions) |
| 1010 | .map(|p| { |
| 1011 | let slice = &interleaved[p * partition..(p + 1) * partition]; |
| 1012 | let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0); |
| 1013 | CLASS_RANGE |
| 1014 | .iter() |
| 1015 | .position(|&range| peak <= range) |
| 1016 | .unwrap_or(CLASSES - 1) |
| 1017 | }) |
| 1018 | .collect(); |
| 1019 | let per_word = class_book.dimensions; |
| 1020 | let mut p = 0usize; |
| 1021 | while p < partitions { |
| 1022 | let mut word = 0usize; |
| 1023 | for i in 0..per_word { |
| 1024 | word = word * CLASSES + classes.get(p + i).copied().unwrap_or(0); |
| 1025 | } |
| 1026 | class_book.write(out, word); |
| 1027 | for _ in 0..per_word { |
| 1028 | if p >= partitions { |
| 1029 | break; |
| 1030 | } |
| 1031 | let class = classes[p]; |
| 1032 | if class > 0 { |
| 1033 | let book = &residue_books[class - 1]; |
| 1034 | let range = CLASS_RANGE[class]; |
| 1035 | for chunk in interleaved[p * partition..(p + 1) * partition].chunks(book.dimensions) |
| 1036 | { |
| 1037 | book.write(out, residue_entry(chunk, range, book.dimensions)); |
| 1038 | } |
| 1039 | } |
| 1040 | p += 1; |
| 1041 | } |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | |
| 1046 | fn residue_entry(values: &[i32], range: i32, dimensions: usize) -> usize { |
| 1047 | let base = (2 * range + 1) as usize; |
| 1048 | let mut entry = 0usize; |
| 1049 | let mut multiplier = 1usize; |
| 1050 | for i in 0..dimensions { |
| 1051 | let value = values.get(i).copied().unwrap_or(0).clamp(-range, range); |
| 1052 | entry += (value + range) as usize * multiplier; |
| 1053 | multiplier *= base; |
| 1054 | } |
| 1055 | entry |
| 1056 | } |
| 1057 | |
| 1058 | |
| 1059 | fn couple(left: i32, right: i32) -> (i32, i32) { |
| 1060 | match left > 0 { |
| 1061 | true => match left > right { |
| 1062 | true => (left, left - right), |
| 1063 | false => (right, left - right), |
| 1064 | }, |
| 1065 | false => match right > left { |
| 1066 | true => (left, right - left), |
| 1067 | false => (right, right - left), |
| 1068 | }, |
| 1069 | } |
| 1070 | } |
| 1071 | |
| 1072 | |
| 1073 | fn predict(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 { |
| 1074 | let dy = y1 - y0; |
| 1075 | let adx = (x1 - x0) as i32; |
| 1076 | let ady = dy.abs(); |
| 1077 | let off = (ady * (x - x0) as i32) / adx; |
| 1078 | match dy < 0 { |
| 1079 | true => y0 - off, |
| 1080 | false => y0 + off, |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | |
| 1085 | |
| 1086 | fn fold(predicted: i32, wanted: i32, range: i32) -> i32 { |
| 1087 | let high_room = range - predicted; |
| 1088 | let low_room = predicted; |
| 1089 | let room = high_room.min(low_room) * 2; |
| 1090 | let delta = wanted - predicted; |
| 1091 | if delta == 0 { |
| 1092 | return 0; |
| 1093 | } |
| 1094 | if delta > 0 && 2 * delta < room { |
| 1095 | return 2 * delta; |
| 1096 | } |
| 1097 | if delta < 0 && -2 * delta - 1 < room { |
| 1098 | return -2 * delta - 1; |
| 1099 | } |
| 1100 | match high_room > low_room { |
| 1101 | true => wanted - predicted + low_room, |
| 1102 | false => predicted - wanted + high_room - 1, |
| 1103 | } |
| 1104 | } |
| 1105 | |
| 1106 | |
| 1107 | |
| 1108 | fn build_floor(half: usize, points: usize) -> Floor1 { |
| 1109 | let mut sorted_x: Vec<u32> = Vec::with_capacity(points); |
| 1110 | let mut last = 0u32; |
| 1111 | for i in 0..points { |
| 1112 | let t = i as f64 / (points - 1) as f64; |
| 1113 | |
| 1114 | |
| 1115 | let value = ((half - 1) as f64).powf(t).round() as u32; |
| 1116 | last = value.max(last + 1); |
| 1117 | sorted_x.push(last.min(half as u32 - 1)); |
| 1118 | } |
| 1119 | |
| 1120 | |
| 1121 | let mut x_list = vec![0u32, half as u32]; |
| 1122 | let mut ranges = vec![(0usize, sorted_x.len())]; |
| 1123 | while let Some((lo, hi)) = ranges.pop() { |
| 1124 | if lo >= hi { |
| 1125 | continue; |
| 1126 | } |
| 1127 | let mid = (lo + hi) / 2; |
| 1128 | x_list.push(sorted_x[mid]); |
| 1129 | ranges.insert(0, (lo, mid)); |
| 1130 | ranges.insert(0, (mid + 1, hi)); |
| 1131 | } |
| 1132 | let values = x_list.len(); |
| 1133 | let mut sorted: Vec<usize> = (0..values).collect(); |
| 1134 | sorted.sort_by_key(|&i| x_list[i]); |
| 1135 | let neighbours = (0..values) |
| 1136 | .map(|i| { |
| 1137 | let mut low = 0usize; |
| 1138 | let mut high = 0usize; |
| 1139 | let mut low_x = None; |
| 1140 | let mut high_x = None; |
| 1141 | for j in 0..i { |
| 1142 | if x_list[j] < x_list[i] && low_x.is_none_or(|b| x_list[j] > b) { |
| 1143 | low = j; |
| 1144 | low_x = Some(x_list[j]); |
| 1145 | } |
| 1146 | if x_list[j] > x_list[i] && high_x.is_none_or(|b| x_list[j] < b) { |
| 1147 | high = j; |
| 1148 | high_x = Some(x_list[j]); |
| 1149 | } |
| 1150 | } |
| 1151 | (low, high) |
| 1152 | }) |
| 1153 | .collect(); |
| 1154 | let partitions = (values - 2) / FLOOR_CLASS_DIM; |
| 1155 | Floor1 { |
| 1156 | partition_classes: vec![0; partitions], |
| 1157 | class_dimensions: vec![FLOOR_CLASS_DIM], |
| 1158 | class_subclasses: vec![0], |
| 1159 | class_masterbooks: vec![0], |
| 1160 | subclass_books: vec![vec![0]], |
| 1161 | multiplier: 1, |
| 1162 | x_list, |
| 1163 | sorted, |
| 1164 | neighbours, |
| 1165 | } |
| 1166 | } |
| 1167 | |
| 1168 | |
| 1169 | fn build_block_config( |
| 1170 | half: usize, |
| 1171 | partition: usize, |
| 1172 | points: usize, |
| 1173 | range: f64, |
| 1174 | co_mask: f64, |
| 1175 | config: &EncoderConfig, |
| 1176 | ) -> BlockConfig { |
| 1177 | let floor = build_floor(half, points); |
| 1178 | let hz: Vec<f64> = floor |
| 1179 | .x_list |
| 1180 | .iter() |
| 1181 | .map(|&x| f64::from(config.sample_rate) * 0.5 * f64::from(x) / half as f64) |
| 1182 | .collect(); |
| 1183 | let ath = hz.iter().map(|&hz| absolute_threshold(hz)).collect(); |
| 1184 | let bark = hz.iter().map(|&hz| bark(hz)).collect(); |
| 1185 | BlockConfig { |
| 1186 | half, |
| 1187 | partition, |
| 1188 | floor, |
| 1189 | ath, |
| 1190 | bark, |
| 1191 | range, |
| 1192 | co_mask, |
| 1193 | } |
| 1194 | } |
| 1195 | |
| 1196 | |
| 1197 | |
| 1198 | fn design_floor_book() -> CodebookSpec { |
| 1199 | let weights: Vec<f64> = (0..256) |
| 1200 | .map(|v| (-(f64::from(v)) / 7.0).exp() + 0.002) |
| 1201 | .collect(); |
| 1202 | CodebookSpec::huffman(&weights, Vec::new()) |
| 1203 | } |
| 1204 | |
| 1205 | |
| 1206 | fn design_class_book() -> CodebookSpec { |
| 1207 | |
| 1208 | |
| 1209 | let per_class = [0.40f64, 0.18, 0.19, 0.16, 0.05, 0.011, 0.008, 0.007, 0.001]; |
| 1210 | let mut weights = Vec::with_capacity(CLASSES * CLASSES); |
| 1211 | for &first in &per_class { |
| 1212 | for &second in &per_class { |
| 1213 | weights.push(first * second); |
| 1214 | } |
| 1215 | } |
| 1216 | let mut spec = CodebookSpec::huffman(&weights, Vec::new()); |
| 1217 | spec.dimensions = 2; |
| 1218 | spec |
| 1219 | } |
| 1220 | |
| 1221 | |
| 1222 | |
| 1223 | |
| 1224 | fn design_residue_books() -> Vec<CodebookSpec> { |
| 1225 | CLASS_RANGE[1..] |
| 1226 | .iter() |
| 1227 | .enumerate() |
| 1228 | .map(|(offset, &range)| { |
| 1229 | let class = offset + 1; |
| 1230 | let dimensions = RESIDUE_BOOK_DIM[class]; |
| 1231 | let base = (2 * range + 1) as usize; |
| 1232 | let entries = base.pow(dimensions as u32); |
| 1233 | let sigma = f64::from(range).max(1.0); |
| 1234 | let mut weights = Vec::with_capacity(entries); |
| 1235 | let mut values = Vec::with_capacity(entries * dimensions); |
| 1236 | for entry in 0..entries { |
| 1237 | let mut nonzero = 0usize; |
| 1238 | let mut weight = 1.0f64; |
| 1239 | for position in 0..dimensions { |
| 1240 | let div = base.pow(position as u32); |
| 1241 | let value = (entry / div % base) as i32 - range; |
| 1242 | values.push(value as f32); |
| 1243 | if value == 0 { |
| 1244 | weight *= 0.60; |
| 1245 | } else { |
| 1246 | nonzero += 1; |
| 1247 | weight *= 0.40 * (-f64::from(value.abs()) / sigma).exp(); |
| 1248 | } |
| 1249 | } |
| 1250 | let sparse = match nonzero { |
| 1251 | 0 => 4.0, |
| 1252 | 1 => 2.0, |
| 1253 | 2 => 0.8, |
| 1254 | _ => 0.25, |
| 1255 | }; |
| 1256 | weights.push(weight * sparse + 1e-8); |
| 1257 | } |
| 1258 | let mut spec = CodebookSpec::huffman(&weights, values); |
| 1259 | spec.dimensions = dimensions; |
| 1260 | spec |
| 1261 | }) |
| 1262 | .collect() |
| 1263 | } |
| 1264 | |
| 1265 | |
| 1266 | |
| 1267 | |
| 1268 | |
| 1269 | |
| 1270 | |
| 1271 | |
| 1272 | fn absolute_threshold(hz: f64) -> f64 { |
| 1273 | let khz = (hz / 1000.0).clamp(0.02, 20.0); |
| 1274 | let spl = |
| 1275 | 3.64 * khz.powf(-0.8) - 6.5 * (-0.6 * (khz - 3.3).powi(2)).exp() + 0.001 * khz.powi(4); |
| 1276 | (spl - 96.0).clamp(-120.0, -80.0) |
| 1277 | } |
| 1278 | |
| 1279 | |
| 1280 | |
| 1281 | fn bark(hz: f64) -> f64 { |
| 1282 | 13.0 * (0.00076 * hz).atan() + 3.5 * ((hz / 7500.0) * (hz / 7500.0)).atan() |
| 1283 | } |
| 1284 | |
| 1285 | struct HeaderSetup<'a> { |
| 1286 | long: &'a BlockConfig, |
| 1287 | short: &'a BlockConfig, |
| 1288 | floor_book: &'a CodebookSpec, |
| 1289 | class_book: &'a CodebookSpec, |
| 1290 | residue_books: &'a [CodebookSpec], |
| 1291 | coupling: &'a [(usize, usize)], |
| 1292 | } |
| 1293 | |
| 1294 | |
| 1295 | fn write_headers(config: &EncoderConfig, channels: usize, setup: HeaderSetup<'_>) -> Vec<Vec<u8>> { |
| 1296 | let HeaderSetup { |
| 1297 | long, |
| 1298 | short, |
| 1299 | floor_book, |
| 1300 | class_book, |
| 1301 | residue_books, |
| 1302 | coupling, |
| 1303 | } = setup; |
| 1304 | let mut ident = vec![1u8]; |
| 1305 | ident.extend_from_slice(b"vorbis"); |
| 1306 | ident.extend_from_slice(&0u32.to_le_bytes()); |
| 1307 | ident.push(channels as u8); |
| 1308 | ident.extend_from_slice(&config.sample_rate.to_le_bytes()); |
| 1309 | ident.extend_from_slice(&0i32.to_le_bytes()); |
| 1310 | ident.extend_from_slice(&config.bitrate_bps.max(0).to_le_bytes()); |
| 1311 | ident.extend_from_slice(&0i32.to_le_bytes()); |
| 1312 | let log2 = |n: usize| n.trailing_zeros() as u8; |
| 1313 | ident.push(log2(BLOCK_SHORT) | (log2(BLOCK_LONG) << 4)); |
| 1314 | ident.push(1); |
| 1315 | |
| 1316 | let mut comment = vec![3u8]; |
| 1317 | comment.extend_from_slice(b"vorbis"); |
| 1318 | let vendor = b"ec-vorbis"; |
| 1319 | comment.extend_from_slice(&(vendor.len() as u32).to_le_bytes()); |
| 1320 | comment.extend_from_slice(vendor); |
| 1321 | comment.extend_from_slice(&0u32.to_le_bytes()); |
| 1322 | comment.push(1); |
| 1323 | |
| 1324 | let mut out = BitsOut::new(); |
| 1325 | for byte in [5u8].iter().chain(b"vorbis") { |
| 1326 | out.write(u32::from(*byte), 8); |
| 1327 | } |
| 1328 | let books: Vec<&CodebookSpec> = std::iter::once(floor_book) |
| 1329 | .chain(std::iter::once(class_book)) |
| 1330 | .chain(residue_books.iter()) |
| 1331 | .collect(); |
| 1332 | out.write(books.len() as u32 - 1, 8); |
| 1333 | for book in &books { |
| 1334 | write_codebook(&mut out, book); |
| 1335 | } |
| 1336 | |
| 1337 | out.write(0, 6); |
| 1338 | out.write(0, 16); |
| 1339 | |
| 1340 | out.write(1, 6); |
| 1341 | for bc in [long, short] { |
| 1342 | out.write(1, 16); |
| 1343 | out.write(bc.floor.partition_classes.len() as u32, 5); |
| 1344 | for _ in &bc.floor.partition_classes { |
| 1345 | out.write(0, 4); |
| 1346 | } |
| 1347 | out.write(FLOOR_CLASS_DIM as u32 - 1, 3); |
| 1348 | out.write(0, 2); |
| 1349 | out.write(1, 8); |
| 1350 | out.write(0, 2); |
| 1351 | let range_bits = ilog(bc.half as u32) - 1; |
| 1352 | out.write(range_bits, 4); |
| 1353 | for &x in bc.floor.x_list.iter().skip(2) { |
| 1354 | out.write(x, range_bits); |
| 1355 | } |
| 1356 | } |
| 1357 | |
| 1358 | |
| 1359 | out.write(1, 6); |
| 1360 | for bc in [long, short] { |
| 1361 | out.write(2, 16); |
| 1362 | out.write(0, 24); |
| 1363 | out.write((bc.half * channels) as u32, 24); |
| 1364 | out.write(bc.partition as u32 - 1, 24); |
| 1365 | out.write(CLASSES as u32 - 1, 6); |
| 1366 | out.write(1, 8); |
| 1367 | for class in 0..CLASSES { |
| 1368 | out.write(u32::from(class > 0), 3); |
| 1369 | out.write(0, 1); |
| 1370 | } |
| 1371 | for class in 1..CLASSES { |
| 1372 | out.write(class as u32 + 1, 8); |
| 1373 | } |
| 1374 | } |
| 1375 | |
| 1376 | |
| 1377 | out.write(1, 6); |
| 1378 | for (floor, residue) in [(0u32, 0u32), (1, 1)] { |
| 1379 | out.write(0, 16); |
| 1380 | out.write(0, 1); |
| 1381 | match coupling.is_empty() { |
| 1382 | true => out.write(0, 1), |
| 1383 | false => { |
| 1384 | out.write(1, 1); |
| 1385 | out.write(coupling.len() as u32 - 1, 8); |
| 1386 | let field = ilog(channels as u32 - 1); |
| 1387 | for &(magnitude, angle) in coupling { |
| 1388 | out.write(magnitude as u32, field); |
| 1389 | out.write(angle as u32, field); |
| 1390 | } |
| 1391 | } |
| 1392 | } |
| 1393 | out.write(0, 2); |
| 1394 | out.write(0, 8); |
| 1395 | out.write(floor, 8); |
| 1396 | out.write(residue, 8); |
| 1397 | } |
| 1398 | |
| 1399 | |
| 1400 | out.write(1, 6); |
| 1401 | out.bit(false); |
| 1402 | out.write(0, 16); |
| 1403 | out.write(0, 16); |
| 1404 | out.write(1, 8); |
| 1405 | out.bit(true); |
| 1406 | out.write(0, 16); |
| 1407 | out.write(0, 16); |
| 1408 | out.write(0, 8); |
| 1409 | out.write(1, 1); |
| 1410 | let setup = out.finish(); |
| 1411 | |
| 1412 | vec![ident, comment, setup] |
| 1413 | } |
| 1414 | |
| 1415 | |
| 1416 | |
| 1417 | fn write_codebook(out: &mut BitsOut, book: &CodebookSpec) { |
| 1418 | out.write(0x0056_4342, 24); |
| 1419 | out.write(book.dimensions as u32, 16); |
| 1420 | out.write(book.entries() as u32, 24); |
| 1421 | out.write(0, 1); |
| 1422 | out.write(0, 1); |
| 1423 | for &length in &book.lengths { |
| 1424 | out.write(u32::from(length) - 1, 5); |
| 1425 | } |
| 1426 | if book.values.is_empty() { |
| 1427 | out.write(0, 4); |
| 1428 | return; |
| 1429 | } |
| 1430 | out.write(1, 4); |
| 1431 | let minimum = book.values.iter().copied().fold(f32::INFINITY, f32::min); |
| 1432 | let maximum = book |
| 1433 | .values |
| 1434 | .iter() |
| 1435 | .copied() |
| 1436 | .fold(f32::NEG_INFINITY, f32::max); |
| 1437 | out.write(float32_pack(minimum), 32); |
| 1438 | out.write(float32_pack(1.0), 32); |
| 1439 | let lookup_values = lookup1_values(book.entries(), book.dimensions); |
| 1440 | let value_bits = ilog((maximum - minimum).round() as u32).max(1); |
| 1441 | out.write(value_bits - 1, 4); |
| 1442 | out.write(0, 1); |
| 1443 | for value in 0..lookup_values { |
| 1444 | out.write(value as u32, value_bits); |
| 1445 | } |
| 1446 | } |
| 1447 | |
| 1448 | |
| 1449 | fn lace(headers: &[Vec<u8>]) -> Vec<u8> { |
| 1450 | let mut out = vec![2u8]; |
| 1451 | for header in headers.iter().take(headers.len() - 1) { |
| 1452 | let mut length = header.len(); |
| 1453 | while length >= 255 { |
| 1454 | out.push(255); |
| 1455 | length -= 255; |
| 1456 | } |
| 1457 | out.push(length as u8); |
| 1458 | } |
| 1459 | for header in headers { |
| 1460 | out.extend_from_slice(header); |
| 1461 | } |
| 1462 | out |
| 1463 | } |
| 1464 | |
| 1465 | impl Encoder for VorbisEncoder { |
| 1466 | fn codec_parameters(&self) -> &CodecParameters { |
| 1467 | &self.params |
| 1468 | } |
| 1469 | |
| 1470 | fn send_frame(&mut self, frame: &Frame) -> Result<()> { |
| 1471 | let Frame::Audio(audio) = frame else { |
| 1472 | return Err(Error::corrupt("video frame pushed into an audio encoder")); |
| 1473 | }; |
| 1474 | if audio.format != SampleFormat::F32 { |
| 1475 | return Err(Error::unsupported( |
| 1476 | format!("{:?} input", audio.format), |
| 1477 | "this encoder takes 32-bit float samples", |
| 1478 | )); |
| 1479 | } |
| 1480 | let channels = usize::from(self.config.channels); |
| 1481 | let mut planes: Vec<Vec<f32>> = vec![Vec::with_capacity(audio.samples); channels]; |
| 1482 | match audio.planar { |
| 1483 | true => { |
| 1484 | for (channel, plane) in audio.data.iter().enumerate().take(channels) { |
| 1485 | planes[channel] = floats(plane, audio.samples); |
| 1486 | } |
| 1487 | } |
| 1488 | false => { |
| 1489 | let interleaved = floats(&audio.data[0], audio.samples * channels); |
| 1490 | for (i, value) in interleaved.into_iter().enumerate() { |
| 1491 | planes[i % channels].push(value); |
| 1492 | } |
| 1493 | } |
| 1494 | } |
| 1495 | let borrowed: Vec<&[f32]> = planes.iter().map(|p| &p[..]).collect(); |
| 1496 | self.push_planar(&borrowed) |
| 1497 | } |
| 1498 | |
| 1499 | fn receive_packet(&mut self) -> Result<Packet> { |
| 1500 | let encoded = self.next_packet()?; |
| 1501 | let base = TimeBase::new(1, i64::from(self.config.sample_rate)); |
| 1502 | let mut packet = Packet::new(0, base, encoded.data); |
| 1503 | packet.pts = Some(encoded.granule - encoded.samples); |
| 1504 | packet.duration = Some(encoded.samples); |
| 1505 | Ok(packet) |
| 1506 | } |
| 1507 | |
| 1508 | fn flush(&mut self) -> Result<()> { |
| 1509 | self.finish(); |
| 1510 | Ok(()) |
| 1511 | } |
| 1512 | } |
| 1513 | |
| 1514 | |
| 1515 | fn floats(plane: &Buf, count: usize) -> Vec<f32> { |
| 1516 | plane |
| 1517 | .chunks_exact(4) |
| 1518 | .take(count) |
| 1519 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 1520 | .collect() |
| 1521 | } |
| 1522 | |
| 1523 | #[cfg(test)] |
| 1524 | mod tests { |
| 1525 | use super::*; |
| 1526 | |
| 1527 | #[test] |
| 1528 | fn folding_is_the_exact_inverse_of_the_decoder() { |
| 1529 | |
| 1530 | |
| 1531 | for predicted in [0i32, 1, 40, 128, 200, 255] { |
| 1532 | for wanted in 0..256i32 { |
| 1533 | let value = fold(predicted, wanted, 256); |
| 1534 | assert!((0..256).contains(&value), "{predicted}->{wanted}: {value}"); |
| 1535 | assert_eq!( |
| 1536 | unfold(predicted, value, 256), |
| 1537 | wanted, |
| 1538 | "predicted {predicted}, wanted {wanted}, coded {value}" |
| 1539 | ); |
| 1540 | } |
| 1541 | } |
| 1542 | } |
| 1543 | |
| 1544 | |
| 1545 | fn unfold(predicted: i32, value: i32, range: i32) -> i32 { |
| 1546 | let high_room = range - predicted; |
| 1547 | let low_room = predicted; |
| 1548 | let room = high_room.min(low_room) * 2; |
| 1549 | if value == 0 { |
| 1550 | return predicted; |
| 1551 | } |
| 1552 | match value >= room { |
| 1553 | true => match high_room > low_room { |
| 1554 | true => value - low_room + predicted, |
| 1555 | false => predicted - value + high_room - 1, |
| 1556 | }, |
| 1557 | false => match value & 1 == 1 { |
| 1558 | true => predicted - (value + 1) / 2, |
| 1559 | false => predicted + value / 2, |
| 1560 | }, |
| 1561 | } |
| 1562 | } |
| 1563 | |
| 1564 | #[test] |
| 1565 | fn vector_residue_books_address_exact_values() { |
| 1566 | let books = design_residue_books(); |
| 1567 | assert_eq!( |
| 1568 | books.iter().map(|b| b.dimensions).collect::<Vec<_>>(), |
| 1569 | vec![4, 2, 2, 1, 1, 1, 1, 1] |
| 1570 | ); |
| 1571 | for (class, book) in books.iter().enumerate().take(3) { |
| 1572 | let range = CLASS_RANGE[class + 1]; |
| 1573 | let vector: Vec<i32> = (0..book.dimensions) |
| 1574 | .map(|i| if i % 2 == 0 { range } else { -range }) |
| 1575 | .collect(); |
| 1576 | let entry = residue_entry(&vector, range, book.dimensions); |
| 1577 | let start = entry * book.dimensions; |
| 1578 | let decoded: Vec<i32> = book.values[start..start + book.dimensions] |
| 1579 | .iter() |
| 1580 | .map(|&v| v as i32) |
| 1581 | .collect(); |
| 1582 | assert_eq!(decoded, vector); |
| 1583 | } |
| 1584 | } |
| 1585 | |
| 1586 | #[test] |
| 1587 | fn tail_granule_44100_mono() { |
| 1588 | let mut enc = VorbisEncoder::new(EncoderConfig { |
| 1589 | sample_rate: 44_100, |
| 1590 | channels: 2, |
| 1591 | bitrate_bps: -1, |
| 1592 | quality: 0.85, |
| 1593 | }) |
| 1594 | .unwrap(); |
| 1595 | let pcm = vec![0.1f32; 44_100 * 2]; |
| 1596 | enc.push_interleaved(&pcm).unwrap(); |
| 1597 | enc.finish(); |
| 1598 | let mut last = 0i64; |
| 1599 | let mut n = 0; |
| 1600 | loop { |
| 1601 | match enc.next_packet() { |
| 1602 | Ok(p) => { |
| 1603 | last = p.granule; |
| 1604 | n += 1; |
| 1605 | } |
| 1606 | Err(Error::Eof) => break, |
| 1607 | Err(e) => panic!("{e}"), |
| 1608 | } |
| 1609 | } |
| 1610 | assert_eq!(n, 45, "packet count"); |
| 1611 | assert_eq!(last, 44_100, "last granule"); |
| 1612 | } |
| 1613 | |
| 1614 | #[test] |
| 1615 | fn coupling_round_trips_every_sign_case() { |
| 1616 | for left in -8..=8i32 { |
| 1617 | for right in -8..=8i32 { |
| 1618 | let (m, a) = couple(left, right); |
| 1619 | let (back_l, back_r) = match (m > 0, a > 0) { |
| 1620 | (true, true) => (m, m - a), |
| 1621 | (true, false) => (m + a, m), |
| 1622 | (false, true) => (m, m + a), |
| 1623 | (false, false) => (m - a, m), |
| 1624 | }; |
| 1625 | assert_eq!((back_l, back_r), (left, right), "{left},{right}"); |
| 1626 | } |
| 1627 | } |
| 1628 | } |
| 1629 | |
| 1630 | |
| 1631 | |
| 1632 | #[test] |
| 1633 | fn a_stationary_signal_uses_only_long_blocks() { |
| 1634 | let mut enc = VorbisEncoder::new(EncoderConfig { |
| 1635 | sample_rate: 48_000, |
| 1636 | channels: 2, |
| 1637 | bitrate_bps: -1, |
| 1638 | quality: 0.6, |
| 1639 | }) |
| 1640 | .unwrap(); |
| 1641 | let samples = 48_000usize; |
| 1642 | let mut pcm = vec![0.0f32; samples * 2]; |
| 1643 | for i in 0..samples { |
| 1644 | let t = i as f32 / 48_000.0; |
| 1645 | let v = (2.0 * std::f32::consts::PI * 1_000.0 * t).sin() * 0.5; |
| 1646 | pcm[2 * i] = v; |
| 1647 | pcm[2 * i + 1] = v; |
| 1648 | } |
| 1649 | enc.push_interleaved(&pcm).unwrap(); |
| 1650 | enc.finish(); |
| 1651 | let mut modes = std::collections::HashSet::new(); |
| 1652 | loop { |
| 1653 | match enc.next_packet() { |
| 1654 | Ok(p) => { |
| 1655 | let mut bits = crate::bits::Bits::new(&p.data); |
| 1656 | assert!(!bits.bit()); |
| 1657 | modes.insert(bits.read(1)); |
| 1658 | } |
| 1659 | Err(Error::Eof) => break, |
| 1660 | Err(e) => panic!("{e}"), |
| 1661 | } |
| 1662 | } |
| 1663 | assert_eq!(modes, std::collections::HashSet::from([MODE_LONG])); |
| 1664 | } |
| 1665 | |
| 1666 | |
| 1667 | |
| 1668 | #[test] |
| 1669 | fn an_onset_after_silence_uses_short_blocks() { |
| 1670 | let mut enc = VorbisEncoder::new(EncoderConfig { |
| 1671 | sample_rate: 44_100, |
| 1672 | channels: 2, |
| 1673 | bitrate_bps: -1, |
| 1674 | quality: 0.6, |
| 1675 | }) |
| 1676 | .unwrap(); |
| 1677 | let silence = 44_100usize; |
| 1678 | let tone = 4_410usize; |
| 1679 | let mut pcm = vec![0.0f32; (silence + tone) * 2]; |
| 1680 | for i in 0..tone { |
| 1681 | let t = i as f32 / 44_100.0; |
| 1682 | let v = (2.0 * std::f32::consts::PI * 1_000.0 * t).sin(); |
| 1683 | pcm[2 * (silence + i)] = v; |
| 1684 | pcm[2 * (silence + i) + 1] = v; |
| 1685 | } |
| 1686 | enc.push_interleaved(&pcm).unwrap(); |
| 1687 | enc.finish(); |
| 1688 | let mut saw_short = false; |
| 1689 | loop { |
| 1690 | match enc.next_packet() { |
| 1691 | Ok(p) => { |
| 1692 | let mut bits = crate::bits::Bits::new(&p.data); |
| 1693 | assert!(!bits.bit()); |
| 1694 | if bits.read(1) == MODE_SHORT { |
| 1695 | saw_short = true; |
| 1696 | } |
| 1697 | } |
| 1698 | Err(Error::Eof) => break, |
| 1699 | Err(e) => panic!("{e}"), |
| 1700 | } |
| 1701 | } |
| 1702 | assert!(saw_short, "no short block coded around the onset"); |
| 1703 | } |
| 1704 | } |