| 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 | use std::collections::VecDeque; |
| 26 | |
| 27 | use ec_core::{ |
| 28 | AudioParameters, Buf, CodecId, CodecParameters, Encoder, Error, Frame, MediaParameters, Packet, |
| 29 | Result, SampleFormat, TimeBase, |
| 30 | }; |
| 31 | use ec_dsp::Mdct; |
| 32 | |
| 33 | use crate::bits::{BitsOut, float32_pack}; |
| 34 | use crate::codebook::{CodebookSpec, ilog}; |
| 35 | use crate::decode::channel_map; |
| 36 | use crate::floor::render_floor1; |
| 37 | use crate::setup::Floor1; |
| 38 | use crate::window; |
| 39 | |
| 40 | |
| 41 | const BLOCK: usize = 2048; |
| 42 | |
| 43 | const HOP: usize = BLOCK / 2; |
| 44 | |
| 45 | const HALF: usize = BLOCK / 2; |
| 46 | |
| 47 | const PARTITION: usize = 32; |
| 48 | |
| 49 | const FLOOR_POINTS: usize = 20; |
| 50 | |
| 51 | const FLOOR_CLASS_DIM: usize = 4; |
| 52 | |
| 53 | const CLASSES: usize = 5; |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | const VORBIS_MDCT_SCALE: f32 = 2.0 / HALF as f32; |
| 59 | |
| 60 | const CLASS_RANGE: [i32; CLASSES] = [0, 1, 4, 16, 127]; |
| 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_bps: i32, |
| 71 | |
| 72 | |
| 73 | pub quality: f32, |
| 74 | } |
| 75 | |
| 76 | impl Default for EncoderConfig { |
| 77 | fn default() -> EncoderConfig { |
| 78 | EncoderConfig { |
| 79 | sample_rate: 48_000, |
| 80 | channels: 2, |
| 81 | bitrate_bps: 128_000, |
| 82 | quality: 0.5, |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | |
| 88 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 89 | pub struct EncodedPacket { |
| 90 | |
| 91 | pub data: Vec<u8>, |
| 92 | |
| 93 | pub granule: i64, |
| 94 | |
| 95 | pub samples: i64, |
| 96 | } |
| 97 | |
| 98 | |
| 99 | pub struct VorbisEncoder { |
| 100 | config: EncoderConfig, |
| 101 | params: CodecParameters, |
| 102 | |
| 103 | to_vorbis: Vec<usize>, |
| 104 | headers: Vec<Vec<u8>>, |
| 105 | floor: Floor1, |
| 106 | floor_book: CodebookSpec, |
| 107 | class_book: CodebookSpec, |
| 108 | residue_books: Vec<CodebookSpec>, |
| 109 | |
| 110 | ath: Vec<f64>, |
| 111 | |
| 112 | coupling: Vec<(usize, usize)>, |
| 113 | mdct: Mdct<f32>, |
| 114 | window: Vec<f32>, |
| 115 | |
| 116 | |
| 117 | buffer: Vec<Vec<f32>>, |
| 118 | |
| 119 | fed: i64, |
| 120 | |
| 121 | blocks: i64, |
| 122 | |
| 123 | granule: i64, |
| 124 | |
| 125 | headroom: f64, |
| 126 | finished: bool, |
| 127 | packets: VecDeque<EncodedPacket>, |
| 128 | } |
| 129 | |
| 130 | impl VorbisEncoder { |
| 131 | |
| 132 | pub fn new(config: EncoderConfig) -> Result<VorbisEncoder> { |
| 133 | let channels = usize::from(config.channels); |
| 134 | if channels == 0 || channels > 255 { |
| 135 | return Err(Error::unsupported( |
| 136 | format!("{channels} channels"), |
| 137 | "Vorbis states a channel count in one byte", |
| 138 | )); |
| 139 | } |
| 140 | if config.sample_rate == 0 { |
| 141 | return Err(Error::corrupt("encoder sample rate of zero")); |
| 142 | } |
| 143 | let (layout, to_ec) = channel_map(channels); |
| 144 | let mut to_vorbis = vec![0usize; channels]; |
| 145 | for (vorbis, &ec) in to_ec.iter().enumerate() { |
| 146 | to_vorbis[ec] = vorbis; |
| 147 | } |
| 148 | |
| 149 | |
| 150 | let coupling = match channels { |
| 151 | 2 => vec![(0usize, 1usize)], |
| 152 | _ => Vec::new(), |
| 153 | }; |
| 154 | |
| 155 | let floor = build_floor(); |
| 156 | let floor_book = design_floor_book(); |
| 157 | let class_book = design_class_book(); |
| 158 | let residue_books = design_residue_books(); |
| 159 | let ath = floor |
| 160 | .x_list |
| 161 | .iter() |
| 162 | .map(|&x| { |
| 163 | let hz = f64::from(config.sample_rate) * 0.5 * f64::from(x) / HALF as f64; |
| 164 | absolute_threshold(hz) |
| 165 | }) |
| 166 | .collect(); |
| 167 | |
| 168 | let headers = write_headers( |
| 169 | &config, |
| 170 | channels, |
| 171 | &floor, |
| 172 | &floor_book, |
| 173 | &class_book, |
| 174 | &residue_books, |
| 175 | &coupling, |
| 176 | ); |
| 177 | let params = CodecParameters { |
| 178 | codec: CodecId::Vorbis, |
| 179 | media: MediaParameters::Audio(AudioParameters { |
| 180 | sample_rate: config.sample_rate, |
| 181 | layout, |
| 182 | format: Some(SampleFormat::F32), |
| 183 | bits_per_sample: None, |
| 184 | }), |
| 185 | extradata: Some(Buf::from_vec(lace(&headers))), |
| 186 | }; |
| 187 | |
| 188 | let quality = f64::from(config.quality.clamp(0.0, 1.0)); |
| 189 | Ok(VorbisEncoder { |
| 190 | mdct: Mdct::new(BLOCK), |
| 191 | window: window::build(BLOCK, BLOCK, true, true), |
| 192 | |
| 193 | |
| 194 | buffer: vec![vec![0.0; HOP]; channels], |
| 195 | fed: 0, |
| 196 | blocks: 0, |
| 197 | granule: 0, |
| 198 | headroom: 4.0 + 26.0 * quality, |
| 199 | finished: false, |
| 200 | packets: VecDeque::new(), |
| 201 | config, |
| 202 | params, |
| 203 | to_vorbis, |
| 204 | headers, |
| 205 | floor, |
| 206 | floor_book, |
| 207 | class_book, |
| 208 | residue_books, |
| 209 | ath, |
| 210 | coupling, |
| 211 | }) |
| 212 | } |
| 213 | |
| 214 | |
| 215 | pub fn headers(&self) -> Vec<&[u8]> { |
| 216 | self.headers.iter().map(|h| &h[..]).collect() |
| 217 | } |
| 218 | |
| 219 | |
| 220 | pub fn extradata(&self) -> Vec<u8> { |
| 221 | lace(&self.headers) |
| 222 | } |
| 223 | |
| 224 | |
| 225 | pub fn parameters(&self) -> &CodecParameters { |
| 226 | &self.params |
| 227 | } |
| 228 | |
| 229 | |
| 230 | pub fn push_planar(&mut self, channels: &[&[f32]]) -> Result<()> { |
| 231 | if channels.len() != usize::from(self.config.channels) { |
| 232 | return Err(Error::corrupt(format!( |
| 233 | "{} channels pushed into a {}-channel encoder", |
| 234 | channels.len(), |
| 235 | self.config.channels |
| 236 | ))); |
| 237 | } |
| 238 | if self.finished { |
| 239 | return Err(Error::corrupt("samples pushed after finish")); |
| 240 | } |
| 241 | let samples = channels.first().map_or(0, |c| c.len()); |
| 242 | for (ec, data) in channels.iter().enumerate() { |
| 243 | if data.len() != samples { |
| 244 | return Err(Error::corrupt("channels of different lengths")); |
| 245 | } |
| 246 | self.buffer[self.to_vorbis[ec]].extend_from_slice(data); |
| 247 | } |
| 248 | self.fed += samples as i64; |
| 249 | self.encode_ready(); |
| 250 | Ok(()) |
| 251 | } |
| 252 | |
| 253 | |
| 254 | pub fn push_interleaved(&mut self, samples: &[f32]) -> Result<()> { |
| 255 | let channels = usize::from(self.config.channels); |
| 256 | if !samples.len().is_multiple_of(channels) { |
| 257 | return Err(Error::corrupt("interleaved push is not a whole frame")); |
| 258 | } |
| 259 | if self.finished { |
| 260 | return Err(Error::corrupt("samples pushed after finish")); |
| 261 | } |
| 262 | for (i, &value) in samples.iter().enumerate() { |
| 263 | self.buffer[self.to_vorbis[i % channels]].push(value); |
| 264 | } |
| 265 | self.fed += (samples.len() / channels) as i64; |
| 266 | self.encode_ready(); |
| 267 | Ok(()) |
| 268 | } |
| 269 | |
| 270 | |
| 271 | pub fn finish(&mut self) { |
| 272 | if self.finished { |
| 273 | return; |
| 274 | } |
| 275 | self.finished = true; |
| 276 | |
| 277 | |
| 278 | let last = ((self.fed + HOP as i64 - 1) / HOP as i64).max(1) as usize; |
| 279 | let needed = last * HOP + BLOCK; |
| 280 | for channel in &mut self.buffer { |
| 281 | if channel.len() < needed { |
| 282 | channel.resize(needed, 0.0); |
| 283 | } |
| 284 | } |
| 285 | self.encode_ready(); |
| 286 | } |
| 287 | |
| 288 | |
| 289 | pub fn next_packet(&mut self) -> Result<EncodedPacket> { |
| 290 | match self.packets.pop_front() { |
| 291 | Some(packet) => Ok(packet), |
| 292 | None if self.finished => Err(Error::Eof), |
| 293 | None => Err(Error::NeedMore), |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | fn encode_ready(&mut self) { |
| 304 | let channels = usize::from(self.config.channels); |
| 305 | loop { |
| 306 | if self.finished && self.blocks > 0 && self.granule >= self.fed { |
| 307 | break; |
| 308 | } |
| 309 | let start = self.blocks as usize * HOP; |
| 310 | if self.buffer[0].len() < start + BLOCK { |
| 311 | break; |
| 312 | } |
| 313 | let centre = self.blocks * HOP as i64; |
| 314 | let granule = match self.finished { |
| 315 | true => centre.min(self.fed), |
| 316 | false => centre, |
| 317 | }; |
| 318 | let data = self.encode_block(start, channels); |
| 319 | self.packets.push_back(EncodedPacket { |
| 320 | data, |
| 321 | granule, |
| 322 | samples: (granule - self.granule).max(0), |
| 323 | }); |
| 324 | self.granule = granule; |
| 325 | self.blocks += 1; |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | |
| 330 | fn encode_block(&mut self, start: usize, channels: usize) -> Vec<u8> { |
| 331 | let mut spectra: Vec<Vec<f32>> = Vec::with_capacity(channels); |
| 332 | let mut block = vec![0.0f32; BLOCK]; |
| 333 | for channel in 0..channels { |
| 334 | block.copy_from_slice(&self.buffer[channel][start..start + BLOCK]); |
| 335 | let mut coefficients = vec![0.0f32; HALF]; |
| 336 | self.mdct |
| 337 | .forward_windowed(&block, &self.window, &mut coefficients); |
| 338 | for value in coefficients.iter_mut() { |
| 339 | *value *= VORBIS_MDCT_SCALE; |
| 340 | } |
| 341 | spectra.push(coefficients); |
| 342 | } |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | let mut curves: Vec<Vec<f32>> = vec![Vec::new(); channels]; |
| 348 | let mut floor_values: Vec<Vec<i32>> = vec![Vec::new(); channels]; |
| 349 | let mut coded = vec![false; channels]; |
| 350 | for &(magnitude, angle) in &self.coupling { |
| 351 | let peaks = self.peaks_of(&[&spectra[magnitude], &spectra[angle]]); |
| 352 | let (y, step2) = self.fit_floor(&peaks); |
| 353 | let mut curve = vec![0.0f32; HALF]; |
| 354 | render_floor1(&self.floor, &y, &step2, &mut curve); |
| 355 | curves[magnitude] = curve.clone(); |
| 356 | curves[angle] = curve; |
| 357 | floor_values[magnitude] = y.clone(); |
| 358 | floor_values[angle] = y; |
| 359 | coded[magnitude] = true; |
| 360 | coded[angle] = true; |
| 361 | } |
| 362 | for channel in 0..channels { |
| 363 | if coded[channel] { |
| 364 | continue; |
| 365 | } |
| 366 | let peaks = self.peaks_of(&[&spectra[channel]]); |
| 367 | let (y, step2) = self.fit_floor(&peaks); |
| 368 | let mut curve = vec![0.0f32; HALF]; |
| 369 | render_floor1(&self.floor, &y, &step2, &mut curve); |
| 370 | curves[channel] = curve; |
| 371 | floor_values[channel] = y; |
| 372 | } |
| 373 | |
| 374 | |
| 375 | let mut quantised: Vec<Vec<i32>> = (0..channels) |
| 376 | .map(|channel| { |
| 377 | spectra[channel] |
| 378 | .iter() |
| 379 | .zip(curves[channel].iter()) |
| 380 | .map(|(&value, &floor)| match floor > 0.0 { |
| 381 | true => value / floor, |
| 382 | false => 0.0, |
| 383 | }) |
| 384 | .map(|normalised| normalised.round() as i32) |
| 385 | .collect::<Vec<i32>>() |
| 386 | }) |
| 387 | .collect(); |
| 388 | for &(magnitude, angle) in &self.coupling { |
| 389 | |
| 390 | |
| 391 | let mut left = std::mem::take(&mut quantised[magnitude]); |
| 392 | let mut right = std::mem::take(&mut quantised[angle]); |
| 393 | for (l, r) in left.iter_mut().zip(right.iter_mut()) { |
| 394 | let (m, a) = couple(*l, *r); |
| 395 | *l = m; |
| 396 | *r = a; |
| 397 | } |
| 398 | quantised[magnitude] = left; |
| 399 | quantised[angle] = right; |
| 400 | } |
| 401 | let limit = CLASS_RANGE[CLASSES - 1]; |
| 402 | for channel in quantised.iter_mut() { |
| 403 | for value in channel.iter_mut() { |
| 404 | *value = (*value).clamp(-limit, limit); |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | let mut out = BitsOut::new(); |
| 409 | out.write(0, 1); |
| 410 | |
| 411 | |
| 412 | out.bit(true); |
| 413 | out.bit(true); |
| 414 | for values in floor_values.iter().take(channels) { |
| 415 | self.write_floor(&mut out, values); |
| 416 | } |
| 417 | self.write_residue(&mut out, &quantised); |
| 418 | let bits = out.len(); |
| 419 | self.update_rate(bits, channels); |
| 420 | out.finish() |
| 421 | } |
| 422 | |
| 423 | |
| 424 | |
| 425 | |
| 426 | |
| 427 | |
| 428 | fn peaks_of(&self, spectra: &[&Vec<f32>]) -> Vec<f64> { |
| 429 | let x = &self.floor.x_list; |
| 430 | x.iter() |
| 431 | .map(|¢re| { |
| 432 | let below = x.iter().filter(|&&o| o < centre).max().copied(); |
| 433 | let above = x.iter().filter(|&&o| o > centre).min().copied(); |
| 434 | let lo = below.map_or(0, |b| ((b + centre) / 2) as usize); |
| 435 | let hi = above.map_or(HALF, |a| ((a + centre) / 2) as usize + 1); |
| 436 | let lo = lo.min(HALF - 1); |
| 437 | let hi = hi.clamp(lo + 1, HALF); |
| 438 | let mut peak = 0.0f64; |
| 439 | for spectrum in spectra { |
| 440 | for &value in &spectrum[lo..hi] { |
| 441 | peak = peak.max(f64::from(value.abs())); |
| 442 | } |
| 443 | } |
| 444 | peak |
| 445 | }) |
| 446 | .collect() |
| 447 | } |
| 448 | |
| 449 | |
| 450 | |
| 451 | |
| 452 | |
| 453 | |
| 454 | |
| 455 | fn fit_floor(&self, peaks: &[f64]) -> (Vec<i32>, Vec<bool>) { |
| 456 | let mut db: Vec<f64> = peaks |
| 457 | .iter() |
| 458 | .map(|&peak| 20.0 * (peak.max(1e-9)).log10()) |
| 459 | .collect(); |
| 460 | |
| 461 | let order = &self.floor.sorted; |
| 462 | for window in order.windows(2) { |
| 463 | let (previous, current) = (window[0], window[1]); |
| 464 | db[current] = db[current].max(db[previous] - 12.0); |
| 465 | } |
| 466 | for window in order.windows(2).rev() { |
| 467 | let (current, next) = (window[0], window[1]); |
| 468 | db[current] = db[current].max(db[next] - 24.0); |
| 469 | } |
| 470 | let target: Vec<f64> = db |
| 471 | .iter() |
| 472 | .zip(self.ath.iter()) |
| 473 | .map(|(&level, &threshold)| (level - self.headroom).max(threshold)) |
| 474 | .collect(); |
| 475 | let y: Vec<i32> = target |
| 476 | .iter() |
| 477 | .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255)) |
| 478 | .collect(); |
| 479 | self.fold_floor(&y) |
| 480 | } |
| 481 | |
| 482 | |
| 483 | |
| 484 | fn fold_floor(&self, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) { |
| 485 | let values = wanted.len(); |
| 486 | let range = 256i32; |
| 487 | let mut final_y = vec![0i32; values]; |
| 488 | let mut step2 = vec![false; values]; |
| 489 | final_y[0] = wanted[0]; |
| 490 | final_y[1] = wanted[1]; |
| 491 | step2[0] = true; |
| 492 | step2[1] = true; |
| 493 | for i in 2..values { |
| 494 | let (low, high) = self.floor.neighbours[i]; |
| 495 | let predicted = predict( |
| 496 | self.floor.x_list[low], |
| 497 | final_y[low], |
| 498 | self.floor.x_list[high], |
| 499 | final_y[high], |
| 500 | self.floor.x_list[i], |
| 501 | ); |
| 502 | let value = fold(predicted, wanted[i], range); |
| 503 | if value != 0 { |
| 504 | step2[low] = true; |
| 505 | step2[high] = true; |
| 506 | step2[i] = true; |
| 507 | } |
| 508 | final_y[i] = wanted[i]; |
| 509 | } |
| 510 | (final_y, step2) |
| 511 | } |
| 512 | |
| 513 | |
| 514 | |
| 515 | fn write_floor(&self, out: &mut BitsOut, y: &[i32]) { |
| 516 | out.bit(true); |
| 517 | out.write(y[0] as u32, 8); |
| 518 | out.write(y[1] as u32, 8); |
| 519 | for i in 2..y.len() { |
| 520 | let (low, high) = self.floor.neighbours[i]; |
| 521 | let predicted = predict( |
| 522 | self.floor.x_list[low], |
| 523 | y[low], |
| 524 | self.floor.x_list[high], |
| 525 | y[high], |
| 526 | self.floor.x_list[i], |
| 527 | ); |
| 528 | let value = fold(predicted, y[i], 256); |
| 529 | self.floor_book.write(out, value as usize); |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | |
| 534 | |
| 535 | fn write_residue(&self, out: &mut BitsOut, quantised: &[Vec<i32>]) { |
| 536 | let channels = quantised.len(); |
| 537 | let total = HALF * channels; |
| 538 | let mut interleaved = vec![0i32; total]; |
| 539 | for (i, slot) in interleaved.iter_mut().enumerate() { |
| 540 | *slot = quantised[i % channels][i / channels]; |
| 541 | } |
| 542 | let partitions = total / PARTITION; |
| 543 | let classes: Vec<usize> = (0..partitions) |
| 544 | .map(|partition| { |
| 545 | let slice = &interleaved[partition * PARTITION..(partition + 1) * PARTITION]; |
| 546 | let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0); |
| 547 | CLASS_RANGE |
| 548 | .iter() |
| 549 | .position(|&range| peak <= range) |
| 550 | .unwrap_or(CLASSES - 1) |
| 551 | }) |
| 552 | .collect(); |
| 553 | let per_word = self.class_book.dimensions; |
| 554 | let mut partition = 0usize; |
| 555 | while partition < partitions { |
| 556 | let mut word = 0usize; |
| 557 | for i in 0..per_word { |
| 558 | word = word * CLASSES + classes.get(partition + i).copied().unwrap_or(0); |
| 559 | } |
| 560 | self.class_book.write(out, word); |
| 561 | for _ in 0..per_word { |
| 562 | if partition >= partitions { |
| 563 | break; |
| 564 | } |
| 565 | let class = classes[partition]; |
| 566 | if class > 0 { |
| 567 | let book = &self.residue_books[class - 1]; |
| 568 | let range = CLASS_RANGE[class]; |
| 569 | for &value in &interleaved[partition * PARTITION..(partition + 1) * PARTITION] { |
| 570 | book.write(out, (value.clamp(-range, range) + range) as usize); |
| 571 | } |
| 572 | } |
| 573 | partition += 1; |
| 574 | } |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | |
| 579 | |
| 580 | |
| 581 | |
| 582 | |
| 583 | |
| 584 | fn update_rate(&mut self, bits: u64, channels: usize) { |
| 585 | if self.config.bitrate_bps <= 0 { |
| 586 | return; |
| 587 | } |
| 588 | let target = |
| 589 | f64::from(self.config.bitrate_bps) * HOP as f64 / f64::from(self.config.sample_rate); |
| 590 | let coefficients = (HALF * channels) as f64; |
| 591 | let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0); |
| 592 | |
| 593 | |
| 594 | |
| 595 | |
| 596 | |
| 597 | self.headroom = (self.headroom + step).clamp(-24.0, 36.0); |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | |
| 602 | fn couple(left: i32, right: i32) -> (i32, i32) { |
| 603 | match left > 0 { |
| 604 | true => match left > right { |
| 605 | true => (left, left - right), |
| 606 | false => (right, left - right), |
| 607 | }, |
| 608 | false => match right > left { |
| 609 | true => (left, right - left), |
| 610 | false => (right, right - left), |
| 611 | }, |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | |
| 616 | fn predict(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 { |
| 617 | let dy = y1 - y0; |
| 618 | let adx = (x1 - x0) as i32; |
| 619 | let ady = dy.abs(); |
| 620 | let off = (ady * (x - x0) as i32) / adx; |
| 621 | match dy < 0 { |
| 622 | true => y0 - off, |
| 623 | false => y0 + off, |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | |
| 628 | |
| 629 | fn fold(predicted: i32, wanted: i32, range: i32) -> i32 { |
| 630 | let high_room = range - predicted; |
| 631 | let low_room = predicted; |
| 632 | let room = high_room.min(low_room) * 2; |
| 633 | let delta = wanted - predicted; |
| 634 | if delta == 0 { |
| 635 | return 0; |
| 636 | } |
| 637 | if delta > 0 && 2 * delta < room { |
| 638 | return 2 * delta; |
| 639 | } |
| 640 | if delta < 0 && -2 * delta - 1 < room { |
| 641 | return -2 * delta - 1; |
| 642 | } |
| 643 | match high_room > low_room { |
| 644 | true => wanted - predicted + low_room, |
| 645 | false => predicted - wanted + high_room - 1, |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | |
| 650 | fn build_floor() -> Floor1 { |
| 651 | let mut sorted_x: Vec<u32> = Vec::with_capacity(FLOOR_POINTS); |
| 652 | let mut last = 0u32; |
| 653 | for i in 0..FLOOR_POINTS { |
| 654 | let t = i as f64 / (FLOOR_POINTS - 1) as f64; |
| 655 | |
| 656 | |
| 657 | let value = (1023f64).powf(t).round() as u32; |
| 658 | last = value.max(last + 1); |
| 659 | sorted_x.push(last); |
| 660 | } |
| 661 | |
| 662 | |
| 663 | let mut x_list = vec![0u32, HALF as u32]; |
| 664 | let mut ranges = vec![(0usize, sorted_x.len())]; |
| 665 | while let Some((lo, hi)) = ranges.pop() { |
| 666 | if lo >= hi { |
| 667 | continue; |
| 668 | } |
| 669 | let mid = (lo + hi) / 2; |
| 670 | x_list.push(sorted_x[mid]); |
| 671 | ranges.insert(0, (lo, mid)); |
| 672 | ranges.insert(0, (mid + 1, hi)); |
| 673 | } |
| 674 | let values = x_list.len(); |
| 675 | let mut sorted: Vec<usize> = (0..values).collect(); |
| 676 | sorted.sort_by_key(|&i| x_list[i]); |
| 677 | let neighbours = (0..values) |
| 678 | .map(|i| { |
| 679 | let mut low = 0usize; |
| 680 | let mut high = 0usize; |
| 681 | let mut low_x = None; |
| 682 | let mut high_x = None; |
| 683 | for j in 0..i { |
| 684 | if x_list[j] < x_list[i] && low_x.is_none_or(|b| x_list[j] > b) { |
| 685 | low = j; |
| 686 | low_x = Some(x_list[j]); |
| 687 | } |
| 688 | if x_list[j] > x_list[i] && high_x.is_none_or(|b| x_list[j] < b) { |
| 689 | high = j; |
| 690 | high_x = Some(x_list[j]); |
| 691 | } |
| 692 | } |
| 693 | (low, high) |
| 694 | }) |
| 695 | .collect(); |
| 696 | let partitions = (values - 2) / FLOOR_CLASS_DIM; |
| 697 | Floor1 { |
| 698 | partition_classes: vec![0; partitions], |
| 699 | class_dimensions: vec![FLOOR_CLASS_DIM], |
| 700 | class_subclasses: vec![0], |
| 701 | class_masterbooks: vec![0], |
| 702 | subclass_books: vec![vec![0]], |
| 703 | multiplier: 1, |
| 704 | x_list, |
| 705 | sorted, |
| 706 | neighbours, |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | |
| 711 | |
| 712 | fn design_floor_book() -> CodebookSpec { |
| 713 | let weights: Vec<f64> = (0..256) |
| 714 | .map(|v| (-(f64::from(v)) / 7.0).exp() + 0.002) |
| 715 | .collect(); |
| 716 | CodebookSpec::huffman(&weights, Vec::new()) |
| 717 | } |
| 718 | |
| 719 | |
| 720 | fn design_class_book() -> CodebookSpec { |
| 721 | let per_class = [0.55f64, 0.20, 0.15, 0.08, 0.02]; |
| 722 | let mut weights = Vec::with_capacity(CLASSES * CLASSES); |
| 723 | for first in per_class { |
| 724 | for second in per_class { |
| 725 | weights.push(first * second); |
| 726 | } |
| 727 | } |
| 728 | let mut spec = CodebookSpec::huffman(&weights, Vec::new()); |
| 729 | spec.dimensions = 2; |
| 730 | spec |
| 731 | } |
| 732 | |
| 733 | |
| 734 | fn design_residue_books() -> Vec<CodebookSpec> { |
| 735 | CLASS_RANGE[1..] |
| 736 | .iter() |
| 737 | .map(|&range| { |
| 738 | let sigma = f64::from(range).max(1.0) / 2.5; |
| 739 | let weights: Vec<f64> = (-range..=range) |
| 740 | .map(|v| (-f64::from(v.abs()) / sigma).exp() + 1e-4) |
| 741 | .collect(); |
| 742 | let values: Vec<f32> = (-range..=range).map(|v| v as f32).collect(); |
| 743 | CodebookSpec::huffman(&weights, values) |
| 744 | }) |
| 745 | .collect() |
| 746 | } |
| 747 | |
| 748 | |
| 749 | fn absolute_threshold(hz: f64) -> f64 { |
| 750 | let khz = (hz / 1000.0).clamp(0.02, 20.0); |
| 751 | let spl = |
| 752 | 3.64 * khz.powf(-0.8) - 6.5 * (-0.6 * (khz - 3.3).powi(2)).exp() + 0.001 * khz.powi(4); |
| 753 | (spl - 96.0).clamp(-120.0, -10.0) |
| 754 | } |
| 755 | |
| 756 | |
| 757 | fn write_headers( |
| 758 | config: &EncoderConfig, |
| 759 | channels: usize, |
| 760 | floor: &Floor1, |
| 761 | floor_book: &CodebookSpec, |
| 762 | class_book: &CodebookSpec, |
| 763 | residue_books: &[CodebookSpec], |
| 764 | coupling: &[(usize, usize)], |
| 765 | ) -> Vec<Vec<u8>> { |
| 766 | let mut ident = vec![1u8]; |
| 767 | ident.extend_from_slice(b"vorbis"); |
| 768 | ident.extend_from_slice(&0u32.to_le_bytes()); |
| 769 | ident.push(channels as u8); |
| 770 | ident.extend_from_slice(&config.sample_rate.to_le_bytes()); |
| 771 | ident.extend_from_slice(&0i32.to_le_bytes()); |
| 772 | ident.extend_from_slice(&config.bitrate_bps.max(0).to_le_bytes()); |
| 773 | ident.extend_from_slice(&0i32.to_le_bytes()); |
| 774 | let log2 = |n: usize| n.trailing_zeros() as u8; |
| 775 | ident.push(log2(BLOCK) | (log2(BLOCK) << 4)); |
| 776 | ident.push(1); |
| 777 | |
| 778 | let mut comment = vec![3u8]; |
| 779 | comment.extend_from_slice(b"vorbis"); |
| 780 | let vendor = b"ec-vorbis"; |
| 781 | comment.extend_from_slice(&(vendor.len() as u32).to_le_bytes()); |
| 782 | comment.extend_from_slice(vendor); |
| 783 | comment.extend_from_slice(&0u32.to_le_bytes()); |
| 784 | comment.push(1); |
| 785 | |
| 786 | let mut out = BitsOut::new(); |
| 787 | for byte in [5u8].iter().chain(b"vorbis") { |
| 788 | out.write(u32::from(*byte), 8); |
| 789 | } |
| 790 | let books: Vec<&CodebookSpec> = std::iter::once(floor_book) |
| 791 | .chain(std::iter::once(class_book)) |
| 792 | .chain(residue_books.iter()) |
| 793 | .collect(); |
| 794 | out.write(books.len() as u32 - 1, 8); |
| 795 | for book in &books { |
| 796 | write_codebook(&mut out, book); |
| 797 | } |
| 798 | |
| 799 | out.write(0, 6); |
| 800 | out.write(0, 16); |
| 801 | |
| 802 | out.write(0, 6); |
| 803 | out.write(1, 16); |
| 804 | out.write(floor.partition_classes.len() as u32, 5); |
| 805 | for _ in &floor.partition_classes { |
| 806 | out.write(0, 4); |
| 807 | } |
| 808 | out.write(FLOOR_CLASS_DIM as u32 - 1, 3); |
| 809 | out.write(0, 2); |
| 810 | |
| 811 | out.write(1, 8); |
| 812 | out.write(0, 2); |
| 813 | let range_bits = ilog(HALF as u32) - 1; |
| 814 | out.write(range_bits, 4); |
| 815 | for &x in floor.x_list.iter().skip(2) { |
| 816 | out.write(x, range_bits); |
| 817 | } |
| 818 | |
| 819 | out.write(0, 6); |
| 820 | out.write(2, 16); |
| 821 | out.write(0, 24); |
| 822 | out.write((HALF * channels) as u32, 24); |
| 823 | out.write(PARTITION as u32 - 1, 24); |
| 824 | out.write(CLASSES as u32 - 1, 6); |
| 825 | out.write(1, 8); |
| 826 | for class in 0..CLASSES { |
| 827 | |
| 828 | out.write(u32::from(class > 0), 3); |
| 829 | out.write(0, 1); |
| 830 | } |
| 831 | for class in 1..CLASSES { |
| 832 | out.write(class as u32 + 1, 8); |
| 833 | } |
| 834 | |
| 835 | out.write(0, 6); |
| 836 | out.write(0, 16); |
| 837 | out.write(0, 1); |
| 838 | match coupling.is_empty() { |
| 839 | true => out.write(0, 1), |
| 840 | false => { |
| 841 | out.write(1, 1); |
| 842 | out.write(coupling.len() as u32 - 1, 8); |
| 843 | let field = ilog(channels as u32 - 1); |
| 844 | for &(magnitude, angle) in coupling { |
| 845 | out.write(magnitude as u32, field); |
| 846 | out.write(angle as u32, field); |
| 847 | } |
| 848 | } |
| 849 | } |
| 850 | out.write(0, 2); |
| 851 | out.write(0, 8); |
| 852 | out.write(0, 8); |
| 853 | out.write(0, 8); |
| 854 | |
| 855 | out.write(0, 6); |
| 856 | out.write(1, 1); |
| 857 | out.write(0, 16); |
| 858 | out.write(0, 16); |
| 859 | out.write(0, 8); |
| 860 | out.write(1, 1); |
| 861 | let setup = out.finish(); |
| 862 | |
| 863 | vec![ident, comment, setup] |
| 864 | } |
| 865 | |
| 866 | |
| 867 | |
| 868 | fn write_codebook(out: &mut BitsOut, book: &CodebookSpec) { |
| 869 | out.write(0x0056_4342, 24); |
| 870 | out.write(book.dimensions as u32, 16); |
| 871 | out.write(book.entries() as u32, 24); |
| 872 | out.write(0, 1); |
| 873 | out.write(0, 1); |
| 874 | for &length in &book.lengths { |
| 875 | out.write(u32::from(length) - 1, 5); |
| 876 | } |
| 877 | if book.values.is_empty() { |
| 878 | out.write(0, 4); |
| 879 | return; |
| 880 | } |
| 881 | |
| 882 | |
| 883 | out.write(1, 4); |
| 884 | let minimum = book.values[0]; |
| 885 | out.write(float32_pack(minimum), 32); |
| 886 | out.write(float32_pack(1.0), 32); |
| 887 | let value_bits = ilog(book.entries() as u32 - 1).max(1); |
| 888 | out.write(value_bits - 1, 4); |
| 889 | out.write(0, 1); |
| 890 | for i in 0..book.entries() { |
| 891 | out.write(i as u32, value_bits); |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | |
| 896 | fn lace(headers: &[Vec<u8>]) -> Vec<u8> { |
| 897 | let mut out = vec![2u8]; |
| 898 | for header in headers.iter().take(headers.len() - 1) { |
| 899 | let mut length = header.len(); |
| 900 | while length >= 255 { |
| 901 | out.push(255); |
| 902 | length -= 255; |
| 903 | } |
| 904 | out.push(length as u8); |
| 905 | } |
| 906 | for header in headers { |
| 907 | out.extend_from_slice(header); |
| 908 | } |
| 909 | out |
| 910 | } |
| 911 | |
| 912 | impl Encoder for VorbisEncoder { |
| 913 | fn codec_parameters(&self) -> &CodecParameters { |
| 914 | &self.params |
| 915 | } |
| 916 | |
| 917 | fn send_frame(&mut self, frame: &Frame) -> Result<()> { |
| 918 | let Frame::Audio(audio) = frame else { |
| 919 | return Err(Error::corrupt("video frame pushed into an audio encoder")); |
| 920 | }; |
| 921 | if audio.format != SampleFormat::F32 { |
| 922 | return Err(Error::unsupported( |
| 923 | format!("{:?} input", audio.format), |
| 924 | "this encoder takes 32-bit float samples", |
| 925 | )); |
| 926 | } |
| 927 | let channels = usize::from(self.config.channels); |
| 928 | let mut planes: Vec<Vec<f32>> = vec![Vec::with_capacity(audio.samples); channels]; |
| 929 | match audio.planar { |
| 930 | true => { |
| 931 | for (channel, plane) in audio.data.iter().enumerate().take(channels) { |
| 932 | planes[channel] = floats(plane, audio.samples); |
| 933 | } |
| 934 | } |
| 935 | false => { |
| 936 | let interleaved = floats(&audio.data[0], audio.samples * channels); |
| 937 | for (i, value) in interleaved.into_iter().enumerate() { |
| 938 | planes[i % channels].push(value); |
| 939 | } |
| 940 | } |
| 941 | } |
| 942 | let borrowed: Vec<&[f32]> = planes.iter().map(|p| &p[..]).collect(); |
| 943 | self.push_planar(&borrowed) |
| 944 | } |
| 945 | |
| 946 | fn receive_packet(&mut self) -> Result<Packet> { |
| 947 | let encoded = self.next_packet()?; |
| 948 | let base = TimeBase::new(1, i64::from(self.config.sample_rate)); |
| 949 | let mut packet = Packet::new(0, base, encoded.data); |
| 950 | packet.pts = Some(encoded.granule - encoded.samples); |
| 951 | packet.duration = Some(encoded.samples); |
| 952 | Ok(packet) |
| 953 | } |
| 954 | |
| 955 | fn flush(&mut self) -> Result<()> { |
| 956 | self.finish(); |
| 957 | Ok(()) |
| 958 | } |
| 959 | } |
| 960 | |
| 961 | |
| 962 | fn floats(plane: &Buf, count: usize) -> Vec<f32> { |
| 963 | plane |
| 964 | .chunks_exact(4) |
| 965 | .take(count) |
| 966 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 967 | .collect() |
| 968 | } |
| 969 | |
| 970 | #[cfg(test)] |
| 971 | mod tests { |
| 972 | use super::*; |
| 973 | |
| 974 | #[test] |
| 975 | fn folding_is_the_exact_inverse_of_the_decoder() { |
| 976 | |
| 977 | |
| 978 | for predicted in [0i32, 1, 40, 128, 200, 255] { |
| 979 | for wanted in 0..256i32 { |
| 980 | let value = fold(predicted, wanted, 256); |
| 981 | assert!((0..256).contains(&value), "{predicted}->{wanted}: {value}"); |
| 982 | assert_eq!( |
| 983 | unfold(predicted, value, 256), |
| 984 | wanted, |
| 985 | "predicted {predicted}, wanted {wanted}, coded {value}" |
| 986 | ); |
| 987 | } |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | |
| 992 | fn unfold(predicted: i32, value: i32, range: i32) -> i32 { |
| 993 | let high_room = range - predicted; |
| 994 | let low_room = predicted; |
| 995 | let room = high_room.min(low_room) * 2; |
| 996 | if value == 0 { |
| 997 | return predicted; |
| 998 | } |
| 999 | match value >= room { |
| 1000 | true => match high_room > low_room { |
| 1001 | true => value - low_room + predicted, |
| 1002 | false => predicted - value + high_room - 1, |
| 1003 | }, |
| 1004 | false => match value & 1 == 1 { |
| 1005 | true => predicted - (value + 1) / 2, |
| 1006 | false => predicted + value / 2, |
| 1007 | }, |
| 1008 | } |
| 1009 | } |
| 1010 | |
| 1011 | #[test] |
| 1012 | fn coupling_round_trips_every_sign_case() { |
| 1013 | for left in -8..=8i32 { |
| 1014 | for right in -8..=8i32 { |
| 1015 | let (m, a) = couple(left, right); |
| 1016 | let (back_l, back_r) = match (m > 0, a > 0) { |
| 1017 | (true, true) => (m, m - a), |
| 1018 | (true, false) => (m + a, m), |
| 1019 | (false, true) => (m, m + a), |
| 1020 | (false, false) => (m - a, m), |
| 1021 | }; |
| 1022 | assert_eq!((back_l, back_r), (left, right), "{left},{right}"); |
| 1023 | } |
| 1024 | } |
| 1025 | } |
| 1026 | } |