forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mux.rs372 lines, 14.8 KiBHistoryRawDownload
1//! Writing: packets in, pages out.
2//!
3//! Two rules shape every page this writes. A granule position states where the
4//! *last packet finishing on that page* ends, so a page is only ever closed
5//! after a packet whose position is known — [`crate::granule_of`] on the packet,
6//! or `pts + duration` when both are stated. And the header packets of every
7//! mapping in this family get pages of their own: the identification packet
8//! alone on the beginning-of-stream page, the rest flushed before the first
9//! audio byte, which is what Vorbis I and RFC 7845 §3 both require.
10//!
11//! Page size is targeted, not fixed: packets are packed until the body passes
12//! [`OggMuxer::set_page_target_bytes`] (4 KiB by default, the size RFC 3533
13//! calls usual) and the next packet boundary with a known granule arrives.
14//! Packets larger than a page are split across pages with the continuation flag,
15//! and a page never carries more than 255 segments.
16
17use std::io::Write;
18
19use ec_core::{Error, Muxer, Packet, Result, StreamInfo};
20
21use crate::mapping::Mapping;
22use crate::page::{self, PageHeader};
23use crate::{granule_of, xiph_unlace};
24
25/// Default page body target: RFC 3533 describes pages as "usually 4-8 kB", and
26/// one packet per page (the alternative) costs 28 bytes of header per 20 ms of
27/// audio.
28pub const DEFAULT_PAGE_TARGET: usize = 4096;
29
30/// Vendor string in a synthesized `OpusTags` packet.
31const VENDOR: &str = "ec-ogg";
32
33/// One logical stream being written.
34struct MuxTrack {
35 serial: u32,
36 /// Header packets in order; the first goes on the beginning-of-stream page.
37 headers: Vec<Vec<u8>>,
38 /// True once the caller supplied headers explicitly, which replace whatever
39 /// `extradata` produced.
40 headers_from_caller: bool,
41 /// Lacing values of the page being built.
42 segments: Vec<u8>,
43 /// Body of the page being built.
44 body: Vec<u8>,
45 /// The page being built opens with the tail of a packet.
46 continued: bool,
47 /// Where the last packet finishing on this page ends, if one has.
48 page_granule: Option<i64>,
49 /// False when a packet finished on this page without stating its position:
50 /// the page cannot be closed here without lying about where it ends.
51 can_end: bool,
52 /// The first data page has not been written yet. It is closed at the first
53 /// position the stream states, whatever the size target says: a decoder
54 /// reads its head trim out of that first granule (a Vorbis stream whose
55 /// first page ends below what its packets decode to is saying "discard the
56 /// difference"), and a page target large enough to swallow it would silently
57 /// add the pre-roll back to the output.
58 first_page_pending: bool,
59 sequence: u32,
60 /// Position written on the last closed page, for the end-of-stream page.
61 last_granule: i64,
62}
63
64impl MuxTrack {
65 fn pending(&self) -> bool {
66 !self.segments.is_empty()
67 }
68}
69
70/// An Ogg writer over any sink.
71pub struct OggMuxer<W: Write> {
72 out: W,
73 streams: Vec<StreamInfo>,
74 tracks: Vec<MuxTrack>,
75 page_target: usize,
76 headers_written: bool,
77 finished: bool,
78}
79
80impl<W: Write> OggMuxer<W> {
81 /// A writer with no streams yet.
82 pub fn new(out: W) -> OggMuxer<W> {
83 OggMuxer {
84 out,
85 streams: Vec::new(),
86 tracks: Vec::new(),
87 page_target: DEFAULT_PAGE_TARGET,
88 headers_written: false,
89 finished: false,
90 }
91 }
92
93 /// Aim for `bytes` of body per page; [`None`] restores
94 /// [`DEFAULT_PAGE_TARGET`]. A page still ends early when its segment table
95 /// fills, and still ends late when the next packet boundary has no granule.
96 pub fn set_page_target_bytes(&mut self, bytes: Option<usize>) {
97 self.page_target = bytes.unwrap_or(DEFAULT_PAGE_TARGET).max(1);
98 }
99
100 /// Override the serial number of stream `index`. Serials only have to be
101 /// unique within the file; the default is derived from the index so that
102 /// two runs over the same input produce the same bytes.
103 pub fn set_serial(&mut self, index: u32, serial: u32) -> Result<()> {
104 let track = self
105 .tracks
106 .get_mut(index as usize)
107 .ok_or_else(|| Error::corrupt(format!("Ogg mux: no stream {index}")))?;
108 track.serial = serial;
109 Ok(())
110 }
111
112 /// Write the beginning-of-stream and remaining header pages of every
113 /// stream. Called automatically before the first data packet; public
114 /// because a caller that declares streams and then hits an error still
115 /// wants a readable file.
116 pub fn write_headers(&mut self) -> Result<()> {
117 if self.headers_written {
118 return Ok(());
119 }
120 if self.tracks.is_empty() {
121 return Err(Error::corrupt("Ogg mux: no streams were declared"));
122 }
123 // Every beginning-of-stream page first, in declaration order, before any
124 // other page in the file (RFC 3533 §4).
125 for index in 0..self.tracks.len() {
126 let first = match self.tracks[index].headers.first() {
127 Some(packet) => packet.clone(),
128 None => {
129 return Err(Error::corrupt(format!(
130 "Ogg mux: stream {index} has no identification header (extradata was empty \
131 and no header packet was written)"
132 )));
133 }
134 };
135 self.push_packet(index, &first, Some(0))?;
136 self.flush_page(index, true, false)?;
137 }
138 // Then the remaining headers, each stream's flushed before any audio.
139 for index in 0..self.tracks.len() {
140 let rest: Vec<Vec<u8>> = self.tracks[index].headers[1..].to_vec();
141 for packet in rest {
142 self.push_packet(index, &packet, Some(0))?;
143 }
144 if self.tracks[index].pending() {
145 self.flush_page(index, false, false)?;
146 }
147 }
148 self.headers_written = true;
149 Ok(())
150 }
151
152 /// Append one packet's segments to the page being built, splitting across
153 /// pages when the segment table fills.
154 fn push_packet(&mut self, index: usize, data: &[u8], granule: Option<i64>) -> Result<()> {
155 // Prefer a clean packet boundary to a continuation: if the packet cannot
156 // fit in what is left of the segment table, close the page first — as
157 // long as closing it here would state a truthful position.
158 let needed = data.len() / 255 + 1;
159 let track = &self.tracks[index];
160 if track.pending() && track.can_end && track.segments.len() + needed > page::MAX_SEGMENTS {
161 self.flush_page(index, false, false)?;
162 }
163
164 let mut at = 0usize;
165 for lace in page::lacing(data.len()) {
166 if self.tracks[index].segments.len() == page::MAX_SEGMENTS {
167 // Forced mid-packet: no packet finishes on this page, which is
168 // exactly what a -1 granule means.
169 self.flush_page(index, false, false)?;
170 self.tracks[index].continued = true;
171 }
172 let track = &mut self.tracks[index];
173 track.segments.push(lace);
174 track
175 .body
176 .extend_from_slice(&data[at..at + usize::from(lace)]);
177 at += usize::from(lace);
178 }
179
180 // A page may only end where the *last* packet finishing on it states
181 // its position, so this tracks the latest packet, not the latest known
182 // granule: one positionless packet after a positioned one closes the
183 // page again.
184 let track = &mut self.tracks[index];
185 match granule {
186 Some(granule) => {
187 track.page_granule = Some(granule);
188 track.can_end = true;
189 }
190 None => track.can_end = false,
191 }
192 Ok(())
193 }
194
195 /// Write the page under construction.
196 fn flush_page(&mut self, index: usize, bos: bool, eos: bool) -> Result<()> {
197 let track = &mut self.tracks[index];
198 if track.segments.is_empty() && !eos {
199 return Ok(());
200 }
201 let granule = match (track.can_end, track.page_granule) {
202 (true, Some(granule)) => granule,
203 // An end-of-stream page with nothing left to carry still states
204 // where the stream ends, or a player has no length to trim to.
205 (_, None) if eos && track.segments.is_empty() => track.last_granule,
206 _ => page::NO_GRANULE,
207 };
208 let header = PageHeader {
209 continued: track.continued,
210 bos,
211 eos,
212 granule,
213 serial: track.serial,
214 sequence: track.sequence,
215 // A page always carries at least one lacing value, even an
216 // end-of-stream page with nothing left to say.
217 segments: match track.segments.is_empty() {
218 true => vec![0],
219 false => std::mem::take(&mut track.segments),
220 },
221 };
222 let body = std::mem::take(&mut track.body);
223 track.sequence += 1;
224 track.continued = false;
225 track.page_granule = None;
226 track.can_end = true;
227 if granule != page::NO_GRANULE {
228 track.last_granule = granule;
229 }
230
231 let mut bytes = Vec::with_capacity(page::HEADER_LEN + header.segments.len() + body.len());
232 header.write_page(&body, &mut bytes);
233 self.out.write_all(&bytes)?;
234 Ok(())
235 }
236
237 /// Header packets from `extradata`, per mapping.
238 fn headers_from_extradata(info: &StreamInfo) -> Result<Vec<Vec<u8>>> {
239 let Some(extradata) = info.params.extradata.as_ref().filter(|e| !e.is_empty()) else {
240 return Ok(Vec::new());
241 };
242 // Xiph-laced extradata carries the whole triplet; a bare identification
243 // packet does not, and Vorbis has no way to invent the other two.
244 if let Ok(packets) = xiph_unlace(extradata)
245 && packets.len() >= 2
246 && Mapping::identify(packets[0]).is_some()
247 {
248 return Ok(packets.into_iter().map(<[u8]>::to_vec).collect());
249 }
250 match Mapping::identify(extradata) {
251 Some(Mapping::Opus { .. }) => Ok(vec![extradata.to_vec(), opus_tags()]),
252 Some(Mapping::Vorbis { .. }) => Err(Error::corrupt(
253 "Ogg mux: Vorbis extradata holds only the identification header; the comment and \
254 setup headers are needed too (Xiph-laced, as xiph_lace produces)",
255 )),
256 // Anything else — a FLAC mapping header, a codec this crate does not
257 // name — is written verbatim as the first header packet, with the
258 // rest expected as header-flagged packets.
259 _ => Ok(vec![extradata.to_vec()]),
260 }
261 }
262}
263
264/// A minimal `OpusTags` packet: RFC 7845 §5 requires one, and a remux that only
265/// carried `OpusHead` has no comments to preserve.
266fn opus_tags() -> Vec<u8> {
267 let mut out = Vec::from(*b"OpusTags");
268 out.extend_from_slice(&(VENDOR.len() as u32).to_le_bytes());
269 out.extend_from_slice(VENDOR.as_bytes());
270 out.extend_from_slice(&0u32.to_le_bytes()); // comment count
271 out
272}
273
274impl<W: Write + Send> Muxer for OggMuxer<W> {
275 fn add_stream(&mut self, info: StreamInfo) -> Result<u32> {
276 if self.headers_written {
277 return Err(Error::corrupt(
278 "Ogg mux: every stream is declared before the first packet",
279 ));
280 }
281 let index = self.tracks.len() as u32;
282 let headers = OggMuxer::<W>::headers_from_extradata(&info)?;
283 self.tracks.push(MuxTrack {
284 // Unique within the file and stable across runs, which keeps a
285 // remux byte-comparable with itself.
286 serial: 0x4544_0000 ^ index,
287 headers,
288 headers_from_caller: false,
289 segments: Vec::new(),
290 body: Vec::new(),
291 continued: false,
292 page_granule: None,
293 can_end: true,
294 first_page_pending: true,
295 sequence: 0,
296 last_granule: 0,
297 });
298 let mut info = info;
299 info.index = index;
300 self.streams.push(info);
301 Ok(index)
302 }
303
304 /// Write one packet.
305 ///
306 /// A packet flagged [`ec_core::PacketFlags::header`] before any audio joins
307 /// the stream's header packets — the first one replaces whatever
308 /// `extradata` gave, so a remux can carry the original `OpusTags` through.
309 /// Otherwise the packet's granule position is [`crate::granule_of`], or
310 /// `pts + duration` when both are known, or unknown — and a page never ends
311 /// on a packet whose position is unknown.
312 fn write_packet(&mut self, packet: &Packet) -> Result<()> {
313 let index = packet.stream as usize;
314 if index >= self.tracks.len() {
315 return Err(Error::corrupt(format!(
316 "Ogg mux: packet for stream {} of {} declared",
317 packet.stream,
318 self.tracks.len()
319 )));
320 }
321 if packet.flags.header && !self.headers_written {
322 let track = &mut self.tracks[index];
323 if !track.headers_from_caller {
324 track.headers.clear();
325 track.headers_from_caller = true;
326 }
327 track.headers.push(packet.data.to_vec());
328 return Ok(());
329 }
330 self.write_headers()?;
331
332 // The page is closed *before* the packet that would overflow it, never
333 // after: that keeps at least one packet pending at all times, so the
334 // end-of-stream flag rides a page that carries audio. A page whose only
335 // content is a zero-length packet is legal Ogg and the oracle reads it as a
336 // packet — "Packet processing failed", a decode error in a file that is
337 // otherwise perfect.
338 let track = &self.tracks[index];
339 let due = track.body.len() >= self.page_target || track.first_page_pending;
340 if track.pending() && track.can_end && due {
341 self.flush_page(index, false, false)?;
342 self.tracks[index].first_page_pending = false;
343 }
344 let granule = granule_of(packet).or_else(|| packet.end_pts());
345 let data = packet.data.clone();
346 self.push_packet(index, &data, granule)?;
347 Ok(())
348 }
349
350 fn finish(&mut self) -> Result<()> {
351 if self.finished {
352 return Ok(());
353 }
354 self.write_headers()?;
355 for index in 0..self.tracks.len() {
356 // The end-of-stream flag rides the last page — which still carries
357 // audio, because packets are only paged out on the arrival of the
358 // next one. Empty only when the stream had no data packets at all.
359 self.flush_page(index, false, true)?;
360 }
361 self.out.flush()?;
362 self.finished = true;
363 Ok(())
364 }
365}
366
367impl<W: Write> OggMuxer<W> {
368 /// The sink, for callers that wrote into a buffer and want it back.
369 pub fn into_inner(self) -> W {
370 self.out
371 }
372}