forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

encode.rs638 lines, 22.6 KiBHistoryRawDownload
1//! ALAC encoding: the inverse of `decode.rs`'s element walk, adaptive-Golomb
2//! coder and predictor. Every constant and code shape here mirrors that file
3//! deliberately, so a `AlacEncoder::encode_frame` output is exactly what
4//! `AlacDecoder::decode` expects.
5//!
6//! Written from the published ALAC format description, same as `decode.rs`.
7//! Nothing here is derived from the reference encoder sources.
8
9use crate::MagicCookie;
10use ec_core::error::{Error, Result};
11use ec_core::frame::{Frame, SampleFormat};
12use ec_core::packet::Packet;
13use ec_core::registry::{CodecParameters, Encoder};
14
15const QBSHIFT: u32 = 9;
16const QB: u32 = 1 << QBSHIFT;
17const MMULSHIFT: u32 = 2;
18const MDENSHIFT: u32 = QBSHIFT - MMULSHIFT - 1;
19const MOFF: u32 = 1 << (MDENSHIFT - 2);
20const BITOFF: i32 = 24;
21const MAX_PREFIX: u32 = 9;
22const MAX_RUN_BITS: u32 = 16;
23const MEAN_CLAMP: u32 = 0xffff;
24
25const ID_SCE: u32 = 0;
26const ID_CPE: u32 = 1;
27const ID_END: u32 = 7;
28
29/// Filter orders searched for the single-pass (mode 0) predictor, plus 31 —
30/// the format's sentinel for "whole-block first-order difference", which
31/// `decode.rs`'s `predict` special-cases regardless of any coefficients
32/// stored alongside it (`decode.rs:245`).
33const ORDER_CANDIDATES: [usize; 5] = [4, 8, 12, 16, 31];
34const ORDER_DIFF: usize = 31;
35
36/// `floor(log2(x + 3))`, duplicated from `decode.rs` because that module's
37/// helpers are private to it.
38fn lg3a(x: u32) -> u32 {
39 31 - (x + 3).leading_zeros()
40}
41
42fn sign(x: i32) -> i32 {
43 (x > 0) as i32 - (x < 0) as i32
44}
45
46/// A zigzag of a signed residual into decode.rs's `ndecode` space: 0, -1, 1,
47/// -2, 2, ... maps to 0, 1, 2, 3, 4, ...
48fn zigzag(v: i32) -> u32 {
49 let v = i64::from(v);
50 (if v >= 0 { v * 2 } else { -v * 2 - 1 }) as u32
51}
52
53/// Where encoded bits go: a real bit writer, or a running count for the
54/// order/mix search that never touches memory for the bits themselves.
55trait BitSink {
56 fn put(&mut self, value: u32, n: u32);
57}
58
59/// MSB-first bit writer, byte-aligned on [`BitWriter::finish`] — the write
60/// side of `decode.rs`'s `Bits`.
61#[derive(Default)]
62struct BitWriter {
63 bytes: Vec<u8>,
64 cur: u8,
65 nbits: u32,
66}
67
68impl BitWriter {
69 fn align(&mut self) {
70 while self.nbits != 0 {
71 self.put(0, 1);
72 }
73 }
74
75 fn finish(mut self) -> Vec<u8> {
76 self.align();
77 self.bytes
78 }
79}
80
81impl BitSink for BitWriter {
82 fn put(&mut self, value: u32, n: u32) {
83 for i in (0..n).rev() {
84 self.cur = (self.cur << 1) | ((value >> i) & 1) as u8;
85 self.nbits += 1;
86 if self.nbits == 8 {
87 self.bytes.push(self.cur);
88 self.cur = 0;
89 self.nbits = 0;
90 }
91 }
92 }
93}
94
95/// A bit count only, for measuring a candidate before committing to it.
96#[derive(Default)]
97struct CostSink(u64);
98
99impl BitSink for CostSink {
100 fn put(&mut self, _value: u32, n: u32) {
101 self.0 += u64::from(n);
102 }
103}
104
105/// One adaptive-Golomb code, the write side of `decode.rs`'s `golomb`: a
106/// unary quotient of `n / m` (escaping to a raw `maxbits` value past
107/// [`MAX_PREFIX`]) and a truncated-binary remainder in `k` or `k - 1` bits.
108fn golomb_write<S: BitSink>(sink: &mut S, n: u32, m: u32, k: u32, maxbits: u32) {
109 if m == 0 {
110 // `decode.rs`'s reader only reaches this when k <= 1 too, in which
111 // case it never looks at a remainder at all — a mean-derived k this
112 // small essentially never occurs (see `rice_encode`'s zero-run k),
113 // but the fallback here is a plain unary-free raw write rather than
114 // a divide by zero.
115 sink.put(n, maxbits.max(1));
116 return;
117 }
118 debug_assert!(maxbits >= 32 || n >> maxbits == 0, "Golomb value {n} does not fit its {maxbits}-bit escape");
119 let q = n / m;
120 if q >= MAX_PREFIX {
121 sink.put(u32::MAX, MAX_PREFIX);
122 if maxbits > 0 {
123 sink.put(n, maxbits);
124 }
125 return;
126 }
127 if q > 0 {
128 sink.put(u32::MAX, q);
129 }
130 sink.put(0, 1);
131 if k > 1 {
132 let r = n - q * m;
133 match r {
134 0 => sink.put(0, k - 1),
135 r => sink.put(r + 1, k),
136 }
137 }
138}
139
140/// Adaptive-Golomb-encode `res` into `sink`, exactly inverting
141/// `decode.rs`'s `Rice::decode` — same mean update, same zero-run escape.
142fn rice_encode<S: BitSink>(sink: &mut S, cfg: &MagicCookie, pb_factor: u32, res: &[i32], chan_bits: u32) {
143 let kb = u32::from(cfg.kb).clamp(1, 31);
144 let pb = u32::from(cfg.pb) * pb_factor / 4;
145 let wb = (1u32 << kb) - 1;
146 let mut mean = u32::from(cfg.mb);
147 let mut zmode = 0u32;
148 let mut c = 0usize;
149 while c < res.len() {
150 let ndecode = zigzag(res[c]);
151 // Safe: `zmode` is only 1 right after a zero run that consumed every
152 // contiguous zero, so the sample here is never itself zero.
153 let n = ndecode - zmode;
154 let k = lg3a(mean >> QBSHIFT).min(kb);
155 let m = (1u32 << k) - 1;
156 golomb_write(sink, n, m, k, chan_bits);
157 c += 1;
158
159 mean = pb
160 .wrapping_mul(ndecode)
161 .wrapping_add(mean)
162 .wrapping_sub(pb.wrapping_mul(mean) >> QBSHIFT);
163 if n > MEAN_CLAMP {
164 mean = MEAN_CLAMP;
165 }
166
167 zmode = 0;
168 if (mean << MMULSHIFT) < QB && c < res.len() {
169 zmode = 1;
170 let k2 = (mean.leading_zeros() as i32 - BITOFF + ((mean + MOFF) >> MDENSHIFT) as i32)
171 .clamp(0, 31) as u32;
172 let mz = ((1u32 << k2) - 1) & wb;
173 let mut run = 0u32;
174 while (c + run as usize) < res.len() && res[c + run as usize] == 0 {
175 run += 1;
176 if run as usize >= (1 << MAX_RUN_BITS) - 1 {
177 break;
178 }
179 }
180 golomb_write(sink, run, mz, k2, MAX_RUN_BITS);
181 c += run as usize;
182 if run >= (1 << MAX_RUN_BITS) - 1 {
183 zmode = 0;
184 }
185 mean = 0;
186 }
187 }
188}
189
190/// The forward twin of `decode.rs`'s `predict`: given the true samples `y`
191/// (already in their coded width), compute the residuals a from-zero
192/// sign-adapting filter of `order` taps and `den_shift` would need to
193/// reproduce them exactly. The coefficients this implicitly walks through
194/// are never returned — the encoder always states an all-zero starting
195/// filter, so the decoder's own adaptation, run from the same zero start,
196/// retraces this pass exactly.
197///
198/// Every residual is wrapped to `chan_bits` exactly as `decode.rs`'s
199/// `predict` wraps its reconstruction (`clamp`, decode.rs:242): a difference
200/// of two in-range samples can need one bit more than the samples do, the
201/// Golomb escape carries only `chan_bits` of it, and the decoder's add then
202/// wraps the truncated value back to the right sample. Adapting on the
203/// unwrapped residual's sign would diverge from the decoder's walk.
204fn analyze(y: &[i32], order: usize, den_shift: u32, chan_bits: u32) -> Vec<i32> {
205 let n = y.len();
206 let mut res = vec![0i32; n];
207 if n == 0 {
208 return res;
209 }
210 let chan_shift = 32 - chan_bits;
211 let wrap = |v: i32| ((v as u32) << chan_shift) as i32 >> chan_shift;
212 res[0] = y[0];
213 if order == ORDER_DIFF {
214 for j in 1..n {
215 res[j] = wrap(y[j].wrapping_sub(y[j - 1]));
216 }
217 return res;
218 }
219 if order == 0 || order >= n {
220 // Order 0 is decode.rs's "residuals are the samples verbatim"; a
221 // caller never asks for 0 < order >= n (`best_candidate` filters
222 // those out), so this path is only ever reached as the order-0 case.
223 res.copy_from_slice(y);
224 return res;
225 }
226
227 let mut coefs = vec![0i32; order];
228 for j in 1..=order {
229 res[j] = wrap(y[j].wrapping_sub(y[j - 1]));
230 }
231 let den_half = match den_shift {
232 0 => 0,
233 s => 1i32 << (s - 1),
234 };
235 for j in order..n - 1 {
236 let top = y[j - order];
237 let mut sum = 0i32;
238 for (k, &c) in coefs.iter().enumerate() {
239 sum = sum.wrapping_add(c.wrapping_mul(y[j - k].wrapping_sub(top)));
240 }
241 let predicted = top.wrapping_add(sum.wrapping_add(den_half) >> den_shift);
242 let del = wrap(y[j + 1].wrapping_sub(predicted));
243 res[j + 1] = del;
244
245 let mut del0 = del;
246 let sg = sign(del);
247 if sg > 0 {
248 for k in (0..order).rev() {
249 let dd = top.wrapping_sub(y[j - k]);
250 let s = sign(dd);
251 coefs[k] -= s;
252 del0 -= ((order - k) as i32).wrapping_mul(s.wrapping_mul(dd) >> den_shift);
253 if del0 <= 0 {
254 break;
255 }
256 }
257 } else if sg < 0 {
258 for k in (0..order).rev() {
259 let dd = top.wrapping_sub(y[j - k]);
260 let s = sign(dd);
261 coefs[k] += s;
262 del0 -= ((order - k) as i32).wrapping_mul((-s).wrapping_mul(dd) >> den_shift);
263 if del0 >= 0 {
264 break;
265 }
266 }
267 }
268 }
269 res
270}
271
272/// One channel's chosen filter: the mode and order fields to write, the
273/// residuals it produces, and its total cost in bits (16-bit plan header +
274/// coefficients + the Rice-coded residuals), for comparing against every
275/// other choice.
276struct Candidate {
277 mode: u32,
278 order: u32,
279 res: Vec<i32>,
280 bits: u64,
281}
282
283/// Cheapest of [`ORDER_CANDIDATES`] (plus the trivial order-0 "residuals are
284/// the samples" case) for one channel of true samples, each as mode 0 — the
285/// only prediction type real-world decoders accept (decode.rs also undoes
286/// mode 1's extra difference pass, but nothing here emits it).
287fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) -> Candidate {
288 let mut orders: Vec<usize> = vec![0];
289 orders.extend(ORDER_CANDIDATES.iter().copied().filter(|&o| o < y.len()));
290 let mut best: Option<Candidate> = None;
291 for order in orders {
292 let res = analyze(y, order, 9, chan_bits);
293 let mut cost = CostSink::default();
294 rice_encode(&mut cost, cfg, pb_factor, &res, chan_bits);
295 let bits = 16 + (order as u64) * 16 + cost.0;
296
297 if best.as_ref().is_none_or(|b| bits < b.bits) {
298 best = Some(Candidate {
299 mode: 0,
300 order: order as u32,
301 res,
302 bits,
303 });
304 }
305 }
306 best.unwrap_or(Candidate {
307 mode: 0,
308 order: 0,
309 res: y.to_vec(),
310 bits: u64::MAX,
311 })
312}
313
314/// A channel's coded parameters and residuals, ready to write: the plan
315/// header fields plus [`Candidate::res`].
316struct ChannelPlan {
317 mode: u32,
318 order: u32,
319 pb_factor: u32,
320 res: Vec<i32>,
321}
322
323const DEN_SHIFT: u32 = 9;
324const PB_FACTOR: u32 = 4;
325
326fn write_plan<S: BitSink>(sink: &mut S, plan: &ChannelPlan) {
327 sink.put(plan.mode, 4);
328 sink.put(DEN_SHIFT, 4);
329 sink.put(PB_FACTOR, 3);
330 sink.put(plan.order, 5);
331 for _ in 0..plan.order {
332 sink.put(0, 16); // all-zero starting coefficients (see `analyze`).
333 }
334}
335
336/// One SCE (mono) or CPE (stereo) element, choosing per-element between raw
337/// (escape) and compressed, and for a pair, between direct L/R and a
338/// mid/side mix, whichever is smaller.
339fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samples: usize, allow_shift: bool) {
340 w.put(0, 16); // element instance tag + 12 reserved bits.
341 let pair = planes.len() == 2;
342 let channels = planes.len() as u32;
343 let bit_depth = u32::from(cfg.bit_depth);
344 let partial = samples != cfg.frame_length as usize;
345 let raw_bits = u64::from(channels) * u64::from(bit_depth) * samples as u64;
346
347 // A 24-bit stream may additionally split each sample into a compressed
348 // high part and an uncompressed low byte ridden ahead of the residuals
349 // (decode.rs:485-490, :533-538) — bytes_shifted 1 — when that beats
350 // compressing the sample whole. Only 0 and 1 are ever tried: 3 is the
351 // format's escape sentinel (decode.rs:439), and a stream never carries
352 // more than one low byte's worth of headroom worth shifting off.
353 let shift_candidates: &[u32] = if bit_depth == 24 && allow_shift { &[0, 1] } else { &[0] };
354
355 let compressed = (samples >= 2).then(|| {
356 shift_candidates
357 .iter()
358 .map(|&bytes_shifted| {
359 let shift_bits = bytes_shifted * 8;
360 let chan_bits = bit_depth - shift_bits + channels - 1;
361 let low_bits = u64::from(shift_bits) * u64::from(channels) * samples as u64;
362 let shifted: Vec<Vec<i32>> = planes
363 .iter()
364 .map(|p| p.iter().map(|&s| s >> shift_bits).collect())
365 .collect();
366
367 let (mix_bits, mix_res, plans, bits) = if pair {
368 let (l, r) = (&shifted[0], &shifted[1]);
369 let lc = best_candidate(cfg, l, chan_bits, PB_FACTOR);
370 let rc = best_candidate(cfg, r, chan_bits, PB_FACTOR);
371 let lr_bits = lc.bits + rc.bits;
372
373 // mix_bits = 1, mix_res = 1: v = l - r, u = r + (v >> 1).
374 let (mut u, mut v) = (vec![0i32; samples], vec![0i32; samples]);
375 for i in 0..samples {
376 v[i] = l[i] - r[i];
377 u[i] = r[i] + (v[i] >> 1);
378 }
379 let uc = best_candidate(cfg, &u, chan_bits, PB_FACTOR);
380 let vc = best_candidate(cfg, &v, chan_bits, PB_FACTOR);
381 let ms_bits = uc.bits + vc.bits;
382
383 match ms_bits < lr_bits {
384 true => (1u32, 1i32, vec![plan_of(uc), plan_of(vc)], ms_bits),
385 false => (2u32, 0i32, vec![plan_of(lc), plan_of(rc)], lr_bits),
386 }
387 } else {
388 let c0 = best_candidate(cfg, &shifted[0], chan_bits, PB_FACTOR);
389 let bits = c0.bits;
390 (0u32, 0i32, vec![plan_of(c0)], bits)
391 };
392 (bytes_shifted, mix_bits, mix_res, plans, bits + low_bits)
393 })
394 .min_by_key(|&(_, _, _, _, bits)| bits)
395 .unwrap()
396 });
397
398 let use_compressed = compressed
399 .as_ref()
400 .is_some_and(|(_, _, _, _, bits)| 16 + bits < raw_bits.max(1));
401 let bytes_shifted = compressed.as_ref().map_or(0, |&(bs, ..)| bs);
402
403 w.put(partial as u32, 1);
404 w.put(if use_compressed { bytes_shifted } else { 0 }, 2);
405 w.put(!use_compressed as u32, 1);
406 if partial {
407 w.put((samples as u32) >> 16, 16);
408 w.put(samples as u32 & 0xffff, 16);
409 }
410
411 match use_compressed {
412 false => {
413 let chan_bits = bit_depth;
414 for i in 0..samples {
415 for plane in planes {
416 w.put(plane[i] as u32 & mask(chan_bits), chan_bits);
417 }
418 }
419 }
420 true => {
421 let (bytes_shifted, mix_bits, mix_res, plans, _) = compressed.unwrap();
422 let shift_bits = bytes_shifted * 8;
423 w.put(mix_bits, 8);
424 w.put((mix_res as i8) as u8 as u32, 8);
425 for plan in &plans {
426 write_plan(w, plan);
427 }
428 // The low bytes ride ahead of the residuals, one `shift_bits`
429 // field per sample per channel, in the same i-outer/channel-inner
430 // order the escape path above uses — decode.rs reads them back
431 // in exactly that order (decode.rs:533-538).
432 if shift_bits > 0 {
433 for i in 0..samples {
434 for plane in planes {
435 w.put(plane[i] as u32 & mask(shift_bits), shift_bits);
436 }
437 }
438 }
439 let chan_bits = bit_depth - shift_bits + channels - 1;
440 for plan in &plans {
441 rice_encode(w, cfg, plan.pb_factor, &plan.res, chan_bits);
442 }
443 }
444 }
445}
446
447fn plan_of(c: Candidate) -> ChannelPlan {
448 ChannelPlan {
449 mode: c.mode,
450 order: c.order,
451 pb_factor: PB_FACTOR,
452 res: c.res,
453 }
454}
455
456/// `n` low bits set, for masking a two's-complement value into an escape's
457/// raw field.
458fn mask(n: u32) -> u32 {
459 match n {
460 32 => u32::MAX,
461 n => (1 << n) - 1,
462 }
463}
464
465/// An ALAC encoder for one mono or stereo stream.
466#[derive(Debug)]
467pub struct AlacEncoder {
468 cookie: MagicCookie,
469 params: CodecParameters,
470 channels: usize,
471 pending: Vec<i32>,
472 packets: std::collections::VecDeque<Vec<u8>>,
473 eof: bool,
474 allow_shift: bool,
475}
476
477impl AlacEncoder {
478 /// An encoder for a mono or stereo stream. `bit_depth` is 16 or 24;
479 /// `frame_length` is the samples-per-channel every full frame carries
480 /// (the reference own encoder writes 4096).
481 pub fn new(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32) -> Result<AlacEncoder> {
482 if !matches!(bit_depth, 16 | 24) {
483 return Err(Error::unsupported(
484 format!("ALAC encoding {bit_depth}-bit samples"),
485 "this encoder writes 16 and 24 bit only",
486 ));
487 }
488 if !(1..=2).contains(&channels) {
489 return Err(Error::unsupported(
490 format!("ALAC encoding {channels} channels"),
491 "this encoder writes mono and stereo only",
492 ));
493 }
494 if !(1..=1 << 20).contains(&frame_length) {
495 return Err(Error::unsupported(
496 format!("ALAC frame length {frame_length}"),
497 "frame length must be 1..=1048576",
498 ));
499 }
500 if sample_rate == 0 {
501 return Err(Error::unsupported("ALAC at 0 Hz", "sample rate must be non-zero"));
502 }
503 let cookie = MagicCookie {
504 frame_length,
505 compatible_version: 0,
506 bit_depth,
507 pb: 40,
508 mb: 10,
509 kb: 14,
510 channels,
511 max_run: 255,
512 max_frame_bytes: 0,
513 avg_bit_rate: 0,
514 sample_rate,
515 };
516 let mut params = crate::codec_parameters(&cookie);
517 params.extradata = Some(cookie.extradata_box().into());
518 Ok(AlacEncoder {
519 cookie,
520 params,
521 channels: channels as usize,
522 pending: Vec::new(),
523 packets: std::collections::VecDeque::new(),
524 eof: false,
525 allow_shift: true,
526 })
527 }
528
529 /// Test-only: force bytes_shifted 0 even at 24 bits, so a test can
530 /// measure both paths against the same source. Both outputs decode the
531 /// same; this only trades size.
532 #[doc(hidden)]
533 pub fn set_byte_shift(&mut self, allow: bool) {
534 self.allow_shift = allow;
535 }
536
537 /// What this encoder states about the stream it writes.
538 pub fn cookie(&self) -> &MagicCookie {
539 &self.cookie
540 }
541
542 /// Encode one frame: `samples` interleaved, true PCM range (not the
543 /// container-shifted range [`AlacDecoder::decode`] hands back), up to
544 /// `frame_length` samples per channel — a shorter slice writes a partial
545 /// frame, exactly as a stream's last frame does.
546 pub fn encode_frame(&self, samples: &[i32]) -> Vec<u8> {
547 let channels = self.channels;
548 let n = samples.len() / channels;
549 let mut planes: Vec<Vec<i32>> = vec![Vec::with_capacity(n); channels];
550 for chunk in samples.chunks_exact(channels) {
551 for (c, plane) in planes.iter_mut().enumerate() {
552 plane.push(chunk[c]);
553 }
554 }
555 let mut w = BitWriter::default();
556 w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3);
557 write_element(&self.cookie, &mut w, &planes, n, self.allow_shift);
558 w.put(ID_END, 3);
559 w.finish()
560 }
561}
562
563impl Encoder for AlacEncoder {
564 fn codec_parameters(&self) -> &CodecParameters {
565 &self.params
566 }
567
568 fn send_frame(&mut self, frame: &Frame) -> Result<()> {
569 let Frame::Audio(audio) = frame else {
570 return Err(Error::corrupt("video frame pushed into an ALAC encoder"));
571 };
572 let channels = self.channels;
573 let shift = self.cookie.container_shift();
574 let want = self.cookie.sample_format();
575 if audio.format != want {
576 return Err(Error::unsupported(
577 format!("{:?} input", audio.format),
578 "this encoder takes samples in the cookie's own sample format",
579 ));
580 }
581 let mut interleaved = Vec::with_capacity(audio.samples * channels);
582 match (audio.planar, want) {
583 (false, SampleFormat::S16) => {
584 for pair in audio.data[0].as_chunks::<2>().0.iter().take(audio.samples * channels) {
585 interleaved.push(i32::from(i16::from_ne_bytes([pair[0], pair[1]])) >> shift);
586 }
587 }
588 (false, _) => {
589 for word in audio.data[0].as_chunks::<4>().0.iter().take(audio.samples * channels) {
590 interleaved.push(i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> shift);
591 }
592 }
593 (true, SampleFormat::S16) => {
594 for i in 0..audio.samples {
595 for plane in audio.data.iter().take(channels) {
596 let at = i * 2;
597 interleaved.push(i32::from(i16::from_ne_bytes([plane[at], plane[at + 1]])) >> shift);
598 }
599 }
600 }
601 (true, _) => {
602 for i in 0..audio.samples {
603 for plane in audio.data.iter().take(channels) {
604 let at = i * 4;
605 let w = [plane[at], plane[at + 1], plane[at + 2], plane[at + 3]];
606 interleaved.push(i32::from_ne_bytes(w) >> shift);
607 }
608 }
609 }
610 }
611 self.pending.extend(interleaved);
612 let per_frame = self.cookie.frame_length as usize * channels;
613 let rest = self.pending.split_off(self.pending.len() / per_frame * per_frame);
614 let full = std::mem::replace(&mut self.pending, rest);
615 for frame in full.chunks_exact(per_frame) {
616 let packet = self.encode_frame(frame);
617 self.packets.push_back(packet);
618 }
619 Ok(())
620 }
621
622 fn receive_packet(&mut self) -> Result<Packet> {
623 match self.packets.pop_front() {
624 Some(data) => Ok(Packet::new(0, ec_core::timebase::TimeBase::new(1, i64::from(self.cookie.sample_rate)), data)),
625 None if self.eof => Err(Error::Eof),
626 None => Err(Error::NeedMore),
627 }
628 }
629
630 fn flush(&mut self) -> Result<()> {
631 if !self.pending.is_empty() {
632 let frame = std::mem::take(&mut self.pending);
633 self.packets.push_back(self.encode_frame(&frame));
634 }
635 self.eof = true;
636 Ok(())
637 }
638}