forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB1f91eddTahinli2 months ago3507 commits

encode.rs966 lines, 30.7 KiBHistoryRawDownload
1//! FLAC encoding: fixed-block-size streams with constant, fixed, LPC and
2//! verbatim subframes, a Rice partition search per residual and a per-block
3//! stereo decorrelation decision.
4//!
5//! The output is a complete `.flac` file: `fLaC`, one `STREAMINFO` (carrying
6//! the MD5 of the input, so any decoder can check us), then the frames.
7
8use ec_core::bitio::BitWriter;
9use ec_core::error::{Error, Result};
10
11use crate::checksum::{crc8, crc16, md5_of_samples};
12use crate::decode::StreamInfo;
13
14/// Encoder settings. [`EncoderConfig::default`] is the level the family ships:
15/// 4096-sample blocks, LPC to order 12, Rice partitions to order 6.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct EncoderConfig {
18 /// Inter-channel samples per frame.
19 pub block_size: usize,
20 /// Highest LPC order tried; 0 disables LPC and leaves the fixed predictors.
21 pub max_lpc_order: usize,
22 /// Bits each quantised LPC coefficient is stored in (5..=15).
23 pub qlp_precision: u32,
24 /// Highest Rice partition order tried.
25 pub max_partition_order: u32,
26 /// Try left/side, right/side and mid/side on stereo input.
27 pub stereo_decorrelation: bool,
28}
29
30impl Default for EncoderConfig {
31 fn default() -> Self {
32 EncoderConfig {
33 block_size: 4096,
34 max_lpc_order: 12,
35 qlp_precision: 15,
36 max_partition_order: 6,
37 stereo_decorrelation: true,
38 }
39 }
40}
41
42impl EncoderConfig {
43 /// Refuse settings that cannot produce a legal stream.
44 pub fn verify(&self) -> Result<()> {
45 if !(16..=65535).contains(&self.block_size) {
46 return Err(Error::unsupported(
47 format!("block size {}", self.block_size),
48 "RFC 9639 allows 16..=65535",
49 ));
50 }
51 if self.max_lpc_order > 32 {
52 return Err(Error::unsupported(
53 format!("LPC order {}", self.max_lpc_order),
54 "RFC 9639 allows up to 32",
55 ));
56 }
57 if !(5..=15).contains(&self.qlp_precision) {
58 return Err(Error::unsupported(
59 format!("coefficient precision {}", self.qlp_precision),
60 "RFC 9639 allows 1..=15; below 5 is never useful",
61 ));
62 }
63 if self.max_partition_order > 15 {
64 return Err(Error::unsupported(
65 format!("partition order {}", self.max_partition_order),
66 "RFC 9639 allows up to 15",
67 ));
68 }
69 Ok(())
70 }
71}
72
73/// Encode interleaved samples into a complete FLAC stream.
74///
75/// `samples` are interleaved by channel and must already fit in
76/// `bits_per_sample`: a sample outside that range is [`Error::Corrupt`],
77/// because silently clipping the caller's audio would make a lossless codec
78/// lossy.
79pub fn encode(
80 config: &EncoderConfig,
81 samples: &[i32],
82 channels: usize,
83 bits_per_sample: u32,
84 sample_rate: u32,
85) -> Result<Vec<u8>> {
86 config.verify()?;
87 if !(1..=8).contains(&channels) {
88 return Err(Error::unsupported(
89 format!("{channels} channels"),
90 "FLAC codes 1..=8 channels",
91 ));
92 }
93 if !(4..=32).contains(&bits_per_sample) {
94 return Err(Error::unsupported(
95 format!("{bits_per_sample} bits per sample"),
96 "FLAC codes 4..=32 bits",
97 ));
98 }
99 if sample_rate == 0 || sample_rate > 655_350 {
100 return Err(Error::unsupported(
101 format!("{sample_rate} Hz"),
102 "FLAC codes 1..=655350 Hz",
103 ));
104 }
105 if !samples.len().is_multiple_of(channels) {
106 return Err(Error::corrupt(format!(
107 "{} samples do not divide into {channels} channels",
108 samples.len()
109 )));
110 }
111 let (low, high) = match bits_per_sample {
112 32 => (i32::MIN, i32::MAX),
113 n => (-(1i32 << (n - 1)), (1i32 << (n - 1)) - 1),
114 };
115 if let Some(bad) = samples.iter().find(|&&s| s < low || s > high) {
116 return Err(Error::corrupt(format!(
117 "sample {bad} does not fit in {bits_per_sample} bits"
118 )));
119 }
120
121 let frames = samples.len() / channels;
122 let mut info = StreamInfo {
123 min_block_size: config.block_size as u16,
124 max_block_size: config.block_size as u16,
125 min_frame_size: 0,
126 max_frame_size: 0,
127 sample_rate,
128 channels: channels as u8,
129 bits_per_sample: bits_per_sample as u8,
130 total_samples: frames as u64,
131 md5: md5_of_samples(samples, bits_per_sample),
132 };
133
134 let mut out = Vec::with_capacity(samples.len() * bits_per_sample as usize / 8);
135 out.extend_from_slice(&crate::decode::MAGIC);
136 out.push(0x80); // last metadata block, type 0 (STREAMINFO)
137 out.extend_from_slice(&[0, 0, 34]);
138 let streaminfo_at = out.len();
139 out.extend_from_slice(&info.to_bytes());
140
141 let mut planes: Vec<Vec<i32>> = (0..channels)
142 .map(|_| Vec::with_capacity(config.block_size))
143 .collect();
144 let mut scratch = Scratch::default();
145 let mut min_frame = u32::MAX;
146 let mut max_frame = 0u32;
147 for (number, block) in samples.chunks(config.block_size * channels).enumerate() {
148 let block_size = block.len() / channels;
149 for (c, plane) in planes.iter_mut().enumerate() {
150 plane.clear();
151 plane.extend(block.iter().skip(c).step_by(channels).copied());
152 }
153 let frame = encode_frame(
154 config,
155 &planes,
156 block_size,
157 bits_per_sample,
158 sample_rate,
159 number as u64,
160 &mut scratch,
161 );
162 min_frame = min_frame.min(frame.len() as u32);
163 max_frame = max_frame.max(frame.len() as u32);
164 out.extend_from_slice(&frame);
165 }
166 if frames > 0 {
167 info.min_frame_size = min_frame;
168 info.max_frame_size = max_frame;
169 out[streaminfo_at..streaminfo_at + 34].copy_from_slice(&info.to_bytes());
170 }
171 Ok(out)
172}
173
174/// Buffers reused across blocks: the two stereo candidates and the analysis
175/// window, which depends only on the block size and so is built once.
176#[derive(Debug, Default)]
177struct Scratch {
178 mid: Vec<i32>,
179 side: Vec<i32>,
180 window: Vec<f64>,
181}
182
183impl Scratch {
184 fn ensure_window(&mut self, n: usize) {
185 if self.window.len() != n {
186 self.window = tukey_window(n);
187 }
188 }
189}
190
191#[allow(clippy::too_many_arguments)]
192fn encode_frame(
193 config: &EncoderConfig,
194 planes: &[Vec<i32>],
195 block_size: usize,
196 bits_per_sample: u32,
197 sample_rate: u32,
198 number: u64,
199 scratch: &mut Scratch,
200) -> Vec<u8> {
201 let channels = planes.len();
202 // Channel assignment: 0..7 = that many independent channels, 8 = left/side,
203 // 9 = right/side, 10 = mid/side. Each candidate signal is planned once and
204 // the cheapest pairing wins — planning carries all the search cost, writing
205 // carries none.
206 let stereo = channels == 2 && config.stereo_decorrelation && bits_per_sample < 32;
207 if stereo {
208 scratch.mid.clear();
209 scratch.side.clear();
210 for (&l, &r) in planes[0].iter().zip(&planes[1]) {
211 // i64 first: `l - r` of two full-depth samples does not fit in i32.
212 scratch
213 .mid
214 .push(((i64::from(l) + i64::from(r)) >> 1) as i32);
215 scratch.side.push((i64::from(l) - i64::from(r)) as i32);
216 }
217 }
218 scratch.ensure_window(block_size);
219 let window = &scratch.window;
220
221 let mut plans: Vec<SubframePlan> = planes
222 .iter()
223 .map(|plane| plan_subframe(config, plane, bits_per_sample, window))
224 .collect();
225 let mut assignment = channels as u32 - 1;
226 if stereo {
227 let mid = plan_subframe(config, &scratch.mid, bits_per_sample, window);
228 // The side channel needs one bit more than the stream's depth, which is
229 // why a 32-bit stream cannot be decorrelated at all.
230 let side = plan_subframe(config, &scratch.side, bits_per_sample + 1, window);
231 let (l, r) = (plans[0].bits, plans[1].bits);
232 let (_, best) = [
233 (l + r, 1u32),
234 (l + side.bits, 8),
235 (side.bits + r, 9),
236 (mid.bits + side.bits, 10),
237 ]
238 .into_iter()
239 .min()
240 .expect("four candidates");
241 assignment = best;
242 match best {
243 8 => plans[1] = side,
244 9 => plans[0] = side,
245 10 => {
246 plans[0] = mid;
247 plans[1] = side;
248 }
249 _ => {}
250 }
251 }
252
253 let mut w = BitWriter::with_capacity(block_size * channels * 2);
254 write_frame_header(
255 &mut w,
256 block_size,
257 sample_rate,
258 assignment,
259 bits_per_sample,
260 number,
261 );
262 debug_assert!(w.is_byte_aligned());
263 let crc = crc8(w.as_bytes());
264 w.write_bits(u32::from(crc), 8);
265 for (c, plan) in plans.iter().enumerate() {
266 let side = matches!((assignment, c), (8, 1) | (10, 1) | (9, 0));
267 write_subframe(&mut w, plan, bits_per_sample + u32::from(side));
268 }
269 w.align_to_byte();
270 let crc = crc16(w.as_bytes());
271 w.write_bits(u32::from(crc), 16);
272 w.into_bytes()
273}
274
275fn write_frame_header(
276 w: &mut BitWriter,
277 block_size: usize,
278 sample_rate: u32,
279 assignment: u32,
280 bits_per_sample: u32,
281 number: u64,
282) {
283 let (bs_code, bs_extra) = match block_size {
284 192 => (1, None),
285 576 => (2, None),
286 1152 => (3, None),
287 2304 => (4, None),
288 4608 => (5, None),
289 256 => (8, None),
290 512 => (9, None),
291 1024 => (10, None),
292 2048 => (11, None),
293 4096 => (12, None),
294 8192 => (13, None),
295 16384 => (14, None),
296 32768 => (15, None),
297 n if n <= 256 => (6, Some((n as u32 - 1, 8))),
298 n => (7, Some((n as u32 - 1, 16))),
299 };
300 let (sr_code, sr_extra) = match sample_rate {
301 88200 => (1, None),
302 176_400 => (2, None),
303 192_000 => (3, None),
304 8000 => (4, None),
305 16000 => (5, None),
306 22050 => (6, None),
307 24000 => (7, None),
308 32000 => (8, None),
309 44100 => (9, None),
310 48000 => (10, None),
311 96000 => (11, None),
312 n if n.is_multiple_of(1000) && n / 1000 <= 255 => (12, Some((n / 1000, 8))),
313 n if n <= 65535 => (13, Some((n, 16))),
314 n if n.is_multiple_of(10) && n / 10 <= 65535 => (14, Some((n / 10, 16))),
315 // Every rate `encode` accepts is covered above; code 0 (take the rate
316 // from STREAMINFO) is the honest fallback rather than a panic.
317 _ => (0, None),
318 };
319 let bps_code = match bits_per_sample {
320 8 => 1,
321 12 => 2,
322 16 => 4,
323 20 => 5,
324 24 => 6,
325 32 => 7,
326 _ => 0,
327 };
328 w.write_bits(0x3ffe, 14);
329 w.write_bit(false); // reserved
330 w.write_bit(false); // fixed block size: the coded number is a frame number
331 w.write_bits(bs_code, 4);
332 w.write_bits(sr_code, 4);
333 w.write_bits(assignment, 4);
334 w.write_bits(bps_code, 3);
335 w.write_bit(false); // reserved
336 write_utf8_number(w, number);
337 if let Some((value, bits)) = bs_extra {
338 w.write_bits(value, bits);
339 }
340 if let Some((value, bits)) = sr_extra {
341 w.write_bits(value, bits);
342 }
343}
344
345/// The UTF-8-shaped coded number of a frame header (up to 36 bits, so wider
346/// than real UTF-8 ever goes).
347fn write_utf8_number(w: &mut BitWriter, value: u64) {
348 if value < 0x80 {
349 w.write_bits(value as u32, 8);
350 return;
351 }
352 // `extra` continuation bytes carry 6 bits each; the lead byte carries
353 // `6 - extra` after its prefix of `extra + 1` ones and a zero.
354 let mut extra = 1usize;
355 while extra < 6 && value >= 1u64 << (6 * extra + (6 - extra)) {
356 extra += 1;
357 }
358 let lead_bits = 6 - extra as u32;
359 let prefix = (0xffu32 << (7 - extra)) & 0xff;
360 let lead = prefix | ((value >> (6 * extra)) as u32 & ((1 << lead_bits) - 1));
361 w.write_bits(lead, 8);
362 for i in (0..extra).rev() {
363 w.write_bits(0x80 | ((value >> (6 * i)) as u32 & 0x3f), 8);
364 }
365}
366
367/// What a subframe will be written as, with its exact cost in bits.
368#[derive(Debug, Clone)]
369struct SubframePlan {
370 bits: usize,
371 wasted: u32,
372 kind: PlanKind,
373}
374
375#[derive(Debug, Clone)]
376enum PlanKind {
377 Constant(i32),
378 Verbatim(Vec<i32>),
379 Fixed {
380 warmup: Vec<i32>,
381 residual: Vec<i32>,
382 rice: RicePlan,
383 },
384 Lpc {
385 warmup: Vec<i32>,
386 precision: u32,
387 shift: u32,
388 coefs: Vec<i32>,
389 residual: Vec<i32>,
390 rice: RicePlan,
391 },
392}
393
394#[derive(Debug, Clone, Default)]
395struct RicePlan {
396 /// 4 or 5: the width of a partition's Rice parameter field.
397 param_bits: u32,
398 partition_order: u32,
399 /// Predictor order, which is what makes partition 0 shorter than the rest.
400 order: usize,
401 params: Vec<u32>,
402}
403
404fn plan_subframe(config: &EncoderConfig, signal: &[i32], bps: u32, window: &[f64]) -> SubframePlan {
405 // Wasted bits: when every sample shares trailing zeros, state them once in
406 // the subframe header instead of once per sample.
407 let any_set = signal.iter().fold(0u32, |acc, &s| acc | s as u32);
408 let wasted = match any_set {
409 0 => 0,
410 n => n.trailing_zeros().min(bps - 1),
411 };
412 let shifted: Vec<i32>;
413 let signal = match wasted {
414 0 => signal,
415 n => {
416 shifted = signal.iter().map(|&s| s >> n).collect();
417 &shifted
418 }
419 };
420 let bps = bps - wasted;
421 let header_bits = 8 + wasted as usize;
422
423 if signal.is_empty() {
424 return SubframePlan {
425 bits: header_bits + bps as usize,
426 wasted,
427 kind: PlanKind::Constant(0),
428 };
429 }
430 if signal.iter().all(|&s| s == signal[0]) {
431 return SubframePlan {
432 bits: header_bits + bps as usize,
433 wasted,
434 kind: PlanKind::Constant(signal[0]),
435 };
436 }
437
438 let mut best = SubframePlan {
439 bits: header_bits + signal.len() * bps as usize,
440 wasted,
441 kind: PlanKind::Verbatim(signal.to_vec()),
442 };
443 if let Some(plan) = plan_fixed(config, signal, bps, header_bits)
444 && plan.bits < best.bits
445 {
446 best = SubframePlan { wasted, ..plan };
447 }
448 if config.max_lpc_order > 0
449 && signal.len() > config.max_lpc_order
450 && window.len() == signal.len()
451 && let Some(plan) = plan_lpc(config, signal, bps, header_bits, window)
452 && plan.bits < best.bits
453 {
454 best = SubframePlan { wasted, ..plan };
455 }
456 best
457}
458
459/// The five fixed predictors, the order chosen by the sum of absolute
460/// residuals — the standard estimate; the Rice search then costs it exactly.
461fn plan_fixed(
462 config: &EncoderConfig,
463 signal: &[i32],
464 bps: u32,
465 header_bits: usize,
466) -> Option<SubframePlan> {
467 let max_order = 4.min(signal.len().saturating_sub(1));
468 let mut diffs: Vec<Vec<i64>> = Vec::with_capacity(max_order + 1);
469 diffs.push(signal.iter().map(|&s| i64::from(s)).collect());
470 for order in 1..=max_order {
471 diffs.push(diffs[order - 1].windows(2).map(|w| w[1] - w[0]).collect());
472 }
473 // Compare orders over the same samples, so the estimate is not biased by a
474 // higher order simply covering fewer of them.
475 let order = (0..=max_order).min_by_key(|&o| {
476 let tail: u64 = diffs[o][max_order - o..]
477 .iter()
478 .map(|&d| d.unsigned_abs())
479 .sum();
480 tail + (o as u64) * u64::from(bps)
481 })?;
482 let residual: Vec<i32> = diffs[order]
483 .iter()
484 .map(|&d| i32::try_from(d))
485 .collect::<std::result::Result<_, _>>()
486 .ok()?; // 32-bit input can overflow the residual; verbatim wins then.
487 let rice = plan_rice(config, &residual, signal.len(), order);
488 Some(SubframePlan {
489 bits: header_bits + order * bps as usize + rice.bits,
490 wasted: 0,
491 kind: PlanKind::Fixed {
492 warmup: signal[..order].to_vec(),
493 residual,
494 rice: rice.plan,
495 },
496 })
497}
498
499fn plan_lpc(
500 config: &EncoderConfig,
501 signal: &[i32],
502 bps: u32,
503 header_bits: usize,
504 window: &[f64],
505) -> Option<SubframePlan> {
506 let max_order = config.max_lpc_order.min(signal.len() - 1).min(32);
507 if max_order == 0 {
508 return None;
509 }
510 let windowed: Vec<f64> = window
511 .iter()
512 .zip(signal)
513 .map(|(w, &s)| w * f64::from(s))
514 .collect();
515 let autoc = autocorrelation(&windowed, max_order);
516 if autoc[0] == 0.0 {
517 return None;
518 }
519 let (coefs_by_order, errors) = levinson_durbin(&autoc, max_order);
520
521 // Order choice by the usual estimate: every order costs its coefficients
522 // and saves half a bit per sample per halving of the prediction error.
523 let n = signal.len() as f64;
524 let cost = |o: usize| {
525 n / 2.0 * errors[o].max(1e-9).log2() + (o as f64) * f64::from(config.qlp_precision)
526 };
527 let order = (1..=max_order)
528 .filter(|&o| !coefs_by_order[o].is_empty())
529 .min_by(|&a, &b| cost(a).total_cmp(&cost(b)))?;
530
531 let (coefs, shift) = quantize_coefficients(&coefs_by_order[order], config.qlp_precision)?;
532 let mut residual = Vec::with_capacity(signal.len() - order);
533 for i in order..signal.len() {
534 let mut sum = 0i64;
535 for (k, &c) in coefs.iter().enumerate() {
536 sum += i64::from(c) * i64::from(signal[i - 1 - k]);
537 }
538 let r = i64::from(signal[i]) - (sum >> shift);
539 residual.push(i32::try_from(r).ok()?);
540 }
541 let rice = plan_rice(config, &residual, signal.len(), order);
542 Some(SubframePlan {
543 bits: header_bits
544 + order * bps as usize
545 + 4
546 + 5
547 + order * config.qlp_precision as usize
548 + rice.bits,
549 wasted: 0,
550 kind: PlanKind::Lpc {
551 warmup: signal[..order].to_vec(),
552 precision: config.qlp_precision,
553 shift,
554 coefs,
555 residual,
556 rice: rice.plan,
557 },
558 })
559}
560
561struct RiceChoice {
562 bits: usize,
563 plan: RicePlan,
564}
565
566/// Choose the partition order and per-partition Rice parameters.
567///
568/// Parameters come from partition sums with the usual estimate, then the whole
569/// configuration is costed exactly — so orders are compared by real bit counts
570/// rather than by two estimates.
571fn plan_rice(
572 config: &EncoderConfig,
573 residual: &[i32],
574 block_size: usize,
575 order: usize,
576) -> RiceChoice {
577 let folded: Vec<u32> = residual.iter().map(|&r| fold(r)).collect();
578 let mut best: Option<RiceChoice> = None;
579 for partition_order in 0..=config.max_partition_order {
580 let partitions = 1usize << partition_order;
581 if !block_size.is_multiple_of(partitions) {
582 break;
583 }
584 let partition_len = block_size / partitions;
585 if partition_len <= order {
586 break;
587 }
588 let mut params = Vec::with_capacity(partitions);
589 let mut bits = 0usize;
590 let mut at = 0usize;
591 let mut max_param = 0u32;
592 for p in 0..partitions {
593 let count = partition_len - if p == 0 { order } else { 0 };
594 let part = &folded[at..at + count];
595 at += count;
596 let sum: u64 = part.iter().map(|&v| u64::from(v)).sum();
597 let param = best_rice_param(sum, count as u64);
598 bits += part
599 .iter()
600 .map(|&v| (v >> param) as usize + 1 + param as usize)
601 .sum::<usize>();
602 max_param = max_param.max(param);
603 params.push(param);
604 }
605 let param_bits = if max_param > 14 { 5 } else { 4 };
606 bits += 2 + 4 + partitions * param_bits as usize;
607 let choice = RiceChoice {
608 bits,
609 plan: RicePlan {
610 param_bits,
611 partition_order,
612 order,
613 params,
614 },
615 };
616 if best.as_ref().is_none_or(|b| choice.bits < b.bits) {
617 best = Some(choice);
618 }
619 }
620 best.expect("partition order 0 is always legal")
621}
622
623/// Zig-zag fold: FLAC codes residuals as unsigned with the sign in bit 0.
624fn fold(r: i32) -> u32 {
625 ((r << 1) ^ (r >> 31)) as u32
626}
627
628/// The Rice parameter whose quotients cost least for a partition of `count`
629/// folded values summing to `sum`, capped at 30 (31 is the escape code).
630fn best_rice_param(sum: u64, count: u64) -> u32 {
631 if count == 0 {
632 return 0;
633 }
634 let mean = sum / count;
635 let mut param = 0u32;
636 while param < 30 && (1u64 << (param + 1)) <= mean {
637 param += 1;
638 }
639 let cost = |k: u32| count * (1 + u64::from(k)) + (sum >> k);
640 let mut best = param;
641 for k in param.saturating_sub(1)..=(param + 1).min(30) {
642 if cost(k) < cost(best) {
643 best = k;
644 }
645 }
646 best
647}
648
649fn write_subframe(w: &mut BitWriter, plan: &SubframePlan, bps: u32) {
650 let kind_code = match &plan.kind {
651 PlanKind::Constant(_) => 0,
652 PlanKind::Verbatim(_) => 1,
653 PlanKind::Fixed { warmup, .. } => 8 + warmup.len() as u32,
654 PlanKind::Lpc { warmup, .. } => 31 + warmup.len() as u32,
655 };
656 w.write_bit(false);
657 w.write_bits(kind_code, 6);
658 w.write_bit(plan.wasted > 0);
659 if plan.wasted > 0 {
660 // Unary: `wasted - 1` zeroes then a one.
661 for _ in 0..plan.wasted - 1 {
662 w.write_bit(false);
663 }
664 w.write_bit(true);
665 }
666 let bps = bps - plan.wasted;
667 match &plan.kind {
668 PlanKind::Constant(v) => w.write_signed(*v, bps),
669 PlanKind::Verbatim(samples) => {
670 for &s in samples {
671 w.write_signed(s, bps);
672 }
673 }
674 PlanKind::Fixed {
675 warmup,
676 residual,
677 rice,
678 } => {
679 for &s in warmup {
680 w.write_signed(s, bps);
681 }
682 write_residual(w, residual, rice);
683 }
684 PlanKind::Lpc {
685 warmup,
686 precision,
687 shift,
688 coefs,
689 residual,
690 rice,
691 } => {
692 for &s in warmup {
693 w.write_signed(s, bps);
694 }
695 w.write_bits(precision - 1, 4);
696 w.write_bits(*shift, 5);
697 for &c in coefs {
698 w.write_signed(c, *precision);
699 }
700 write_residual(w, residual, rice);
701 }
702 }
703}
704
705fn write_residual(w: &mut BitWriter, residual: &[i32], rice: &RicePlan) {
706 w.write_bits(u32::from(rice.param_bits == 5), 2);
707 w.write_bits(rice.partition_order, 4);
708 let partitions = 1usize << rice.partition_order;
709 let partition_len = (residual.len() + rice.order) / partitions;
710 let mut at = 0usize;
711 for (p, &param) in rice.params.iter().enumerate() {
712 let count = partition_len - if p == 0 { rice.order } else { 0 };
713 w.write_bits(param, rice.param_bits);
714 for &r in &residual[at..at + count] {
715 let folded = fold(r);
716 for _ in 0..folded >> param {
717 w.write_bit(false);
718 }
719 w.write_bit(true);
720 if param > 0 {
721 w.write_bits(folded & ((1 << param) - 1), param);
722 }
723 }
724 at += count;
725 }
726 debug_assert_eq!(at, residual.len());
727}
728
729fn tukey_window(n: usize) -> Vec<f64> {
730 // Tukey(0.5): a Hann taper over the outer quarter at each end, flat between.
731 const P: f64 = 0.5;
732 let taper = (P * (n as f64 - 1.0) / 2.0).max(1.0);
733 (0..n)
734 .map(|i| {
735 let i = i as f64;
736 let last = n as f64 - 1.0;
737 if i < taper {
738 0.5 * (1.0 - (std::f64::consts::PI * i / taper).cos())
739 } else if i > last - taper {
740 0.5 * (1.0 - (std::f64::consts::PI * (last - i) / taper).cos())
741 } else {
742 1.0
743 }
744 })
745 .collect()
746}
747
748fn autocorrelation(signal: &[f64], max_order: usize) -> Vec<f64> {
749 (0..=max_order)
750 .map(|lag| {
751 signal[lag..]
752 .iter()
753 .zip(signal)
754 .map(|(a, b)| a * b)
755 .sum::<f64>()
756 })
757 .collect()
758}
759
760/// Levinson-Durbin: predictor coefficients for every order up to `max_order`,
761/// plus the prediction error each order leaves.
762///
763/// The returned coefficients are in FLAC's sense — `x[n] ~ sum c[k]*x[n-1-k]` —
764/// which is the negation of the recursion's internal ones.
765fn levinson_durbin(autoc: &[f64], max_order: usize) -> (Vec<Vec<f64>>, Vec<f64>) {
766 let mut coefs = vec![Vec::new(); max_order + 1];
767 let mut errors = vec![autoc[0]; max_order + 1];
768 let mut a = vec![0.0f64; max_order];
769 let mut err = autoc[0];
770 for i in 0..max_order {
771 if err <= 0.0 {
772 break;
773 }
774 let mut r = -autoc[i + 1];
775 for j in 0..i {
776 r -= a[j] * autoc[i - j];
777 }
778 r /= err;
779 a[i] = r;
780 for j in 0..i / 2 {
781 let tmp = a[j];
782 a[j] += r * a[i - 1 - j];
783 a[i - 1 - j] += r * tmp;
784 }
785 if i % 2 == 1 {
786 let j = i / 2;
787 a[j] += a[j] * r;
788 }
789 err *= 1.0 - r * r;
790 errors[i + 1] = err;
791 coefs[i + 1] = a[..=i].iter().map(|&v| -v).collect();
792 }
793 (coefs, errors)
794}
795
796/// Quantise predictor coefficients to `precision` bits and a shift, carrying
797/// the rounding error forward.
798fn quantize_coefficients(coefs: &[f64], precision: u32) -> Option<(Vec<i32>, u32)> {
799 const MAX_SHIFT: i32 = 15;
800 let cmax = coefs.iter().fold(0.0f64, |m, c| m.max(c.abs()));
801 if cmax <= 0.0 || !cmax.is_finite() {
802 return None;
803 }
804 let log2cmax = cmax.log2().floor() as i32;
805 let shift = (precision as i32 - 1 - log2cmax - 1).min(MAX_SHIFT);
806 if shift < 0 {
807 return None; // coefficients too large to quantise; fixed predictors win.
808 }
809 let limit = 1i32 << (precision - 1);
810 let scale = f64::from(1i32 << shift);
811 let mut error = 0.0f64;
812 let mut out = Vec::with_capacity(coefs.len());
813 for &c in coefs {
814 error += c * scale;
815 let q = error.round().clamp(f64::from(-limit), f64::from(limit - 1)) as i32;
816 error -= f64::from(q);
817 out.push(q);
818 }
819 Some((out, shift as u32))
820}
821
822#[cfg(test)]
823mod tests {
824 use super::*;
825 use crate::decode::{Block, FlacReader, read_utf8_number};
826 use ec_core::bitio::BitReader;
827
828 fn tone(frames: usize, channels: usize, bps: u32) -> Vec<i32> {
829 let amp = f64::from(1i32 << (bps - 2));
830 (0..frames * channels)
831 .map(|i| {
832 let t = (i / channels) as f64;
833 let c = (i % channels) as f64;
834 (amp * ((t * 0.031 + c * 0.7).sin() + 0.2 * (t * 0.29).sin())) as i32
835 })
836 .collect()
837 }
838
839 fn round_trip(samples: &[i32], channels: usize, bps: u32, rate: u32) {
840 let config = EncoderConfig::default();
841 let bytes = encode(&config, samples, channels, bps, rate).expect("encode");
842 let mut reader = FlacReader::new(&bytes).expect("open");
843 let info = reader.stream_info().expect("streaminfo").clone();
844 assert_eq!(info.sample_rate, rate);
845 assert_eq!(usize::from(info.channels), channels);
846 assert_eq!(u32::from(info.bits_per_sample), bps);
847 assert_eq!(info.total_samples, (samples.len() / channels) as u64);
848 let decoded = reader.decode_all().expect("decode");
849 assert_eq!(
850 decoded.interleaved(),
851 samples,
852 "{channels}ch/{bps}bit/{rate}Hz did not round-trip"
853 );
854 assert_eq!(
855 info.md5,
856 md5_of_samples(&decoded.interleaved(), bps),
857 "STREAMINFO MD5 must match the decoded audio"
858 );
859 }
860
861 #[test]
862 fn round_trips_every_shape_the_family_uses() {
863 for (channels, bps, rate) in [
864 (1usize, 16u32, 44100u32),
865 (2, 16, 44100),
866 (2, 16, 48000),
867 (2, 24, 96000),
868 (6, 16, 48000),
869 (8, 24, 48000),
870 (1, 8, 8000),
871 (2, 20, 192_000),
872 ] {
873 round_trip(&tone(5000, channels, bps), channels, bps, rate);
874 }
875 }
876
877 #[test]
878 fn round_trips_the_awkward_signals() {
879 let config = EncoderConfig::default();
880 let cases: Vec<Vec<i32>> = vec![
881 vec![0; 4096 * 2], // digital silence
882 vec![i32::from(i16::MIN); 100], // constant full scale
883 (0..8192)
884 .map(|i| if i % 64 < 32 { 3000 } else { -3000 })
885 .collect(), // square
886 vec![-1], // one sample
887 (0..4096).map(|i| (i % 7) * 256).collect(), // wasted bits
888 (0..4096)
889 .map(|i| ((i * 2654435761u64 % 65536) as i32) - 32768)
890 .collect(), // noise
891 ];
892 for samples in cases {
893 let bytes = encode(&config, &samples, 1, 16, 44100).expect("encode");
894 let decoded = FlacReader::new(&bytes)
895 .expect("open")
896 .decode_all()
897 .expect("decode");
898 assert_eq!(decoded.interleaved(), samples);
899 }
900 }
901
902 #[test]
903 fn a_short_last_block_still_decodes() {
904 let config = EncoderConfig {
905 block_size: 512,
906 ..EncoderConfig::default()
907 };
908 let samples = tone(1300, 2, 16);
909 let bytes = encode(&config, &samples, 2, 16, 44100).expect("encode");
910 let mut reader = FlacReader::new(&bytes).expect("open");
911 let mut block = Block::default();
912 let mut sizes = Vec::new();
913 while reader.next_block(&mut block).expect("frame") {
914 sizes.push(block.len());
915 }
916 assert_eq!(sizes, vec![512, 512, 276]);
917 }
918
919 #[test]
920 fn refuses_input_it_cannot_encode_losslessly() {
921 let config = EncoderConfig::default();
922 assert!(encode(&config, &[1 << 20], 1, 16, 44100).is_err());
923 assert!(encode(&config, &[1, 2, 3], 2, 16, 44100).is_err());
924 assert!(encode(&config, &[0; 16], 9, 16, 44100).is_err());
925 assert!(encode(&config, &[0; 16], 1, 33, 44100).is_err());
926 assert!(encode(&config, &[0; 16], 1, 16, 0).is_err());
927 }
928
929 #[test]
930 fn utf8_coded_numbers_round_trip() {
931 for value in [
932 0u64,
933 1,
934 0x7f,
935 0x80,
936 0x7ff,
937 0x800,
938 0xffff,
939 0x10_ffff,
940 0x3ff_ffff,
941 0x7fff_ffff,
942 ] {
943 let mut w = BitWriter::new();
944 write_utf8_number(&mut w, value);
945 let bytes = w.into_bytes();
946 let mut r = BitReader::new(&bytes);
947 assert_eq!(
948 read_utf8_number(&mut r, 36).unwrap(),
949 value,
950 "number {value}"
951 );
952 }
953 }
954
955 #[test]
956 fn compresses_better_than_raw_pcm() {
957 let samples = tone(44100, 2, 16);
958 let raw = samples.len() * 2;
959 let bytes = encode(&EncoderConfig::default(), &samples, 2, 16, 44100).unwrap();
960 assert!(
961 bytes.len() < raw / 2,
962 "{} bytes from {raw} of PCM is not compression",
963 bytes.len()
964 );
965 }
966}