forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

demux.rs566 lines, 22.3 KiBHistoryRawDownload
1//! Reading: pages in, packets out.
2//!
3//! Three things make an Ogg demuxer more than a loop over pages. Packets are
4//! *not* page-sized — one packet can span pages and one page can hold dozens —
5//! so segments are reassembled across pages. Timing comes from the page, not
6//! the packet: a granule position states where the last packet finishing on
7//! that page ends, so packet timestamps are carried forward from each page
8//! boundary and re-synchronised at the next one (exactly, for a mapping that
9//! states per-packet durations; page by page for one that does not — see
10//! [`Mapping::packet_duration`]). And a page whose checksum fails is not fatal:
11//! the reader drops it, discards whatever packet it was assembling and scans
12//! on for the next capture pattern, so damage costs the packets inside the
13//! damaged page and nothing after it.
14
15use std::collections::VecDeque;
16use std::io::{BufReader, Read, Seek, SeekFrom};
17
18use ec_core::{
19 Buf, CodecParameters, Demuxer, Error, MediaParameters, Packet, Result, SeekMode, StreamInfo,
20 Timestamp,
21};
22
23use crate::mapping::Mapping;
24use crate::page::{self, PageHeader};
25use crate::{granule_side_data, xiph_lace};
26
27/// One page, read and verified.
28struct RawPage {
29 header: PageHeader,
30 body: Vec<u8>,
31 /// Byte offset of the capture pattern.
32 offset: u64,
33}
34
35/// What one attempt at reading a page produced.
36enum Step {
37 /// A page whose checksum verified.
38 Page(RawPage),
39 /// A capture pattern whose page did not verify; scanning resumes just past
40 /// it.
41 Damaged,
42 /// No further page in the file.
43 End,
44}
45
46/// Per logical stream state, in discovery order.
47struct Track {
48 serial: u32,
49 mapping: Mapping,
50 /// Header packets, in order, until [`Mapping::header_packets`] are in.
51 headers: Vec<Vec<u8>>,
52 /// Bytes of a packet still being assembled across a page boundary.
53 partial: Vec<u8>,
54 /// A packet is mid-assembly (true even when its bytes so far are empty,
55 /// which happens when a page ends exactly on a 255-byte segment).
56 assembling: bool,
57 /// Granule position the next packet starts at.
58 pos: i64,
59 /// False between a packet of unknown duration and the next page granule.
60 pos_known: bool,
61 /// The stream has seen its end-of-stream page.
62 eos: bool,
63}
64
65impl Track {
66 fn headers_complete(&self) -> bool {
67 self.headers.len() >= self.mapping.header_packets()
68 }
69}
70
71/// An Ogg reader over anything seekable.
72///
73/// [`OggDemuxer::open`] consumes the header packets of every logical stream, so
74/// [`Demuxer::streams`] is complete before the first [`Demuxer::next_packet`],
75/// and header packets are never handed out as packets — they live in
76/// [`CodecParameters::extradata`], Xiph-laced for Vorbis, the raw `OpusHead`
77/// for Opus.
78pub struct OggDemuxer<R: Read + Seek> {
79 inner: BufReader<R>,
80 streams: Vec<StreamInfo>,
81 tracks: Vec<Track>,
82 queue: VecDeque<Packet>,
83 /// Offset of the first page past the last header page.
84 data_start: u64,
85 /// Pages dropped for a failed checksum.
86 damaged: u64,
87}
88
89impl<R: Read + Seek> OggDemuxer<R> {
90 /// Read every stream's headers and stop at the first audio page.
91 pub fn open(inner: R) -> Result<OggDemuxer<R>> {
92 let mut demuxer = OggDemuxer {
93 inner: BufReader::new(inner),
94 streams: Vec::new(),
95 tracks: Vec::new(),
96 queue: VecDeque::new(),
97 data_start: 0,
98 damaged: 0,
99 };
100 demuxer.read_headers()?;
101 demuxer.measure_durations()?;
102 Ok(demuxer)
103 }
104
105 /// How many pages were dropped because their checksum did not verify.
106 pub fn damaged_pages(&self) -> u64 {
107 self.damaged
108 }
109
110 /// The mapping of stream `index`, for callers that need the pre-skip or the
111 /// granule clock behind [`StreamInfo::time_base`].
112 pub fn mapping(&self, index: usize) -> Option<Mapping> {
113 self.tracks.get(index).map(|t| t.mapping)
114 }
115
116 /// Read pages until every discovered stream has all of its header packets.
117 fn read_headers(&mut self) -> Result<()> {
118 loop {
119 if !self.tracks.is_empty() && self.tracks.iter().all(Track::headers_complete) {
120 self.data_start = self.inner.stream_position()?;
121 return Ok(());
122 }
123 match read_page(&mut self.inner)? {
124 Step::Page(page) => self.consume(page)?,
125 Step::Damaged => self.damaged += 1,
126 Step::End => match self.tracks.is_empty() {
127 true => {
128 return Err(Error::corrupt(
129 "Ogg: no logical stream with a known mapping",
130 ));
131 }
132 // Headers that never completed: whatever streams were found
133 // are described as far as their headers went.
134 false => {
135 self.data_start = self.inner.stream_position()?;
136 return Ok(());
137 }
138 },
139 }
140 }
141 }
142
143 /// Walk to the end once to learn each stream's last granule position, then
144 /// come back. Cheap (a bounded tail scan) and it is the only way an Ogg
145 /// file states its duration at all.
146 fn measure_durations(&mut self) -> Result<()> {
147 let resume = self.inner.stream_position()?;
148 let end = self.inner.seek(SeekFrom::End(0))?;
149 // Tail window, widened until a page for every stream turns up or the
150 // whole file has been walked.
151 let mut window = 64 * 1024;
152 let mut last: Vec<Option<i64>> = vec![None; self.tracks.len()];
153 loop {
154 let from = end.saturating_sub(window);
155 self.inner.seek(SeekFrom::Start(from))?;
156 loop {
157 match read_page(&mut self.inner)? {
158 Step::Page(page) => {
159 if let Some(i) = self.track_index(page.header.serial)
160 && page.header.granule != page::NO_GRANULE
161 {
162 last[i] = Some(page.header.granule);
163 }
164 }
165 Step::Damaged => continue,
166 Step::End => break,
167 }
168 }
169 if last.iter().all(Option::is_some) || from == 0 {
170 break;
171 }
172 window *= 8;
173 }
174 for (i, granule) in last.into_iter().enumerate() {
175 if let Some(granule) = granule {
176 let start = self.streams[i].start_time.unwrap_or(0);
177 // A granule too close to i64::MIN to subtract the pre-skip from states no
178 // duration, rather than wrapping into a bogus one.
179 self.streams[i].duration = granule.checked_sub(start).map(|d| d.max(0));
180 }
181 }
182 self.inner.seek(SeekFrom::Start(resume))?;
183 Ok(())
184 }
185
186 fn track_index(&self, serial: u32) -> Option<usize> {
187 self.tracks.iter().position(|t| t.serial == serial)
188 }
189
190 /// Turn one page into packets: header packets into the stream description,
191 /// audio packets into the queue.
192 fn consume(&mut self, page: RawPage) -> Result<()> {
193 let serial = page.header.serial;
194 let index = match self.track_index(serial) {
195 Some(i) => i,
196 None => match page.header.bos {
197 true => match self.start_track(&page) {
198 Some(i) => i,
199 // A mapping nothing in this family claims (Theora, Skeleton,
200 // a private stream): its pages are skipped, not an error —
201 // the audio streams beside it still read.
202 None => return Ok(()),
203 },
204 false => return Ok(()),
205 },
206 };
207
208 let mapping = self.tracks[index].mapping;
209 let time_base = self.streams[index].time_base;
210 let mut packet = std::mem::take(&mut self.tracks[index].partial);
211 let mut assembling = self.tracks[index].assembling;
212 let mut pos = self.tracks[index].pos;
213 let mut pos_known = self.tracks[index].pos_known;
214 let mut headers_done = self.tracks[index].headers_complete();
215 let mut at = 0usize;
216 let mut segments = &page.header.segments[..];
217
218 match (page.header.continued, assembling) {
219 // The head of this packet was in a page we never saw: drop segments
220 // up to and including the first terminator.
221 (true, false) => {
222 let mut skipped = 0;
223 for (i, &lace) in segments.iter().enumerate() {
224 at += usize::from(lace);
225 skipped = i + 1;
226 if lace < 255 {
227 break;
228 }
229 }
230 segments = &segments[skipped..];
231 }
232 // A packet was mid-assembly and this page does not continue it: the
233 // partial is orphaned.
234 (false, true) => {
235 packet.clear();
236 assembling = false;
237 }
238 _ => {}
239 }
240
241 let first_new = self.queue.len();
242 for &lace in segments {
243 let end = at + usize::from(lace);
244 let Some(slice) = page.body.get(at..end) else {
245 // The segment table promised more body than the page carried.
246 return Err(Error::corrupt("Ogg page: segment table overruns the body"));
247 };
248 packet.extend_from_slice(slice);
249 at = end;
250 if lace == 255 {
251 assembling = true;
252 continue;
253 }
254 assembling = false;
255 let done = std::mem::take(&mut packet);
256 match headers_done {
257 false => {
258 self.tracks[index].headers.push(done);
259 if self.tracks[index].headers_complete() {
260 headers_done = true;
261 self.finish_stream(index)?;
262 }
263 }
264 true => {
265 // The zero-length segment a muxer uses to carry an
266 // end-of-stream flag on an otherwise empty page is not a
267 // packet; handing it out would inflate every packet count.
268 if done.is_empty() {
269 continue;
270 }
271 let duration = mapping.packet_duration(&done);
272 let mut out = Packet::new(index as u32, time_base, done);
273 out.pts = pos_known.then_some(pos);
274 out.dts = out.pts;
275 out.duration = duration;
276 // Every Ogg audio packet is a decodable entry point as far
277 // as the container is concerned; codec pre-roll (a Vorbis
278 // block needs its predecessor to overlap) is the decoder's.
279 out.flags.keyframe = true;
280 match duration {
281 // Past i64::MAX the position is no longer known, like an
282 // unknown duration: the next page granule re-anchors it.
283 Some(d) if pos_known => match pos.checked_add(d) {
284 Some(next) => pos = next,
285 None => pos_known = false,
286 },
287 Some(_) => {}
288 None => pos_known = false,
289 }
290 self.queue.push_back(out);
291 }
292 }
293 }
294 let track = &mut self.tracks[index];
295 track.partial = packet;
296 track.assembling = assembling;
297 track.pos = pos;
298 track.pos_known = pos_known;
299 track.eos |= page.header.eos;
300
301 // The granule is where the last packet finishing on this page ends, so
302 // it is also where the next one starts — the point every mapping's
303 // timing is re-anchored to.
304 if page.header.granule != page::NO_GRANULE {
305 if self.queue.len() > first_new {
306 let last = self.queue.len() - 1;
307 self.queue[last]
308 .side_data
309 .push(granule_side_data(page.header.granule));
310 }
311 let track = &mut self.tracks[index];
312 track.pos = page.header.granule;
313 track.pos_known = true;
314 }
315 Ok(())
316 }
317
318 /// A beginning-of-stream page: identify the mapping from its first packet.
319 fn start_track(&mut self, page: &RawPage) -> Option<usize> {
320 let len = usize::from(*page.header.segments.first()?);
321 let first = page.body.get(..len)?;
322 let mapping = Mapping::identify(first)?;
323 let mut params = CodecParameters::new(mapping.codec());
324 if let MediaParameters::Audio(audio) = &mut params.media {
325 audio.sample_rate = mapping.sample_rate();
326 audio.layout = mapping.layout();
327 }
328 let index = self.tracks.len();
329 let mut info = StreamInfo::new(index as u32, mapping.time_base(), params);
330 info.start_time = Some(match mapping {
331 // Opus granules include the samples a decoder throws away, so
332 // presentation starts at the pre-skip rather than at zero.
333 Mapping::Opus { pre_skip, .. } => i64::from(pre_skip),
334 _ => 0,
335 });
336 self.streams.push(info);
337 self.tracks.push(Track {
338 serial: page.header.serial,
339 mapping,
340 headers: Vec::new(),
341 partial: Vec::new(),
342 assembling: false,
343 pos: 0,
344 pos_known: true,
345 eos: false,
346 });
347 Some(index)
348 }
349
350 /// All header packets are in: publish them as `extradata`.
351 fn finish_stream(&mut self, index: usize) -> Result<()> {
352 let track = &self.tracks[index];
353 let extradata = match track.mapping {
354 // The three-packet triplet, laced the way every consumer of Vorbis
355 // extradata outside Ogg expects it.
356 Mapping::Vorbis { .. } => {
357 let refs: Vec<&[u8]> = track.headers.iter().map(Vec::as_slice).collect();
358 xiph_lace(&refs)
359 }
360 // RFC 7845 identification header, verbatim; the tags packet is
361 // metadata, not decoder setup.
362 Mapping::Opus { .. } | Mapping::Flac { .. } => Some(track.headers[0].clone()),
363 };
364 self.streams[index].params.extradata = extradata.map(Buf::from_vec);
365 Ok(())
366 }
367
368 /// Scan forward from `offset` for the next page of `serial`.
369 fn page_at_or_after(&mut self, offset: u64, serial: u32) -> Result<Option<(u64, i64)>> {
370 self.inner.seek(SeekFrom::Start(offset))?;
371 loop {
372 match read_page(&mut self.inner)? {
373 Step::Page(page) if page.header.serial == serial => {
374 return Ok(Some((page.offset, page.header.granule)));
375 }
376 Step::Page(_) | Step::Damaged => continue,
377 Step::End => return Ok(None),
378 }
379 }
380 }
381
382 /// Drop assembly state and queued packets after a jump.
383 fn reset_state(&mut self) {
384 self.queue.clear();
385 for track in &mut self.tracks {
386 track.partial.clear();
387 track.assembling = false;
388 track.pos_known = false;
389 track.eos = false;
390 }
391 }
392}
393
394impl<R: Read + Seek + Send> Demuxer for OggDemuxer<R> {
395 fn streams(&self) -> &[StreamInfo] {
396 &self.streams
397 }
398
399 fn next_packet(&mut self) -> Result<Packet> {
400 loop {
401 if let Some(packet) = self.queue.pop_front() {
402 return Ok(packet);
403 }
404 match read_page(&mut self.inner)? {
405 Step::Page(page) => self.consume(page)?,
406 Step::Damaged => self.damaged += 1,
407 Step::End => return Err(Error::Eof),
408 }
409 }
410 }
411
412 /// Land on a page boundary at or before `to` by bisecting the file on
413 /// granule positions — the only index Ogg has.
414 ///
415 /// [`SeekMode::Exact`] is served as [`SeekMode::SyncBefore`]: pages are the
416 /// finest position the container offers, and a decoder that needs the
417 /// sample exactly discards forward from there.
418 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
419 let index = usize::try_from(stream).unwrap_or(usize::MAX);
420 let info = self
421 .streams
422 .get(index)
423 .ok_or_else(|| Error::corrupt(format!("Ogg seek: no stream {stream}")))?;
424 let serial = self.tracks[index].serial;
425 let target = to.rescale(info.time_base, ec_core::Rounding::Down).ticks;
426 let first_stream_page = self
427 .page_at_or_after(self.data_start, serial)?
428 .map(|(offset, _)| offset);
429
430 let end = self.inner.seek(SeekFrom::End(0))?;
431 let mut lo = self.data_start;
432 let mut hi = end;
433 // Last page start whose granule is at or before the target, and the
434 // first one at or after it — one bisection answers both.
435 let mut before: Option<(u64, i64)> = None;
436 let mut after: Option<(u64, i64)> = None;
437 while lo < hi {
438 let mid = lo + (hi - lo) / 2;
439 match self.page_at_or_after(mid, serial)? {
440 Some((offset, granule)) if granule != page::NO_GRANULE && granule <= target => {
441 before = Some((offset, granule));
442 // Always make progress: the found page may start before mid.
443 lo = offset.max(mid) + 1;
444 }
445 Some((offset, granule)) if granule != page::NO_GRANULE => {
446 after = Some((offset, granule));
447 hi = match offset > mid {
448 true => mid,
449 false => offset,
450 };
451 }
452 // A page with no granule says nothing about position; step past
453 // it rather than splitting the same interval forever.
454 Some((offset, _)) => lo = offset.max(mid) + 1,
455 None => hi = mid,
456 }
457 }
458 let found = match mode {
459 SeekMode::SyncAfter => after.or(before),
460 // No page ends at or before the target: it is inside the first one,
461 // and the stream's beginning is what "at or before" means there.
462 _ => before,
463 };
464 self.reset_state();
465 let granule = match found {
466 // The first data page is the stream head. Replaying it must behave
467 // exactly like a fresh open: its packet carries the head trim
468 // granule, and the packet's timestamp still starts at zero.
469 Some((offset, _)) if Some(offset) == first_stream_page => {
470 self.inner.seek(SeekFrom::Start(offset))?;
471 0
472 }
473 // A granule is where a page *ends*, and a Vorbis or FLAC packet
474 // states no duration of its own — so reading from the page the
475 // bisection found would hand out its packets with no timestamp at
476 // all, and a seek could not say where it landed. The landing is the
477 // page *after* it, whose first sample is that page's granule.
478 Some((offset, granule)) => {
479 self.inner.seek(SeekFrom::Start(offset))?;
480 read_page(&mut self.inner)?;
481 granule
482 }
483 // Nothing indexed the target: the stream's own beginning is the
484 // only honest answer, and every packet of it is still to come.
485 None => {
486 self.inner.seek(SeekFrom::Start(self.data_start))?;
487 0
488 }
489 };
490 // Never resume inside the headers: they are not audio and must not be
491 // handed out as packets.
492 if self.inner.stream_position()? < self.data_start {
493 self.inner.seek(SeekFrom::Start(self.data_start))?;
494 }
495 let track = &mut self.tracks[index];
496 track.pos = granule;
497 track.pos_known = true;
498 Ok(())
499 }
500}
501
502/// Read one page: scan for the capture pattern, verify the checksum, hand back
503/// header and body.
504fn read_page<R: Read + Seek>(inner: &mut BufReader<R>) -> Result<Step> {
505 let mut fixed = [0u8; page::HEADER_LEN];
506 let mut window = 0usize;
507 // Scan for "OggS". The pattern has no proper prefix that is also a suffix,
508 // so a failed match can never hide the start of a real one.
509 while window < 4 {
510 let mut byte = [0u8; 1];
511 match inner.read(&mut byte) {
512 Ok(0) => return Ok(Step::End),
513 Ok(_) => {}
514 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
515 Err(e) => return Err(e.into()),
516 }
517 window = match byte[0] == page::CAPTURE[window] {
518 true => window + 1,
519 false => usize::from(byte[0] == page::CAPTURE[0]),
520 };
521 }
522 let offset = inner.stream_position()? - 4;
523 fixed[..4].copy_from_slice(&page::CAPTURE);
524 if read_exact_or_end(inner, &mut fixed[4..])? {
525 return Ok(Step::End);
526 }
527
528 let Ok((mut header, nsegs)) = PageHeader::parse_fixed(&fixed) else {
529 inner.seek(SeekFrom::Start(offset + 4))?;
530 return Ok(Step::Damaged);
531 };
532 let mut segments = vec![0u8; nsegs];
533 if read_exact_or_end(inner, &mut segments)? {
534 return Ok(Step::End);
535 }
536 header.segments = segments;
537 let mut body = vec![0u8; header.body_len()];
538 if read_exact_or_end(inner, &mut body)? {
539 return Ok(Step::End);
540 }
541
542 let stored = PageHeader::stored_crc(&fixed);
543 let mut zeroed = fixed;
544 zeroed[22..26].fill(0);
545 if crate::crc::crc32(&[&zeroed, &header.segments, &body]) != stored {
546 // Damage is local: resume scanning right after this capture pattern so
547 // the very next intact page is found.
548 inner.seek(SeekFrom::Start(offset + 4))?;
549 return Ok(Step::Damaged);
550 }
551 Ok(Step::Page(RawPage {
552 header,
553 body,
554 offset,
555 }))
556}
557
558/// `read_exact`, with a truncated file reported as end rather than as an error:
559/// a half-written page at EOF is the normal shape of an interrupted recording.
560fn read_exact_or_end<R: Read>(inner: &mut BufReader<R>, buf: &mut [u8]) -> Result<bool> {
561 match inner.read_exact(buf) {
562 Ok(()) => Ok(false),
563 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(true),
564 Err(e) => Err(e.into()),
565 }
566}