forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.2 MiBe18142dTahinli5 hours ago4543 commits

encode.rs980 lines, 31.4 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::{ChannelAssignment, 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 = ChannelAssignment::Independent(channels as u8);
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, ChannelAssignment::Independent(2)),
234 (l + side.bits, ChannelAssignment::LeftSide),
235 (side.bits + r, ChannelAssignment::RightSide),
236 (mid.bits + side.bits, ChannelAssignment::MidSide),
237 ]
238 .into_iter()
239 .min_by_key(|candidate| candidate.0)
240 .expect("four candidates");
241 assignment = best;
242 match best {
243 ChannelAssignment::LeftSide => plans[1] = side,
244 ChannelAssignment::RightSide => plans[0] = side,
245 ChannelAssignment::MidSide => {
246 plans[0] = mid;
247 plans[1] = side;
248 }
249 ChannelAssignment::Independent(_) => {}
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!(
267 (assignment, c),
268 (ChannelAssignment::LeftSide, 1)
269 | (ChannelAssignment::MidSide, 1)
270 | (ChannelAssignment::RightSide, 0)
271 );
272 write_subframe(&mut w, plan, bits_per_sample + u32::from(side));
273 }
274 w.align_to_byte();
275 let crc = crc16(w.as_bytes());
276 w.write_bits(u32::from(crc), 16);
277 w.into_bytes()
278}
279
280fn assignment_code(assignment: ChannelAssignment) -> u32 {
281 match assignment {
282 ChannelAssignment::Independent(n) => u32::from(n) - 1,
283 ChannelAssignment::LeftSide => 8,
284 ChannelAssignment::RightSide => 9,
285 ChannelAssignment::MidSide => 10,
286 }
287}
288
289fn write_frame_header(
290 w: &mut BitWriter,
291 block_size: usize,
292 sample_rate: u32,
293 assignment: ChannelAssignment,
294 bits_per_sample: u32,
295 number: u64,
296) {
297 let (bs_code, bs_extra) = match block_size {
298 192 => (1, None),
299 576 => (2, None),
300 1152 => (3, None),
301 2304 => (4, None),
302 4608 => (5, None),
303 256 => (8, None),
304 512 => (9, None),
305 1024 => (10, None),
306 2048 => (11, None),
307 4096 => (12, None),
308 8192 => (13, None),
309 16384 => (14, None),
310 32768 => (15, None),
311 n if n <= 256 => (6, Some((n as u32 - 1, 8))),
312 n => (7, Some((n as u32 - 1, 16))),
313 };
314 let (sr_code, sr_extra) = match sample_rate {
315 88200 => (1, None),
316 176_400 => (2, None),
317 192_000 => (3, None),
318 8000 => (4, None),
319 16000 => (5, None),
320 22050 => (6, None),
321 24000 => (7, None),
322 32000 => (8, None),
323 44100 => (9, None),
324 48000 => (10, None),
325 96000 => (11, None),
326 n if n.is_multiple_of(1000) && n / 1000 <= 255 => (12, Some((n / 1000, 8))),
327 n if n <= 65535 => (13, Some((n, 16))),
328 n if n.is_multiple_of(10) && n / 10 <= 65535 => (14, Some((n / 10, 16))),
329 // Every rate `encode` accepts is covered above; code 0 (take the rate
330 // from STREAMINFO) is the honest fallback rather than a panic.
331 _ => (0, None),
332 };
333 let bps_code = match bits_per_sample {
334 8 => 1,
335 12 => 2,
336 16 => 4,
337 20 => 5,
338 24 => 6,
339 32 => 7,
340 _ => 0,
341 };
342 w.write_bits(0x3ffe, 14);
343 w.write_bit(false); // reserved
344 w.write_bit(false); // fixed block size: the coded number is a frame number
345 w.write_bits(bs_code, 4);
346 w.write_bits(sr_code, 4);
347 w.write_bits(assignment_code(assignment), 4);
348 w.write_bits(bps_code, 3);
349 w.write_bit(false); // reserved
350 write_utf8_number(w, number);
351 if let Some((value, bits)) = bs_extra {
352 w.write_bits(value, bits);
353 }
354 if let Some((value, bits)) = sr_extra {
355 w.write_bits(value, bits);
356 }
357}
358
359/// The UTF-8-shaped coded number of a frame header (up to 36 bits, so wider
360/// than real UTF-8 ever goes).
361fn write_utf8_number(w: &mut BitWriter, value: u64) {
362 if value < 0x80 {
363 w.write_bits(value as u32, 8);
364 return;
365 }
366 // `extra` continuation bytes carry 6 bits each; the lead byte carries
367 // `6 - extra` after its prefix of `extra + 1` ones and a zero.
368 let mut extra = 1usize;
369 while extra < 6 && value >= 1u64 << (6 * extra + (6 - extra)) {
370 extra += 1;
371 }
372 let lead_bits = 6 - extra as u32;
373 let prefix = (0xffu32 << (7 - extra)) & 0xff;
374 let lead = prefix | ((value >> (6 * extra)) as u32 & ((1 << lead_bits) - 1));
375 w.write_bits(lead, 8);
376 for i in (0..extra).rev() {
377 w.write_bits(0x80 | ((value >> (6 * i)) as u32 & 0x3f), 8);
378 }
379}
380
381/// What a subframe will be written as, with its exact cost in bits.
382#[derive(Debug, Clone)]
383struct SubframePlan {
384 bits: usize,
385 wasted: u32,
386 kind: PlanKind,
387}
388
389#[derive(Debug, Clone)]
390enum PlanKind {
391 Constant(i32),
392 Verbatim(Vec<i32>),
393 Fixed {
394 warmup: Vec<i32>,
395 residual: Vec<i32>,
396 rice: RicePlan,
397 },
398 Lpc {
399 warmup: Vec<i32>,
400 precision: u32,
401 shift: u32,
402 coefs: Vec<i32>,
403 residual: Vec<i32>,
404 rice: RicePlan,
405 },
406}
407
408#[derive(Debug, Clone, Default)]
409struct RicePlan {
410 /// 4 or 5: the width of a partition's Rice parameter field.
411 param_bits: u32,
412 partition_order: u32,
413 /// Predictor order, which is what makes partition 0 shorter than the rest.
414 order: usize,
415 params: Vec<u32>,
416}
417
418fn plan_subframe(config: &EncoderConfig, signal: &[i32], bps: u32, window: &[f64]) -> SubframePlan {
419 // Wasted bits: when every sample shares trailing zeros, state them once in
420 // the subframe header instead of once per sample.
421 let any_set = signal.iter().fold(0u32, |acc, &s| acc | s as u32);
422 let wasted = match any_set {
423 0 => 0,
424 n => n.trailing_zeros().min(bps - 1),
425 };
426 let shifted: Vec<i32>;
427 let signal = match wasted {
428 0 => signal,
429 n => {
430 shifted = signal.iter().map(|&s| s >> n).collect();
431 &shifted
432 }
433 };
434 let bps = bps - wasted;
435 let header_bits = 8 + wasted as usize;
436
437 if signal.is_empty() {
438 return SubframePlan {
439 bits: header_bits + bps as usize,
440 wasted,
441 kind: PlanKind::Constant(0),
442 };
443 }
444 if signal.iter().all(|&s| s == signal[0]) {
445 return SubframePlan {
446 bits: header_bits + bps as usize,
447 wasted,
448 kind: PlanKind::Constant(signal[0]),
449 };
450 }
451
452 let mut best = SubframePlan {
453 bits: header_bits + signal.len() * bps as usize,
454 wasted,
455 kind: PlanKind::Verbatim(signal.to_vec()),
456 };
457 if let Some(plan) = plan_fixed(config, signal, bps, header_bits)
458 && plan.bits < best.bits
459 {
460 best = SubframePlan { wasted, ..plan };
461 }
462 if config.max_lpc_order > 0
463 && signal.len() > config.max_lpc_order
464 && window.len() == signal.len()
465 && let Some(plan) = plan_lpc(config, signal, bps, header_bits, window)
466 && plan.bits < best.bits
467 {
468 best = SubframePlan { wasted, ..plan };
469 }
470 best
471}
472
473/// The five fixed predictors, the order chosen by the sum of absolute
474/// residuals — the standard estimate; the Rice search then costs it exactly.
475fn plan_fixed(
476 config: &EncoderConfig,
477 signal: &[i32],
478 bps: u32,
479 header_bits: usize,
480) -> Option<SubframePlan> {
481 let max_order = 4.min(signal.len().saturating_sub(1));
482 let mut diffs: Vec<Vec<i64>> = Vec::with_capacity(max_order + 1);
483 diffs.push(signal.iter().map(|&s| i64::from(s)).collect());
484 for order in 1..=max_order {
485 diffs.push(diffs[order - 1].windows(2).map(|w| w[1] - w[0]).collect());
486 }
487 // Compare orders over the same samples, so the estimate is not biased by a
488 // higher order simply covering fewer of them.
489 let order = (0..=max_order).min_by_key(|&o| {
490 let tail: u64 = diffs[o][max_order - o..]
491 .iter()
492 .map(|&d| d.unsigned_abs())
493 .sum();
494 tail + (o as u64) * u64::from(bps)
495 })?;
496 let residual: Vec<i32> = diffs[order]
497 .iter()
498 .map(|&d| i32::try_from(d))
499 .collect::<std::result::Result<_, _>>()
500 .ok()?; // 32-bit input can overflow the residual; verbatim wins then.
501 let rice = plan_rice(config, &residual, signal.len(), order);
502 Some(SubframePlan {
503 bits: header_bits + order * bps as usize + rice.bits,
504 wasted: 0,
505 kind: PlanKind::Fixed {
506 warmup: signal[..order].to_vec(),
507 residual,
508 rice: rice.plan,
509 },
510 })
511}
512
513fn plan_lpc(
514 config: &EncoderConfig,
515 signal: &[i32],
516 bps: u32,
517 header_bits: usize,
518 window: &[f64],
519) -> Option<SubframePlan> {
520 let max_order = config.max_lpc_order.min(signal.len() - 1).min(32);
521 if max_order == 0 {
522 return None;
523 }
524 let windowed: Vec<f64> = window
525 .iter()
526 .zip(signal)
527 .map(|(w, &s)| w * f64::from(s))
528 .collect();
529 let autoc = autocorrelation(&windowed, max_order);
530 if autoc[0] == 0.0 {
531 return None;
532 }
533 let (coefs_by_order, errors) = levinson_durbin(&autoc, max_order);
534
535 // Order choice by the usual estimate: every order costs its coefficients
536 // and saves half a bit per sample per halving of the prediction error.
537 let n = signal.len() as f64;
538 let cost = |o: usize| {
539 n / 2.0 * errors[o].max(1e-9).log2() + (o as f64) * f64::from(config.qlp_precision)
540 };
541 let order = (1..=max_order)
542 .filter(|&o| !coefs_by_order[o].is_empty())
543 .min_by(|&a, &b| cost(a).total_cmp(&cost(b)))?;
544
545 let (coefs, shift) = quantize_coefficients(&coefs_by_order[order], config.qlp_precision)?;
546 let mut residual = Vec::with_capacity(signal.len() - order);
547 for i in order..signal.len() {
548 let mut sum = 0i64;
549 for (k, &c) in coefs.iter().enumerate() {
550 sum += i64::from(c) * i64::from(signal[i - 1 - k]);
551 }
552 let r = i64::from(signal[i]) - (sum >> shift);
553 residual.push(i32::try_from(r).ok()?);
554 }
555 let rice = plan_rice(config, &residual, signal.len(), order);
556 Some(SubframePlan {
557 bits: header_bits
558 + order * bps as usize
559 + 4
560 + 5
561 + order * config.qlp_precision as usize
562 + rice.bits,
563 wasted: 0,
564 kind: PlanKind::Lpc {
565 warmup: signal[..order].to_vec(),
566 precision: config.qlp_precision,
567 shift,
568 coefs,
569 residual,
570 rice: rice.plan,
571 },
572 })
573}
574
575struct RiceChoice {
576 bits: usize,
577 plan: RicePlan,
578}
579
580/// Choose the partition order and per-partition Rice parameters.
581///
582/// Parameters come from partition sums with the usual estimate, then the whole
583/// configuration is costed exactly — so orders are compared by real bit counts
584/// rather than by two estimates.
585fn plan_rice(
586 config: &EncoderConfig,
587 residual: &[i32],
588 block_size: usize,
589 order: usize,
590) -> RiceChoice {
591 let folded: Vec<u32> = residual.iter().map(|&r| fold(r)).collect();
592 let mut best: Option<RiceChoice> = None;
593 for partition_order in 0..=config.max_partition_order {
594 let partitions = 1usize << partition_order;
595 if !block_size.is_multiple_of(partitions) {
596 break;
597 }
598 let partition_len = block_size / partitions;
599 if partition_len <= order {
600 break;
601 }
602 let mut params = Vec::with_capacity(partitions);
603 let mut bits = 0usize;
604 let mut at = 0usize;
605 let mut max_param = 0u32;
606 for p in 0..partitions {
607 let count = partition_len - if p == 0 { order } else { 0 };
608 let part = &folded[at..at + count];
609 at += count;
610 let sum: u64 = part.iter().map(|&v| u64::from(v)).sum();
611 let param = best_rice_param(sum, count as u64);
612 bits += part
613 .iter()
614 .map(|&v| (v >> param) as usize + 1 + param as usize)
615 .sum::<usize>();
616 max_param = max_param.max(param);
617 params.push(param);
618 }
619 let param_bits = if max_param > 14 { 5 } else { 4 };
620 bits += 2 + 4 + partitions * param_bits as usize;
621 let choice = RiceChoice {
622 bits,
623 plan: RicePlan {
624 param_bits,
625 partition_order,
626 order,
627 params,
628 },
629 };
630 if best.as_ref().is_none_or(|b| choice.bits < b.bits) {
631 best = Some(choice);
632 }
633 }
634 best.expect("partition order 0 is always legal")
635}
636
637/// Zig-zag fold: FLAC codes residuals as unsigned with the sign in bit 0.
638fn fold(r: i32) -> u32 {
639 ((r << 1) ^ (r >> 31)) as u32
640}
641
642/// The Rice parameter whose quotients cost least for a partition of `count`
643/// folded values summing to `sum`, capped at 30 (31 is the escape code).
644fn best_rice_param(sum: u64, count: u64) -> u32 {
645 if count == 0 {
646 return 0;
647 }
648 let mean = sum / count;
649 let mut param = 0u32;
650 while param < 30 && (1u64 << (param + 1)) <= mean {
651 param += 1;
652 }
653 let cost = |k: u32| count * (1 + u64::from(k)) + (sum >> k);
654 let mut best = param;
655 for k in param.saturating_sub(1)..=(param + 1).min(30) {
656 if cost(k) < cost(best) {
657 best = k;
658 }
659 }
660 best
661}
662
663fn write_subframe(w: &mut BitWriter, plan: &SubframePlan, bps: u32) {
664 let kind_code = match &plan.kind {
665 PlanKind::Constant(_) => 0,
666 PlanKind::Verbatim(_) => 1,
667 PlanKind::Fixed { warmup, .. } => 8 + warmup.len() as u32,
668 PlanKind::Lpc { warmup, .. } => 31 + warmup.len() as u32,
669 };
670 w.write_bit(false);
671 w.write_bits(kind_code, 6);
672 w.write_bit(plan.wasted > 0);
673 if plan.wasted > 0 {
674 // Unary: `wasted - 1` zeroes then a one.
675 for _ in 0..plan.wasted - 1 {
676 w.write_bit(false);
677 }
678 w.write_bit(true);
679 }
680 let bps = bps - plan.wasted;
681 match &plan.kind {
682 PlanKind::Constant(v) => w.write_signed(*v, bps),
683 PlanKind::Verbatim(samples) => {
684 for &s in samples {
685 w.write_signed(s, bps);
686 }
687 }
688 PlanKind::Fixed {
689 warmup,
690 residual,
691 rice,
692 } => {
693 for &s in warmup {
694 w.write_signed(s, bps);
695 }
696 write_residual(w, residual, rice);
697 }
698 PlanKind::Lpc {
699 warmup,
700 precision,
701 shift,
702 coefs,
703 residual,
704 rice,
705 } => {
706 for &s in warmup {
707 w.write_signed(s, bps);
708 }
709 w.write_bits(precision - 1, 4);
710 w.write_bits(*shift, 5);
711 for &c in coefs {
712 w.write_signed(c, *precision);
713 }
714 write_residual(w, residual, rice);
715 }
716 }
717}
718
719fn write_residual(w: &mut BitWriter, residual: &[i32], rice: &RicePlan) {
720 w.write_bits(u32::from(rice.param_bits == 5), 2);
721 w.write_bits(rice.partition_order, 4);
722 let partitions = 1usize << rice.partition_order;
723 let partition_len = (residual.len() + rice.order) / partitions;
724 let mut at = 0usize;
725 for (p, &param) in rice.params.iter().enumerate() {
726 let count = partition_len - if p == 0 { rice.order } else { 0 };
727 w.write_bits(param, rice.param_bits);
728 for &r in &residual[at..at + count] {
729 let folded = fold(r);
730 for _ in 0..folded >> param {
731 w.write_bit(false);
732 }
733 w.write_bit(true);
734 if param > 0 {
735 w.write_bits(folded & ((1 << param) - 1), param);
736 }
737 }
738 at += count;
739 }
740 debug_assert_eq!(at, residual.len());
741}
742
743fn tukey_window(n: usize) -> Vec<f64> {
744 // Tukey(0.5): a Hann taper over the outer quarter at each end, flat between.
745 const P: f64 = 0.5;
746 let taper = (P * (n as f64 - 1.0) / 2.0).max(1.0);
747 (0..n)
748 .map(|i| {
749 let i = i as f64;
750 let last = n as f64 - 1.0;
751 if i < taper {
752 0.5 * (1.0 - (std::f64::consts::PI * i / taper).cos())
753 } else if i > last - taper {
754 0.5 * (1.0 - (std::f64::consts::PI * (last - i) / taper).cos())
755 } else {
756 1.0
757 }
758 })
759 .collect()
760}
761
762fn autocorrelation(signal: &[f64], max_order: usize) -> Vec<f64> {
763 (0..=max_order)
764 .map(|lag| {
765 signal[lag..]
766 .iter()
767 .zip(signal)
768 .map(|(a, b)| a * b)
769 .sum::<f64>()
770 })
771 .collect()
772}
773
774/// Levinson-Durbin: predictor coefficients for every order up to `max_order`,
775/// plus the prediction error each order leaves.
776///
777/// The returned coefficients are in FLAC's sense — `x[n] ~ sum c[k]*x[n-1-k]` —
778/// which is the negation of the recursion's internal ones.
779fn levinson_durbin(autoc: &[f64], max_order: usize) -> (Vec<Vec<f64>>, Vec<f64>) {
780 let mut coefs = vec![Vec::new(); max_order + 1];
781 let mut errors = vec![autoc[0]; max_order + 1];
782 let mut a = vec![0.0f64; max_order];
783 let mut err = autoc[0];
784 for i in 0..max_order {
785 if err <= 0.0 {
786 break;
787 }
788 let mut r = -autoc[i + 1];
789 for j in 0..i {
790 r -= a[j] * autoc[i - j];
791 }
792 r /= err;
793 a[i] = r;
794 for j in 0..i / 2 {
795 let tmp = a[j];
796 a[j] += r * a[i - 1 - j];
797 a[i - 1 - j] += r * tmp;
798 }
799 if i % 2 == 1 {
800 let j = i / 2;
801 a[j] += a[j] * r;
802 }
803 err *= 1.0 - r * r;
804 errors[i + 1] = err;
805 coefs[i + 1] = a[..=i].iter().map(|&v| -v).collect();
806 }
807 (coefs, errors)
808}
809
810/// Quantise predictor coefficients to `precision` bits and a shift, carrying
811/// the rounding error forward.
812fn quantize_coefficients(coefs: &[f64], precision: u32) -> Option<(Vec<i32>, u32)> {
813 const MAX_SHIFT: i32 = 15;
814 let cmax = coefs.iter().fold(0.0f64, |m, c| m.max(c.abs()));
815 if cmax <= 0.0 || !cmax.is_finite() {
816 return None;
817 }
818 let log2cmax = cmax.log2().floor() as i32;
819 let shift = (precision as i32 - 1 - log2cmax - 1).min(MAX_SHIFT);
820 if shift < 0 {
821 return None; // coefficients too large to quantise; fixed predictors win.
822 }
823 let limit = 1i32 << (precision - 1);
824 let scale = f64::from(1i32 << shift);
825 let mut error = 0.0f64;
826 let mut out = Vec::with_capacity(coefs.len());
827 for &c in coefs {
828 error += c * scale;
829 let q = error.round().clamp(f64::from(-limit), f64::from(limit - 1)) as i32;
830 error -= f64::from(q);
831 out.push(q);
832 }
833 Some((out, shift as u32))
834}
835
836#[cfg(test)]
837mod tests {
838 use super::*;
839 use crate::decode::{Block, FlacReader, read_utf8_number};
840 use ec_core::bitio::BitReader;
841
842 fn tone(frames: usize, channels: usize, bps: u32) -> Vec<i32> {
843 let amp = f64::from(1i32 << (bps - 2));
844 (0..frames * channels)
845 .map(|i| {
846 let t = (i / channels) as f64;
847 let c = (i % channels) as f64;
848 (amp * ((t * 0.031 + c * 0.7).sin() + 0.2 * (t * 0.29).sin())) as i32
849 })
850 .collect()
851 }
852
853 fn round_trip(samples: &[i32], channels: usize, bps: u32, rate: u32) {
854 let config = EncoderConfig::default();
855 let bytes = encode(&config, samples, channels, bps, rate).expect("encode");
856 let mut reader = FlacReader::new(&bytes).expect("open");
857 let info = reader.stream_info().expect("streaminfo").clone();
858 assert_eq!(info.sample_rate, rate);
859 assert_eq!(usize::from(info.channels), channels);
860 assert_eq!(u32::from(info.bits_per_sample), bps);
861 assert_eq!(info.total_samples, (samples.len() / channels) as u64);
862 let decoded = reader.decode_all().expect("decode");
863 assert_eq!(
864 decoded.interleaved(),
865 samples,
866 "{channels}ch/{bps}bit/{rate}Hz did not round-trip"
867 );
868 assert_eq!(
869 info.md5,
870 md5_of_samples(&decoded.interleaved(), bps),
871 "STREAMINFO MD5 must match the decoded audio"
872 );
873 }
874
875 #[test]
876 fn round_trips_every_shape_the_family_uses() {
877 for (channels, bps, rate) in [
878 (1usize, 16u32, 44100u32),
879 (2, 16, 44100),
880 (2, 16, 48000),
881 (2, 24, 96000),
882 (6, 16, 48000),
883 (8, 24, 48000),
884 (1, 8, 8000),
885 (2, 20, 192_000),
886 ] {
887 round_trip(&tone(5000, channels, bps), channels, bps, rate);
888 }
889 }
890
891 #[test]
892 fn round_trips_the_awkward_signals() {
893 let config = EncoderConfig::default();
894 let cases: Vec<Vec<i32>> = vec![
895 vec![0; 4096 * 2], // digital silence
896 vec![i32::from(i16::MIN); 100], // constant full scale
897 (0..8192)
898 .map(|i| if i % 64 < 32 { 3000 } else { -3000 })
899 .collect(), // square
900 vec![-1], // one sample
901 (0..4096).map(|i| (i % 7) * 256).collect(), // wasted bits
902 (0..4096)
903 .map(|i| ((i * 2654435761u64 % 65536) as i32) - 32768)
904 .collect(), // noise
905 ];
906 for samples in cases {
907 let bytes = encode(&config, &samples, 1, 16, 44100).expect("encode");
908 let decoded = FlacReader::new(&bytes)
909 .expect("open")
910 .decode_all()
911 .expect("decode");
912 assert_eq!(decoded.interleaved(), samples);
913 }
914 }
915
916 #[test]
917 fn a_short_last_block_still_decodes() {
918 let config = EncoderConfig {
919 block_size: 512,
920 ..EncoderConfig::default()
921 };
922 let samples = tone(1300, 2, 16);
923 let bytes = encode(&config, &samples, 2, 16, 44100).expect("encode");
924 let mut reader = FlacReader::new(&bytes).expect("open");
925 let mut block = Block::default();
926 let mut sizes = Vec::new();
927 while reader.next_block(&mut block).expect("frame") {
928 sizes.push(block.len());
929 }
930 assert_eq!(sizes, vec![512, 512, 276]);
931 }
932
933 #[test]
934 fn refuses_input_it_cannot_encode_losslessly() {
935 let config = EncoderConfig::default();
936 assert!(encode(&config, &[1 << 20], 1, 16, 44100).is_err());
937 assert!(encode(&config, &[1, 2, 3], 2, 16, 44100).is_err());
938 assert!(encode(&config, &[0; 16], 9, 16, 44100).is_err());
939 assert!(encode(&config, &[0; 16], 1, 33, 44100).is_err());
940 assert!(encode(&config, &[0; 16], 1, 16, 0).is_err());
941 }
942
943 #[test]
944 fn utf8_coded_numbers_round_trip() {
945 for value in [
946 0u64,
947 1,
948 0x7f,
949 0x80,
950 0x7ff,
951 0x800,
952 0xffff,
953 0x10_ffff,
954 0x3ff_ffff,
955 0x7fff_ffff,
956 ] {
957 let mut w = BitWriter::new();
958 write_utf8_number(&mut w, value);
959 let bytes = w.into_bytes();
960 let mut r = BitReader::new(&bytes);
961 assert_eq!(
962 read_utf8_number(&mut r, 36).unwrap(),
963 value,
964 "number {value}"
965 );
966 }
967 }
968
969 #[test]
970 fn compresses_better_than_raw_pcm() {
971 let samples = tone(44100, 2, 16);
972 let raw = samples.len() * 2;
973 let bytes = encode(&EncoderConfig::default(), &samples, 2, 16, 44100).unwrap();
974 assert!(
975 bytes.len() < raw / 2,
976 "{} bytes from {raw} of PCM is not compression",
977 bytes.len()
978 );
979 }
980}