forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

trim.rs136 lines, 5.1 KiBHistoryRawDownload
1//! Granule trimming: where an Ogg Vorbis stream starts and ends, in samples.
2//!
3//! A Vorbis block always decodes a whole window of samples, so the last packet
4//! of a stream routinely reaches past the end the container states. Ogg says
5//! where that end is: the granule position of the last page, which
6//! `ec-ogg` attaches to the packet that finishes on it. Vorbis I (Annex A.2)
7//! makes that granule the stream's exact length.
8//!
9//! The decoder counts its own samples from zero. A granule is an absolute
10//! position, so the two are tied by an *offset* (`granule - decoded`), taken
11//! from the first granule that arrives before any sample has been produced.
12//! A stream that begins at position zero has offset zero and no front trim;
13//! one that begins later, or whose first granule is ahead of its decoded
14//! count, gets its head dropped. Later granules only move the end.
15//!
16//! Samples past the latest granule are not released: a later page may still
17//! extend the stream, and the flush at end of stream cuts the rest.
18
19use ec_core::{Packet, SideData};
20
21/// The [`SideData::Custom`] kind `ec-ogg` attaches a page granule under. It is
22/// `ec_ogg::GRANULE_KIND`; this crate does not depend on `ec-ogg`, so the
23/// constant is restated here.
24const GRANULE_KIND: u32 = u32::from_be_bytes(*b"OggS");
25
26/// The granule position `ec-ogg` attached to `packet`, if it did.
27pub(crate) fn granule_of(packet: &Packet) -> Option<i64> {
28 packet.side_data.iter().find_map(|side| match side {
29 SideData::Custom { kind, data } if *kind == GRANULE_KIND && data.len() == 8 => {
30 Some(i64::from_le_bytes(data[..8].try_into().ok()?))
31 }
32 _ => None,
33 })
34}
35
36/// Holds decoded samples until the granules say which of them are the stream's.
37#[derive(Debug)]
38pub(crate) struct GranuleTrim {
39 /// Decoded samples not yet released, per channel in the output's order.
40 pending: Vec<Vec<f32>>,
41 /// Decoded-sample index of `pending[..][0]`.
42 start: i64,
43 /// Samples decoded so far, released or not.
44 decoded: i64,
45 /// `granule - decoded` at the first granule that arrived before any output,
46 /// or zero when the first granule arrived later. Decoded index `i` is the
47 /// stream's sample `i + offset` in granule terms.
48 offset: Option<i64>,
49 /// Exclusive decoded index the stream ends at, from the latest granule.
50 end: Option<i64>,
51}
52
53impl GranuleTrim {
54 /// An empty trim for `channels` output channels.
55 pub(crate) fn new(channels: usize) -> GranuleTrim {
56 GranuleTrim {
57 pending: vec![Vec::new(); channels],
58 start: 0,
59 decoded: 0,
60 offset: None,
61 end: None,
62 }
63 }
64
65 /// Samples decoded so far.
66 pub(crate) fn decoded(&self) -> i64 {
67 self.decoded
68 }
69
70 /// Take in one packet's decoded samples, one vector per output channel.
71 pub(crate) fn push(&mut self, samples: Vec<Vec<f32>>) {
72 let count = samples.first().map_or(0, Vec::len) as i64;
73 for (pending, samples) in self.pending.iter_mut().zip(samples) {
74 pending.extend(samples);
75 }
76 self.decoded += count;
77 }
78
79 /// Record a granule. `before` is `decoded()` as it stood before the
80 /// packet carrying this granule was pushed.
81 pub(crate) fn granule(&mut self, granule: i64, before: i64) {
82 if self.offset.is_none() {
83 let offset = if before == 0 {
84 granule - self.decoded
85 } else {
86 0
87 };
88 self.offset = Some(offset);
89 // Nothing was released before this packet, so the head to drop is
90 // at the front of what is pending now.
91 let front = (-offset).max(0);
92 let len = self.pending.first().map_or(0, Vec::len) as i64;
93 let drop = front.min(len).max(0) as usize;
94 for pending in &mut self.pending {
95 pending.drain(..drop);
96 }
97 self.start += drop as i64;
98 }
99 self.end = Some(granule - self.offset.unwrap_or(0));
100 }
101
102 /// Samples that are now final, one vector per channel. With `finish` set
103 /// (end of stream), everything the last granule does not reach is dropped.
104 pub(crate) fn release(&mut self, finish: bool) -> Vec<Vec<f32>> {
105 let limit = match self.end {
106 Some(end) => end.min(self.decoded),
107 None => self.decoded,
108 };
109 let len = self.pending.first().map_or(0, Vec::len) as i64;
110 let take = (limit - self.start).clamp(0, len) as usize;
111 let out = self
112 .pending
113 .iter_mut()
114 .map(|pending| pending.drain(..take).collect())
115 .collect();
116 self.start += take as i64;
117 if finish {
118 for pending in &mut self.pending {
119 pending.clear();
120 }
121 self.start = self.decoded;
122 }
123 out
124 }
125
126 /// Forget everything, as a seek does.
127 pub(crate) fn reset(&mut self) {
128 for pending in &mut self.pending {
129 pending.clear();
130 }
131 self.start = 0;
132 self.decoded = 0;
133 self.offset = None;
134 self.end = None;
135 }
136}