From dca152c77e11ad02a8b2ebffab970dbc5bf02631 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:10:06 -0800 Subject: [PATCH 1/2] craft-media: Ogg probe reads only the header pages, and PacketReader reads packets in file order ogg::open reads and indexes every page of a file before a caller can read its first packet. Two ways to start sooner: - probe reads pages only until every stream that begins at the start of the file has its header packets, then returns the streams with their codecs and headers. It also stops after PROBE_PACKETS data packets or at the first page past PROBE_BYTES (128 MiB); the search past damage stops there as well. - PacketReader reads the same first pages, then returns the data packets of every stream in file order, one page at a time, into a buffer the caller reuses. It keeps no packet list, so memory does not grow with the file. Header packets of later links of a chained file are filed in streams() as their pages are reached. open, probe and PacketReader share one page reader, so they check CRCs, skip damage and warn the same way. OggFile::read_packet_into reads a packet into a reused buffer. Tests compare the reader with open on clean, damaged, chained and truncated files, and check where the probe stops and what it reads. --- crates/media/README.md | 11 +- crates/media/src/ogg/mod.rs | 596 +++++++++++++++++++++++----------- crates/media/src/ogg/tests.rs | 248 ++++++++++++++ 3 files changed, 666 insertions(+), 189 deletions(-) diff --git a/crates/media/README.md b/crates/media/README.md index a90b559932..2c62bc132b 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -448,6 +448,14 @@ link of a chained file), unless it carries on the page sequence of a stream with page yet. Damage recovery may read bytes again up to twice the file's length plus 1 MiB, so a file is read at most about three times over; the packets kept and the header packets of a stream are bounded too, with a warning when a bound is reached. +`probe` reads only the first pages: it stops once every stream that begins there has its header +packets, after `PROBE_PACKETS` data packets, or at the first page that would start after +`PROBE_BYTES` (128 MiB), a limit the search past damage keeps to as well. `PacketReader` +reads the same first pages, then returns the data packets of every stream in file order, one page +at a time, into a buffer the caller reuses. It keeps no packet list, so the cap on kept packets does +not apply to it; damage is skipped with the same budget and warnings as `open`. Header packets stay +in `streams()`, where a later link of a chained file appears as a new stream when its pages are +reached. `OggFile::read_packet_into` reads a packet into a reused buffer. `OpusTiming` gives each Opus packet's start, the pre-skip and the end trimming of the final page. The muxer side is `PageWriter`, from FilmCraft's `filmcraft-oggmux` by @JordyUSA @@ -1018,7 +1026,8 @@ custom source (a web `Blob`, a network range reader) to use every container with additions, color and mastering metadata, Chapters, Tags, Attachments, CRC-32, Cue-less seek, hostile cluster timestamps) and mux-demux round trips. For Ogg (`src/ogg`): page parsing, CRC, packets across pages, damage resync and its read budget, lost pages, chained links and stray - beginning-of-stream flags, the packet and header caps, Opus timing (end trimming, hostile granules) and the codec parameters of each codec. + beginning-of-stream flags, the packet and header caps, the first-pages probe and its limits, the + sequential reader against `open`, Opus timing (end trimming, hostile granules) and the codec parameters of each codec. - `tests/roundtrip.rs`: property tests that write random multi-track files (progressive and fragmented) and read them back. - `tests/oracle_demux.rs` and `tests/oracle_mux.rs` compare the demuxer and muxer with ffprobe and diff --git a/crates/media/src/ogg/mod.rs b/crates/media/src/ogg/mod.rs index d487f92242..3986ac10f3 100644 --- a/crates/media/src/ogg/mod.rs +++ b/crates/media/src/ogg/mod.rs @@ -8,6 +8,10 @@ //! `OpusHead` + `OpusTags`; Vorbis: identification, comment, setup) are collected separately from //! the audio packets. //! +//! [`probe`] reads only the first pages, as far as every stream's header packets, and +//! [`PacketReader`] goes on from there, returning the data packets in file order a page at a time +//! without indexing the file. +//! //! [`OpusTiming`] implements RFC 7845 §4: packet start positions from granule positions and //! TOC-derived durations, the pre-skip, and end trimming of the final page, so a player can seek //! to any 48 kHz sample. @@ -23,7 +27,7 @@ #![warn(missing_docs)] -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::fmt; use std::io; @@ -267,6 +271,8 @@ pub struct Stream { header_bytes: usize, /// The page sequence number the next page should carry. next_seq: Option, + /// The first packet has been filed (it set `codec` and `header_count`). + started: bool, } impl Stream { @@ -338,7 +344,9 @@ impl Stream { // the first packet is read once: for its codec, and then as a header (a packet too large // to be one is only read as far as the codec needs) let mut first = None; - if self.headers.is_empty() && self.packets.is_empty() { + // `PacketReader` takes data packets out of `packets`, so empty lists do not mark the first + if !self.started { + self.started = true; let data = read_parts(src, &pk.parts, if size <= MAX_HEADER_BYTES { size } else { FIRST_PACKET_PREFIX })?; self.codec = Codec::of(&data); self.header_count = match self.codec { @@ -381,6 +389,11 @@ impl Stream { self.headers.push(data); Ok(()) } + + /// Every header packet has been read: the next packet is data. + fn headers_complete(&self) -> bool { + self.headers.len() >= self.header_count + } } /// An opened Ogg file. @@ -434,10 +447,15 @@ impl Warnings { } self.damage += 1; } - fn finish(mut self) -> Vec { + /// Add the closing warning that counts the damaged regions not listed since the last one. + fn close(&mut self) { if let Some(more) = self.damage.checked_sub(MAX_DAMAGE_WARNINGS).filter(|&n| n > 0) { self.list.push(format!("{more} more damaged regions not listed")); + self.damage = MAX_DAMAGE_WARNINGS; } + } + fn finish(mut self) -> Vec { + self.close(); self.list } } @@ -490,188 +508,375 @@ enum Capture { /// Read every page and assemble the packets of every logical bitstream. pub fn open(src: &(impl ByteSource + ?Sized)) -> Result { let len = src.len(); - let mut streams: Vec = Vec::new(); - let mut by_serial: HashMap = HashMap::new(); - let mut partial: HashMap = HashMap::new(); - let mut warnings = Warnings::default(); - let mut pos = 0u64; - let mut found_any = false; - let mut recovery = Recovery::new(len); - let mut packet_budget = usize::try_from(len / FILE_BYTES_PER_PACKET).unwrap_or(usize::MAX).clamp(MIN_PACKET_ALLOWANCE, MAX_PACKETS); - let mut hdr = [0u8; 27 + 255]; - while pos + 27 <= len { - src.read_at(pos, &mut hdr[..27])?; - if !recovery.charge(pos, pos + 27) { - warnings.push(past_budget(pos)); - break; - } - if &hdr[..4] != b"OggS" || hdr[4] != 0 { - match find_capture(src, pos + 1, len, &mut recovery)? { - Capture::At(p) => { - if found_any { - warnings.damage(|| format!("lost sync at byte {pos}; resumed at {p}")); - } - pos = p; - continue; - } - Capture::End => break, - Capture::BudgetSpent => { - warnings.push(past_budget(pos)); - break; - } - } - } - let nseg = hdr[26] as usize; - let head = 27 + nseg; - let page_len = if pos + head as u64 <= len { - src.read_at(pos + 27, &mut hdr[27..head])?; - head as u64 + hdr[27..head].iter().map(|&b| b as u64).sum::() - } else { - u64::MAX - }; - let fits = pos.saturating_add(page_len) <= len; - // the lacing values and the body: fake page headers a few bytes apart would otherwise - // each have their overlapping bodies read and hashed for free - if !recovery.charge(pos + 27, if fits { pos + page_len } else { (pos + head as u64).min(len) }) { - warnings.push(past_budget(pos)); - break; - } - if !fits { - // truncated, or a damaged lacing value: look for a page further on - warnings.damage(|| format!("page at byte {pos} runs past the end of the file")); - pos += 1; - continue; - } - let mut page = vec![0u8; page_len as usize]; - page[..head].copy_from_slice(&hdr[..head]); - src.read_at(pos + head as u64, &mut page[head..])?; - let stored_crc = u32::from_le_bytes([page[22], page[23], page[24], page[25]]); - page[22..26].fill(0); - if crc32(&page) != stored_crc { - warnings.damage(|| format!("bad CRC on page at byte {pos}")); - pos += 1; - continue; - } - found_any = true; - let flags = page[5]; - let granule = i64::from_le_bytes(page[6..14].try_into().unwrap_or([0; 8])); - let serial = u32::from_le_bytes([page[14], page[15], page[16], page[17]]); - let seq = u32::from_le_bytes([page[18], page[19], page[20], page[21]]); - let lacing = page[27..27 + nseg].to_vec(); - let body_off = pos + 27 + nseg as u64; - // a beginning-of-stream page for a serial already seen starts the next link of a chained - // file (RFC 3533 §4), which may reuse the serial; one that carries on the page sequence of - // a stream with no end-of-stream page yet is a stray flag in that stream - if flags & 0x02 != 0 - && let Some(&si) = by_serial.get(&serial) - { - let st = &streams[si]; - if !st.saw_eos && st.next_seq == Some(seq) { - warnings.damage(|| format!("stray beginning-of-stream flag on page at byte {pos}, read as part of stream {serial}")); - } else { - if !st.saw_eos { - warnings.damage(|| format!("stream {serial} starts again at byte {pos} before its end-of-stream page")); - } - by_serial.remove(&serial); - if partial.remove(&serial).is_some() { - warnings.damage(|| format!("incomplete packet before page at byte {pos}")); - } - } - } - let si = *by_serial.entry(serial).or_insert_with(|| { - streams.push(Stream { - serial, - codec: Codec::Unknown, - headers: Vec::new(), - packets: Vec::new(), - pages: 0, - last_granule: None, - saw_eos: false, - header_count: 1, - header_bytes: 0, - next_seq: None, - }); - streams.len() - 1 - }); - let st = &mut streams[si]; - // a gap in the page sequence numbers is a lost page: a packet it continued is incomplete - if st.next_seq.is_some_and(|n| n != seq) { - warnings.damage(|| format!("pages missing before page at byte {pos}")); - partial.remove(&serial); - } - st.next_seq = Some(seq.wrapping_add(1)); - let page_index = st.pages; - st.pages += 1; - if flags & 0x04 != 0 { - st.saw_eos = true; - } - // a page that does not continue a pending packet (a page was lost): drop the packet - let continued = flags & 0x01 != 0; - if !continued && partial.remove(&serial).is_some() { - warnings.damage(|| format!("incomplete packet before page at byte {pos}")); - } - let mut completed: Vec = Vec::new(); - let mut off = 0u64; - let mut seg_start = 0u64; - // a continued page without a pending packet (a page was lost): drop the fragment - let mut skip_fragment = continued && !partial.contains_key(&serial); - for (k, &l) in lacing.iter().enumerate() { - off += l as u64; - if l < 255 || k + 1 == nseg { - let (a, n) = (seg_start, off - seg_start); - seg_start = off; - if skip_fragment { - if l < 255 { - skip_fragment = false; - } - continue; - } - let p = partial.entry(serial).or_insert_with(|| Partial { parts: Vec::new(), size: 0, prefix: Vec::new() }); - if n > 0 { - let Some(size) = p.size.checked_add(n as u32) else { - warnings.push(format!("packet over 4 GiB dropped at byte {pos}")); - partial.remove(&serial); - skip_fragment = l == 255; - continue; - }; - p.parts.push((body_off + a, n as u32)); - p.size = size; - let s = (body_off - pos + a) as usize; - let need = 2usize.saturating_sub(p.prefix.len()).min(n as usize); - p.prefix.extend_from_slice(&page[s..s + need]); - } - if l < 255 - && let Some(p) = partial.remove(&serial) - { - let mut prefix = [0u8; 2]; - prefix[..p.prefix.len().min(2)].copy_from_slice(&p.prefix[..p.prefix.len().min(2)]); - completed.push(Packet { parts: p.parts, size: p.size, granule: None, page: page_index, eos: flags & 0x04 != 0, prefix }); - } - } - } - let Some(left) = packet_budget.checked_sub(completed.len()) else { - warnings.push(format!("stopped at byte {pos}: more packets than a file of this size can hold")); - break; - }; - packet_budget = left; - if granule != -1 { - st.last_granule = Some(granule); - if let Some(last) = completed.last_mut() { - last.granule = Some(granule); - } - } - for pk in completed { - st.add_packet(src, pk, &mut warnings)?; - } - pos += page_len; - } - if !found_any { + let packet_budget = usize::try_from(len / FILE_BYTES_PER_PACKET).unwrap_or(usize::MAX).clamp(MIN_PACKET_ALLOWANCE, MAX_PACKETS); + let mut demux = Demux::new(len, Some(packet_budget)); + while demux.next_page(src, u64::MAX)?.is_some() {} + if !demux.found_any { return Err(Error::NotOgg); } - if !partial.is_empty() { - warnings.push("file ends inside a packet".into()); + demux.end_warnings(); + Ok(OggFile { streams: demux.streams, warnings: demux.warnings.finish() }) +} + +/// The page reader behind [`open`], [`probe`] and [`PacketReader`]: it reads one page at a time +/// and files the packets the page completes with their stream. +struct Demux { + len: u64, + streams: Vec, + by_serial: HashMap, + partial: HashMap, + warnings: Warnings, + /// Where the next page is looked for. + pos: u64, + found_any: bool, + recovery: Recovery, + /// Packets that may still be completed, or `None` when there is no cap (`PacketReader` keeps + /// no data packets). + packet_budget: Option, + /// The last page read had the beginning-of-stream flag. + last_bos: bool, + /// No page follows: the source ended, or a budget ran out. + ended: bool, + hdr: [u8; 27 + 255], + page: Vec, + completed: Vec, +} + +impl Demux { + fn new(len: u64, packet_budget: Option) -> Demux { + Demux { + len, + streams: Vec::new(), + by_serial: HashMap::new(), + partial: HashMap::new(), + warnings: Warnings::default(), + pos: 0, + found_any: false, + recovery: Recovery::new(len), + packet_budget, + last_bos: false, + ended: false, + hdr: [0; 27 + 255], + page: Vec::new(), + completed: Vec::new(), + } + } + + /// Every stream begun so far has all its header packets, and the last page read began no + /// stream (RFC 3533 §4 puts the beginning-of-stream pages of a link before its other pages). + fn headers_read(&self) -> bool { + self.found_any && !self.last_bos && self.streams.iter().all(Stream::headers_complete) + } + + /// The warnings for the end of the source: a packet left incomplete, and the count of damaged + /// regions not listed. + fn end_warnings(&mut self) { + if !self.partial.is_empty() { + self.warnings.push("file ends inside a packet".into()); + self.partial.clear(); + } + self.warnings.close(); + } + + /// Read the next good page that starts before `stop` and file the packets it completes. + /// Returns the page's stream and how many data packets it added to the end of that stream's + /// `packets`, or `None` when no page follows (`ended` is then set) or the next page would start + /// at or after `stop` (a later call goes on from `stop`). + fn next_page(&mut self, src: &(impl ByteSource + ?Sized), stop: u64) -> Result> { + let len = self.len; + while !self.ended && self.pos + 27 <= len { + let pos = self.pos; + if pos >= stop { + return Ok(None); + } + let hdr = &mut self.hdr; + src.read_at(pos, &mut hdr[..27])?; + if !self.recovery.charge(pos, pos + 27) { + self.warnings.push(past_budget(pos)); + break; + } + if &hdr[..4] != b"OggS" || hdr[4] != 0 { + // the scan looks at capture patterns that start before `stop` + let scan_end = len.min(stop.saturating_add(3)); + match find_capture(src, pos + 1, scan_end, &mut self.recovery)? { + Capture::At(p) => { + if self.found_any { + self.warnings.damage(|| format!("lost sync at byte {pos}; resumed at {p}")); + } + self.pos = p; + continue; + } + Capture::End if scan_end < len => { + self.pos = stop.max(pos + 1); + return Ok(None); + } + Capture::End => break, + Capture::BudgetSpent => { + self.warnings.push(past_budget(pos)); + break; + } + } + } + let nseg = hdr[26] as usize; + let head = 27 + nseg; + let page_len = if pos + head as u64 <= len { + src.read_at(pos + 27, &mut hdr[27..head])?; + head as u64 + hdr[27..head].iter().map(|&b| b as u64).sum::() + } else { + u64::MAX + }; + let fits = pos.saturating_add(page_len) <= len; + // the lacing values and the body: fake page headers a few bytes apart would otherwise + // each have their overlapping bodies read and hashed for free + if !self.recovery.charge(pos + 27, if fits { pos + page_len } else { (pos + head as u64).min(len) }) { + self.warnings.push(past_budget(pos)); + break; + } + if !fits { + // truncated, or a damaged lacing value: look for a page further on + self.warnings.damage(|| format!("page at byte {pos} runs past the end of the file")); + self.pos += 1; + continue; + } + let page = &mut self.page; + page.clear(); + page.resize(page_len as usize, 0); + page[..head].copy_from_slice(&hdr[..head]); + src.read_at(pos + head as u64, &mut page[head..])?; + let stored_crc = u32::from_le_bytes([page[22], page[23], page[24], page[25]]); + page[22..26].fill(0); + if crc32(page) != stored_crc { + self.warnings.damage(|| format!("bad CRC on page at byte {pos}")); + self.pos += 1; + continue; + } + self.found_any = true; + let flags = page[5]; + self.last_bos = flags & 0x02 != 0; + let granule = i64::from_le_bytes(page[6..14].try_into().unwrap_or([0; 8])); + let serial = u32::from_le_bytes([page[14], page[15], page[16], page[17]]); + let seq = u32::from_le_bytes([page[18], page[19], page[20], page[21]]); + let lacing = &hdr[27..head]; + let body_off = pos + 27 + nseg as u64; + let (streams, by_serial, partial, warnings) = (&mut self.streams, &mut self.by_serial, &mut self.partial, &mut self.warnings); + // a beginning-of-stream page for a serial already seen starts the next link of a chained + // file (RFC 3533 §4), which may reuse the serial; one that carries on the page sequence of + // a stream with no end-of-stream page yet is a stray flag in that stream + if flags & 0x02 != 0 + && let Some(&si) = by_serial.get(&serial) + { + let st = &streams[si]; + if !st.saw_eos && st.next_seq == Some(seq) { + warnings.damage(|| format!("stray beginning-of-stream flag on page at byte {pos}, read as part of stream {serial}")); + } else { + if !st.saw_eos { + warnings.damage(|| format!("stream {serial} starts again at byte {pos} before its end-of-stream page")); + } + by_serial.remove(&serial); + if partial.remove(&serial).is_some() { + warnings.damage(|| format!("incomplete packet before page at byte {pos}")); + } + } + } + let si = *by_serial.entry(serial).or_insert_with(|| { + streams.push(Stream { + serial, + codec: Codec::Unknown, + headers: Vec::new(), + packets: Vec::new(), + pages: 0, + last_granule: None, + saw_eos: false, + header_count: 1, + header_bytes: 0, + next_seq: None, + started: false, + }); + streams.len() - 1 + }); + let st = &mut streams[si]; + // a gap in the page sequence numbers is a lost page: a packet it continued is incomplete + if st.next_seq.is_some_and(|n| n != seq) { + warnings.damage(|| format!("pages missing before page at byte {pos}")); + partial.remove(&serial); + } + st.next_seq = Some(seq.wrapping_add(1)); + let page_index = st.pages; + st.pages += 1; + if flags & 0x04 != 0 { + st.saw_eos = true; + } + // a page that does not continue a pending packet (a page was lost): drop the packet + let continued = flags & 0x01 != 0; + if !continued && partial.remove(&serial).is_some() { + warnings.damage(|| format!("incomplete packet before page at byte {pos}")); + } + let completed = &mut self.completed; + completed.clear(); + let mut off = 0u64; + let mut seg_start = 0u64; + // a continued page without a pending packet (a page was lost): drop the fragment + let mut skip_fragment = continued && !partial.contains_key(&serial); + for (k, &l) in lacing.iter().enumerate() { + off += l as u64; + if l < 255 || k + 1 == nseg { + let (a, n) = (seg_start, off - seg_start); + seg_start = off; + if skip_fragment { + if l < 255 { + skip_fragment = false; + } + continue; + } + let p = partial.entry(serial).or_insert_with(|| Partial { parts: Vec::new(), size: 0, prefix: Vec::new() }); + if n > 0 { + let Some(size) = p.size.checked_add(n as u32) else { + warnings.push(format!("packet over 4 GiB dropped at byte {pos}")); + partial.remove(&serial); + skip_fragment = l == 255; + continue; + }; + p.parts.push((body_off + a, n as u32)); + p.size = size; + let s = (body_off - pos + a) as usize; + let need = 2usize.saturating_sub(p.prefix.len()).min(n as usize); + p.prefix.extend_from_slice(&page[s..s + need]); + } + if l < 255 + && let Some(p) = partial.remove(&serial) + { + let mut prefix = [0u8; 2]; + prefix[..p.prefix.len().min(2)].copy_from_slice(&p.prefix[..p.prefix.len().min(2)]); + completed.push(Packet { parts: p.parts, size: p.size, granule: None, page: page_index, eos: flags & 0x04 != 0, prefix }); + } + } + } + if let Some(budget) = self.packet_budget { + let Some(left) = budget.checked_sub(completed.len()) else { + warnings.push(format!("stopped at byte {pos}: more packets than a file of this size can hold")); + break; + }; + self.packet_budget = Some(left); + } + if granule != -1 { + st.last_granule = Some(granule); + if let Some(last) = completed.last_mut() { + last.granule = Some(granule); + } + } + let before = st.packets.len(); + for pk in completed.drain(..) { + st.add_packet(src, pk, warnings)?; + } + self.pos += page_len; + return Ok(Some((si, st.packets.len() - before))); + } + self.ended = true; + Ok(None) + } +} + +/// The streams of an Ogg file from its first pages only: each stream's codec and header packets, +/// for a player that starts before the rest of the file is read. +/// +/// Reading stops once every stream that begins at the start of the file has all its header +/// packets, after [`PROBE_PACKETS`] data packets, at the first page that would start after +/// [`PROBE_BYTES`] (the search past damage stops there too), or at the end of the file. Fails with +/// [`Error::NotOgg`] when no good page starts in the first `PROBE_BYTES`. `packets` holds only the data packets completed on the pages read, and `pages` and +/// `last_granule` count only those pages. Pages are read as [`open`] reads them (CRC-32 checked, +/// damage skipped). +pub fn probe(src: &(impl ByteSource + ?Sized)) -> Result { + let PacketReader { mut demux, queue, .. } = PacketReader::new(src)?; + for (s, p) in queue { + demux.streams[s].packets.push(p); + } + Ok(OggFile { streams: demux.streams, warnings: demux.warnings.finish() }) +} + +/// The most data packets [`PacketReader::new`] and [`probe`] hold while they wait for header +/// packets. +pub const PROBE_PACKETS: usize = 1 << 16; +/// The bytes of file after which [`PacketReader::new`] and [`probe`] stop waiting for header +/// packets: room for two streams with the largest headers kept. +pub const PROBE_BYTES: u64 = 2 * MAX_HEADER_BYTES as u64; + +/// Reads the packets of an Ogg file in file order, a page at a time, without first indexing the +/// whole file as [`open`] does. +/// +/// [`new`](PacketReader::new) reads the first pages, as [`probe`] does, so [`streams`](PacketReader::streams) +/// gives each stream's codec and header packets before the first data packet is read. +/// [`next_packet`](PacketReader::next_packet) then returns the data packets of every stream in the +/// order they complete in the file. Header packets are not returned: they stay in `streams`, where +/// the later links of a chained file appear as new streams when their pages are reached. Data +/// packets are not kept, so `Stream::packets` stays empty and memory does not grow with the file. +/// Damaged pages are skipped as in [`open`], with the same recovery budget and warnings; the cap +/// on kept packets does not apply. +pub struct PacketReader { + src: S, + demux: Demux, + /// Data packets completed and not yet returned, with their stream. + queue: VecDeque<(usize, Packet)>, + /// The end-of-source warnings have been added. + closed: bool, +} + +impl PacketReader { + /// Read the first pages of `src`: see [`probe`] for where reading stops. Fails with + /// [`Error::NotOgg`] when no good page starts in the first [`PROBE_BYTES`] of the file. + pub fn new(src: S) -> Result> { + let mut r = PacketReader { demux: Demux::new(src.len(), None), src, queue: VecDeque::new(), closed: false }; + while !r.demux.headers_read() && r.queue.len() < PROBE_PACKETS && r.fill(PROBE_BYTES)? {} + if !r.demux.found_any { + return Err(Error::NotOgg); + } + Ok(r) + } + + /// The streams read so far, with their codecs and header packets. `packets` is empty. + pub fn streams(&self) -> &[Stream] { + &self.demux.streams + } + + /// Warnings about the pages read so far (damage skipped, an incomplete packet at the end). + pub fn warnings(&self) -> &[String] { + &self.demux.warnings.list + } + + /// The next data packet in file order: its stream (an index into + /// [`streams`](PacketReader::streams)) and its place in the file, with its bytes in `buf`, + /// which is cleared first and reused. `None` at the end of the file. + pub fn next_packet(&mut self, buf: &mut Vec) -> Result> { + loop { + if let Some((_, p)) = self.queue.front() { + read_parts_into(&self.src, &p.parts, usize::MAX, buf)?; + return Ok(self.queue.pop_front()); + } + if !self.fill(u64::MAX)? { + return Ok(None); + } + } + } + + /// Read one more page that starts before `stop` and queue its data packets; false at the end + /// of the source or at `stop`. + fn fill(&mut self, stop: u64) -> Result { + match self.demux.next_page(&self.src, stop)? { + Some((si, added)) => { + let packets = &mut self.demux.streams[si].packets; + let from = packets.len() - added; + self.queue.extend(packets.drain(from..).map(|p| (si, p))); + Ok(true) + } + None if !self.demux.ended => Ok(false), + None => { + if !self.closed { + self.closed = true; + self.demux.end_warnings(); + } + Ok(false) + } + } } - Ok(OggFile { streams, warnings: warnings.finish() }) } fn past_budget(pos: u64) -> String { @@ -714,21 +919,29 @@ fn find_capture(src: &(impl ByteSource + ?Sized), from: u64, len: u64, recovery: /// The first `max` bytes of a packet's parts. fn read_parts(src: &(impl ByteSource + ?Sized), parts: &[(u64, u32)], max: usize) -> Result> { + let mut v = Vec::new(); + read_parts_into(src, parts, max, &mut v)?; + Ok(v) +} + +/// The first `max` bytes of a packet's parts, in `buf` (cleared first). +fn read_parts_into(src: &(impl ByteSource + ?Sized), parts: &[(u64, u32)], max: usize, buf: &mut Vec) -> Result<()> { + buf.clear(); // Ranges come from a scan of some source; check them against this one before sizing a buffer. let len = src.len(); if parts.iter().any(|&(o, n)| o.checked_add(u64::from(n)).is_none_or(|end| end > len)) { return Err(Error::Invalid("packet range lies outside the source".into())); } - let mut v = Vec::with_capacity(parts.iter().map(|p| p.1 as usize).sum::().min(max)); + buf.reserve(parts.iter().map(|p| p.1 as usize).sum::().min(max)); for &(o, n) in parts { - let a = v.len(); + let a = buf.len(); if a == max { break; } - v.resize(a + (n as usize).min(max - a), 0); - src.read_at(o, &mut v[a..])?; + buf.resize(a + (n as usize).min(max - a), 0); + src.read_at(o, &mut buf[a..])?; } - Ok(v) + Ok(()) } impl OggFile { @@ -738,8 +951,15 @@ impl OggFile { } /// The bytes of packet `i` of stream `s`. pub fn read_packet(&self, src: &(impl ByteSource + ?Sized), s: usize, i: usize) -> Result> { + let mut v = Vec::new(); + self.read_packet_into(src, s, i, &mut v)?; + Ok(v) + } + /// The bytes of packet `i` of stream `s`, in `buf`, which is cleared first and reused: one + /// buffer serves every packet of a file. + pub fn read_packet_into(&self, src: &(impl ByteSource + ?Sized), s: usize, i: usize, buf: &mut Vec) -> Result<()> { let p = self.streams.get(s).and_then(|st| st.packets.get(i)).ok_or_else(|| Error::Invalid(format!("no packet {i} in stream {s}")))?; - read_parts(src, &p.parts, usize::MAX) + read_parts_into(src, &p.parts, usize::MAX, buf) } } diff --git a/crates/media/src/ogg/tests.rs b/crates/media/src/ogg/tests.rs index f827648b1f..6617c8e2db 100644 --- a/crates/media/src/ogg/tests.rs +++ b/crates/media/src/ogg/tests.rs @@ -781,3 +781,251 @@ fn largest_trusted_granule_with_a_huge_pre_skip_stays_in_range() { // the end (2^62) lies before the shift, so nothing is playable assert_eq!(t.total, 0); } + +/// A data packet from a `PacketReader`: its stream, the packet and its bytes. +type ReadPacket = (usize, Packet, Vec); + +/// Every data packet a `PacketReader` returns, and the reader after the end of the file. +fn read_all(src: S) -> (Vec, PacketReader) { + let mut r = PacketReader::new(src).unwrap(); + let mut out = Vec::new(); + let mut buf = Vec::new(); + while let Some((s, p)) = r.next_packet(&mut buf).unwrap() { + out.push((s, p, buf.clone())); + } + (out, r) +} + +/// The reader gives the streams, packets and warnings `open` gives, and keeps no packets. +fn assert_reader_matches_open(f: &[u8]) { + let o = open(f).unwrap(); + let (got, r) = read_all(f); + assert_eq!(r.streams().len(), o.streams.len()); + for (s, (rs, os)) in r.streams().iter().zip(&o.streams).enumerate() { + assert_eq!((rs.serial, rs.codec, &rs.headers, rs.pages, rs.saw_eos), (os.serial, os.codec, &os.headers, os.pages, os.saw_eos)); + assert!(rs.packets.is_empty()); + let mine: Vec<&ReadPacket> =got.iter().filter(|g| g.0 == s).collect(); + assert_eq!(mine.len(), os.packets.len(), "stream {s}"); + for (i, (g, p)) in mine.iter().zip(&os.packets).enumerate() { + assert_eq!(&g.1, p, "stream {s} packet {i}"); + assert_eq!(g.2, o.read_packet(f, s, i).unwrap(), "stream {s} packet {i}"); + } + } + // file order: each packet lies after the one before it + assert!(got.windows(2).all(|w| w[0].1.parts.last().map(|p| p.0) < w[1].1.parts.last().map(|p| p.0))); + assert_eq!(r.warnings(), o.warnings); +} + +/// Opus header pages of two streams with their beginning-of-stream pages first, then one data +/// page of each in turn. +fn two_streams(npk: usize) -> Vec { + let mut f = Vec::new(); + let head = opus_head(0); + let (l, b) = lace(&[&head], false); + page(&mut f, 0x02, 0, 1, 0, &l, &b); + page(&mut f, 0x02, 0, 2, 0, &l, &b); + let (l, b) = lace(&[b"OpusTags"], false); + page(&mut f, 0, 0, 1, 1, &l, &b); + // a data page of stream 1 before the last header page of stream 2 + let p = pkt(0, 30); + let (lp, bp) = lace(&[&p], false); + page(&mut f, 0, 960, 1, 2, &lp, &bp); + page(&mut f, 0, 0, 2, 1, &l, &b); + for i in 1..npk { + for serial in [1, 2] { + let p = pkt(i * serial as usize, 30 + i % 7); + let (l, b) = lace(&[&p], false); + let last = i + 1 == npk; + page(&mut f, if last { 0x04 } else { 0 }, (i as i64 + 1) * 960, serial, i as u32 + if serial == 1 { 2 } else { 1 }, &l, &b); + } + } + f +} + +#[test] +fn probe_reads_only_the_header_pages() { + let mut f = Vec::new(); + opus_pages(&mut f, 3, 400, 6000, true); + let starts = page_starts(&f); + let src = Counted(f, Default::default()); + let o = probe(&src).unwrap(); + assert!(o.warnings.is_empty(), "{:?}", o.warnings); + let st = &o.streams[0]; + assert_eq!((st.codec, st.headers.len(), st.packets.len(), st.pages), (Codec::Opus, 2, 0, 2)); + assert_eq!(st.codec_params(), open(&src.0).unwrap().streams[0].codec_params()); + // the two header pages and their packets (19 and 16 bytes) once more, and nothing of the + // 2.4 MB after them + assert_eq!(src.1.get(), starts[2] as u64 + 19 + 16, "{} of {} bytes read", src.1.get(), src.len()); +} + +#[test] +fn probe_waits_for_the_headers_of_every_stream() { + let f = two_streams(50); + let src = Counted(f, Default::default()); + let o = probe(&src).unwrap(); + assert_eq!(o.streams.len(), 2); + for st in &o.streams { + assert_eq!((st.codec, st.headers.len()), (Codec::Opus, 2)); + } + // the data packet before stream 2's last header page is kept, and reading stops there + assert_eq!((o.streams[0].packets.len(), o.streams[1].packets.len()), (1, 0)); + assert_eq!(o.read_packet(&src.0, 0, 0).unwrap(), pkt(0, 30)); + assert!(src.1.get() < src.len() / 10, "{} of {} bytes read", src.1.get(), src.len()); + // a file of beginning-of-stream pages only, and no Ogg at all + let mut g = Vec::new(); + let (l, b) = lace(&[&opus_head(0)], false); + page(&mut g, 0x02, 0, 1, 0, &l, &b); + assert_eq!(probe(&g).unwrap().streams[0].headers.len(), 1); + assert!(matches!(probe(&b"not ogg at all, no capture pattern".to_vec()), Err(Error::NotOgg))); + assert!(matches!(PacketReader::new(&b"OggS but nothing after it".to_vec()), Err(Error::NotOgg))); +} + +#[test] +fn probe_stops_waiting_after_probe_packets() { + // stream 2 begins with a page that completes no packet and never has another, while stream 1 + // has a page of 255 empty data packets after another + let mut f = Vec::new(); + let (l, b) = lace(&[&opus_head(0)], false); + page(&mut f, 0x02, 0, 1, 0, &l, &b); + page(&mut f, 0x02, 0, 2, 0, &[], &[]); + let (l, b) = lace(&[b"OpusTags"], false); + page(&mut f, 0, 0, 1, 1, &l, &b); + for seq in 2..(PROBE_PACKETS / 255 + 40) as u32 { + page(&mut f, 0, -1, 1, seq, &[0; 255], &[]); + } + let src = Counted(f, Default::default()); + let o = probe(&src).unwrap(); + assert!(o.streams[1].headers.is_empty()); + let held = o.streams[0].packets.len(); + assert!((PROBE_PACKETS..PROBE_PACKETS + 255).contains(&held), "{held}"); + assert!(src.1.get() < src.len(), "{} of {} bytes read", src.1.get(), src.len()); +} + +#[test] +fn a_stop_offset_bounds_the_search_past_damage() { + // 3000 bytes of junk, then a file: a page search with a stop at byte 500 reads no further + // than the patterns that start before it, and the next search goes on from there + let mut f = vec![b'j'; 3000]; + f.extend(opus_file(4, 0, 0)); + let src = Counted(f, Default::default()); + let mut d = Demux::new(src.len(), None); + assert!(d.next_page(&src, 500).unwrap().is_none()); + assert!(!d.ended && !d.found_any && d.pos == 500, "{} {} {}", d.ended, d.found_any, d.pos); + // the first header, then the scan to byte 503 in two reads that overlap by 3 bytes + assert_eq!(src.1.get(), 27 + 502 + 3, "{} bytes read", src.1.get()); + assert_eq!(d.next_page(&src, u64::MAX).unwrap(), Some((0, 0))); + assert_eq!(d.pos, 3000 + page_starts(&src.0[3000..])[1] as u64); + // pages that fail their CRC stop at the offset too + let mut f = Vec::new(); + opus_pages(&mut f, 3, 40, 100, true); + let starts = page_starts(&f); + for &s in &starts[..30] { + f[s + 30] ^= 0xFF; + } + let mut d = Demux::new(f.len() as u64, None); + assert!(d.next_page(&f, starts[10] as u64).unwrap().is_none()); + assert!(!d.ended && d.pos == starts[10] as u64); + // the first good page holds one packet, read as the stream's first header + assert_eq!(d.next_page(&f, u64::MAX).unwrap(), Some((0, 0))); + assert_eq!(d.pos, starts[31] as u64); +} + +#[test] +fn packet_reader_returns_what_open_indexes() { + assert_reader_matches_open(&opus_file(10, 312, 500)); + assert_reader_matches_open(&two_streams(40)); + // packets across pages, and a lost page in the middle of one + let mut f = Vec::new(); + let (l, b) = lace(&[&opus_head(0)], false); + page(&mut f, 0x02, 0, 1, 0, &l, &b); + let (l, b) = lace(&[b"OpusTags"], false); + page(&mut f, 0, 0, 1, 1, &l, &b); + let big = pkt(0, 600); + page(&mut f, 0, -1, 1, 2, &[255], &big[..255]); + page(&mut f, 0x01, -1, 1, 3, &[255], &big[255..510]); + let (l, b) = lace(&[&big[510..], &pkt(1, 30)], false); + page(&mut f, 0x01, 1920, 1, 4, &l, &b); + let (l, b) = lace(&[&pkt(2, 700)], false); + page(&mut f, 0x04, 2880, 1, 5, &l, &b); + assert_reader_matches_open(&f); + let mut g = f.clone(); + g[page_starts(&f)[3] + 40] ^= 0xFF; + assert_reader_matches_open(&g); + // chained links that reuse a serial, then a file cut inside a packet + let mut f = Vec::new(); + opus_pages(&mut f, 0, 3, 40, true); + opus_pages(&mut f, 0, 3, 40, true); + assert_reader_matches_open(&f); + assert_reader_matches_open(&f[..f.len() - 10]); + // damage on every other page, more than the damage warnings listed: the same pages are + // skipped with the same warnings and the same closing count + let mut f = Vec::new(); + opus_pages(&mut f, 3, 3000, 40, true); + let starts = page_starts(&f); + for k in (2..3002).step_by(2) { + f[starts[k] + 30] ^= 0xFF; + } + assert_reader_matches_open(&f); +} + +#[test] +fn packet_reader_keeps_no_packets_and_has_no_packet_cap() { + // the file of `empty_packets_are_capped_by_the_file_size`, where open stops at its packet cap + let mut f = Vec::new(); + let (l, b) = lace(&[&opus_head(0)], false); + page(&mut f, 0x02, 0, 1, 0, &l, &b); + let pages = MIN_PACKET_ALLOWANCE / 255 + 10; + for seq in 1..=pages as u32 { + page(&mut f, 0, -1, 1, seq, &[0; 255], &[]); + } + let mut r = PacketReader::new(&f).unwrap(); + let mut buf = vec![1; 8]; + let mut n = 0; + while let Some((s, p)) = r.next_packet(&mut buf).unwrap() { + assert_eq!((s, p.size, buf.len()), (0, 0, 0)); + n += 1; + } + // the first empty packet is the second Opus header + assert_eq!((n, r.streams()[0].headers.len()), (255 * pages - 1, 2)); + assert!(r.streams()[0].packets.is_empty()); + assert!(r.warnings().is_empty(), "{:?}", r.warnings()); + assert!(r.next_packet(&mut buf).unwrap().is_none()); +} + +#[test] +fn packet_reader_files_a_first_packet_too_large_for_a_header_once() { + // a first packet over MAX_HEADER_BYTES is data, so the next packet must not be taken for the + // first one and its codec + let size = MAX_HEADER_BYTES + 1; + let first: Vec = (0..size).map(|k| (k % 251) as u8).collect(); + let mut f = Vec::new(); + let page_body = 255 * 255; + let full = size / page_body; + for (seq, chunk) in first[..full * page_body].chunks(page_body).enumerate() { + page(&mut f, if seq == 0 { 0x02 } else { 0x01 }, -1, 5, seq as u32, &[255; 255], chunk); + } + let (l, b) = lace(&[&first[full * page_body..]], false); + page(&mut f, 0x01, -1, 5, full as u32, &l, &b); + let head = opus_head(0); + let (l, b) = lace(&[&head, &b"x"[..]], false); + page(&mut f, 0x04, 0, 5, full as u32 + 1, &l, &b); + let o = open(&f).unwrap(); + assert_eq!((o.streams[0].codec, o.streams[0].headers.len(), o.streams[0].packets.len()), (Codec::Unknown, 0, 3)); + let (got, r) = read_all(&f); + assert_eq!((r.streams()[0].codec, r.streams()[0].headers.len()), (Codec::Unknown, 0)); + assert_eq!(got.len(), 3); + assert!(got[0].2 == first && got[1].2 == head && got[2].2 == b"x"); +} + +#[test] +fn read_packet_into_reuses_one_buffer() { + let f = opus_file(10, 312, 500); + let o = open(&f).unwrap(); + let mut buf = Vec::new(); + o.read_packet_into(&f, 0, 4, &mut buf).unwrap(); + assert_eq!(buf, pkt(4, 44)); + let at = buf.as_ptr(); + o.read_packet_into(&f, 0, 0, &mut buf).unwrap(); + assert_eq!((buf.as_slice(), buf.as_ptr()), (pkt(0, 40).as_slice(), at)); + assert!(matches!(o.read_packet_into(&f, 0, 10, &mut buf), Err(Error::Invalid(_)))); +} From d7823013639a7dc7f0d95fff40b2052b421302f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:47:30 -0800 Subject: [PATCH 2/2] craft-media: Ogg reader resumes after a failed header read and reports lost sync across the probe stop - A read that fails while a page's packets are filed leaves the rest of them queued, and the next call files them, so a retry no longer files a header twice or takes the next header for data. Stream::header_data does the read before add_packet changes anything. - A search past damage that stops at the probe offset keeps where sync was lost, and the warning names that byte when the search goes on. - headers_read checks a count of streams still waiting for headers instead of every stream on each page. A stream that a new link with its serial replaces is no longer waited for, so the probe stops after the new link's header pages. - The reader test checks file order from the pages packets complete on, so a packet completed by a zero lacing value is placed correctly. - The docs of PROBE_PACKETS and PacketReader state the page-sized overshoot, the streams that can lack headers after the probe, and the stream headers that stay in memory. --- crates/media/src/ogg/mod.rs | 149 ++++++++++++++++++++++++-------- crates/media/src/ogg/tests.rs | 155 +++++++++++++++++++++++++++++++++- 2 files changed, 265 insertions(+), 39 deletions(-) diff --git a/crates/media/src/ogg/mod.rs b/crates/media/src/ogg/mod.rs index 3986ac10f3..87611cc4c2 100644 --- a/crates/media/src/ogg/mod.rs +++ b/crates/media/src/ogg/mod.rs @@ -337,28 +337,47 @@ impl Stream { } impl Stream { - /// File a completed packet: the first one sets the codec and how many headers follow it, then - /// header packets are read in, and the rest are audio. - fn add_packet(&mut self, src: &(impl ByteSource + ?Sized), pk: Packet, warnings: &mut Warnings) -> Result<()> { + /// The bytes [`add_packet`](Stream::add_packet) needs of the next completed packet: all of a + /// header packet, the start of a first packet too large to be one, or none for a data packet. + /// It changes nothing, so a read that fails can be tried again. + fn header_data(&self, src: &(impl ByteSource + ?Sized), pk: &Packet) -> Result>> { let size = pk.size as usize; - // the first packet is read once: for its codec, and then as a header (a packet too large - // to be one is only read as far as the codec needs) - let mut first = None; // `PacketReader` takes data packets out of `packets`, so empty lists do not mark the first + if !self.started { + return read_parts(src, &pk.parts, if size <= MAX_HEADER_BYTES { size } else { FIRST_PACKET_PREFIX }).map(Some); + } + if self.headers.len() >= self.header_count + || !self.packets.is_empty() + || self.headers.len() >= MAX_HEADERS + || self.header_bytes.saturating_add(size) > MAX_HEADER_BYTES + { + return Ok(None); + } + read_parts(src, &pk.parts, size).map(Some) + } + + /// File a completed packet with what [`header_data`](Stream::header_data) read of it: the + /// first one sets the codec and how many headers follow it, then header packets are kept, and + /// the rest are audio. + fn add_packet(&mut self, pk: Packet, data: Option>, warnings: &mut Warnings) { + let size = pk.size as usize; + let mut data = data; + // the first packet is read once: for its codec, and then as a header (a packet too large + // to be one is only read as far as the codec needs) if !self.started { self.started = true; - let data = read_parts(src, &pk.parts, if size <= MAX_HEADER_BYTES { size } else { FIRST_PACKET_PREFIX })?; - self.codec = Codec::of(&data); + let first = data.take().unwrap_or_default(); + self.codec = Codec::of(&first); self.header_count = match self.codec { - Codec::Flac => flac_header_count(&data), - Codec::Speex => speex_header_count(&data), + Codec::Flac => flac_header_count(&first), + Codec::Speex => speex_header_count(&first), c => c.header_count(), }; - first = Some(data).filter(|d| d.len() == size); + data = Some(first).filter(|d| d.len() == size); } if self.headers.len() >= self.header_count || !self.packets.is_empty() { self.packets.push(pk); - return Ok(()); + return; } // a count the file states (FLAC, Speex) or leaves open is capped, so a hostile first // packet cannot turn the audio into headers; a packet past the cap is not read @@ -366,11 +385,12 @@ impl Stream { warnings.push(format!("stream {}: header packets beyond {MAX_HEADERS} or {MAX_HEADER_BYTES} bytes read as data", self.serial)); self.header_count = self.headers.len(); self.packets.push(pk); - return Ok(()); + return; } - let data = match first { - Some(data) => data, - None => read_parts(src, &pk.parts, size)?, + // `header_data` read every packet that gets this far + let Some(data) = data else { + self.packets.push(pk); + return; }; if self.header_count == usize::MAX && !self.headers.is_empty() { // FLAC with an unstated count: metadata packets run to the one flagged last. A packet @@ -379,7 +399,7 @@ impl Stream { if !is_flac_metadata_block(&data) { self.header_count = self.headers.len(); self.packets.push(pk); - return Ok(()); + return; } if data[0] & 0x80 != 0 { self.header_count = self.headers.len() + 1; @@ -387,7 +407,6 @@ impl Stream { } self.header_bytes = self.header_bytes.saturating_add(data.len()); self.headers.push(data); - Ok(()) } /// Every header packet has been read: the next packet is data. @@ -535,11 +554,21 @@ struct Demux { packet_budget: Option, /// The last page read had the beginning-of-stream flag. last_bos: bool, + /// Streams that do not yet have all their header packets and can still get pages (a stream + /// that a new link with its serial replaced is not counted). + incomplete: usize, + /// Where sync was lost when a search past damage stopped at a stop offset, for the warning + /// once the search goes on and finds the next page. + lost_at: Option, /// No page follows: the source ended, or a budget ran out. ended: bool, hdr: [u8; 27 + 255], page: Vec, - completed: Vec, + /// The packets the last page read completed that are not yet filed with its stream. + completed: VecDeque, + /// The stream of the last page read and its count of data packets before the page, while + /// `completed` holds packets to file. + filing: Option<(usize, usize)>, } impl Demux { @@ -555,17 +584,46 @@ impl Demux { recovery: Recovery::new(len), packet_budget, last_bos: false, + incomplete: 0, + lost_at: None, ended: false, hdr: [0; 27 + 255], page: Vec::new(), - completed: Vec::new(), + completed: VecDeque::new(), + filing: None, } } - /// Every stream begun so far has all its header packets, and the last page read began no + /// Every stream begun so far that can still get pages has all its header packets, and the last page read began no /// stream (RFC 3533 §4 puts the beginning-of-stream pages of a link before its other pages). fn headers_read(&self) -> bool { - self.found_any && !self.last_bos && self.streams.iter().all(Stream::headers_complete) + self.found_any && !self.last_bos && self.incomplete == 0 + } + + /// File the packets in `completed` with the stream of the page that completed them, and + /// return that stream and how many data packets the page added to its `packets`. A read that + /// fails leaves the packet it failed on and the ones after it in `completed`, and the next + /// call files them. + fn file_completed(&mut self, src: &(impl ByteSource + ?Sized)) -> Result> { + let Some((si, before)) = self.filing else { + return Ok(None); + }; + let st = &mut self.streams[si]; + while let Some(pk) = self.completed.front() { + let data = st.header_data(src, pk)?; + let Some(pk) = self.completed.pop_front() else { + break; + }; + let was = st.headers_complete(); + st.add_packet(pk, data, &mut self.warnings); + match (was, st.headers_complete()) { + (false, true) => self.incomplete = self.incomplete.saturating_sub(1), + (true, false) => self.incomplete += 1, + _ => {} + } + } + self.filing = None; + Ok(Some((si, st.packets.len() - before))) } /// The warnings for the end of the source: a packet left incomplete, and the count of damaged @@ -581,8 +639,12 @@ impl Demux { /// Read the next good page that starts before `stop` and file the packets it completes. /// Returns the page's stream and how many data packets it added to the end of that stream's /// `packets`, or `None` when no page follows (`ended` is then set) or the next page would start - /// at or after `stop` (a later call goes on from `stop`). + /// at or after `stop` (a later call goes on from `stop`). After a read fails while the page's + /// packets are filed, the next call files the rest of them and returns that page. fn next_page(&mut self, src: &(impl ByteSource + ?Sized), stop: u64) -> Result> { + if self.filing.is_some() { + return self.file_completed(src); + } let len = self.len; while !self.ended && self.pos + 27 <= len { let pos = self.pos; @@ -600,22 +662,29 @@ impl Demux { let scan_end = len.min(stop.saturating_add(3)); match find_capture(src, pos + 1, scan_end, &mut self.recovery)? { Capture::At(p) => { + let lost = self.lost_at.take().unwrap_or(pos); if self.found_any { - self.warnings.damage(|| format!("lost sync at byte {pos}; resumed at {p}")); + self.warnings.damage(|| format!("lost sync at byte {lost}; resumed at {p}")); } self.pos = p; continue; } Capture::End if scan_end < len => { + self.lost_at.get_or_insert(pos); self.pos = stop.max(pos + 1); return Ok(None); } Capture::End => break, Capture::BudgetSpent => { - self.warnings.push(past_budget(pos)); + self.warnings.push(past_budget(self.lost_at.take().unwrap_or(pos))); break; } } + } else if let Some(lost) = self.lost_at.take() + && self.found_any + { + // the search stopped at the stop offset, and the next page starts there + self.warnings.damage(|| format!("lost sync at byte {lost}; resumed at {pos}")); } let nseg = hdr[26] as usize; let head = 27 + nseg; @@ -672,6 +741,10 @@ impl Demux { if !st.saw_eos { warnings.damage(|| format!("stream {serial} starts again at byte {pos} before its end-of-stream page")); } + // no page reaches the old stream again, so its missing headers are not waited for + if !st.headers_complete() { + self.incomplete = self.incomplete.saturating_sub(1); + } by_serial.remove(&serial); if partial.remove(&serial).is_some() { warnings.damage(|| format!("incomplete packet before page at byte {pos}")); @@ -692,6 +765,7 @@ impl Demux { next_seq: None, started: false, }); + self.incomplete += 1; streams.len() - 1 }); let st = &mut streams[si]; @@ -747,7 +821,7 @@ impl Demux { { let mut prefix = [0u8; 2]; prefix[..p.prefix.len().min(2)].copy_from_slice(&p.prefix[..p.prefix.len().min(2)]); - completed.push(Packet { parts: p.parts, size: p.size, granule: None, page: page_index, eos: flags & 0x04 != 0, prefix }); + completed.push_back(Packet { parts: p.parts, size: p.size, granule: None, page: page_index, eos: flags & 0x04 != 0, prefix }); } } } @@ -760,16 +834,13 @@ impl Demux { } if granule != -1 { st.last_granule = Some(granule); - if let Some(last) = completed.last_mut() { + if let Some(last) = completed.back_mut() { last.granule = Some(granule); } } - let before = st.packets.len(); - for pk in completed.drain(..) { - st.add_packet(src, pk, warnings)?; - } + self.filing = Some((si, st.packets.len())); self.pos += page_len; - return Ok(Some((si, st.packets.len() - before))); + return self.file_completed(src); } self.ended = true; Ok(None) @@ -793,8 +864,9 @@ pub fn probe(src: &(impl ByteSource + ?Sized)) -> Result { Ok(OggFile { streams: demux.streams, warnings: demux.warnings.finish() }) } -/// The most data packets [`PacketReader::new`] and [`probe`] hold while they wait for header -/// packets. +/// The count of held data packets at which [`PacketReader::new`] and [`probe`] stop waiting for +/// header packets. The count is checked before each page is read, and one page can complete up to +/// 255 packets, so up to 254 more than this can be held. pub const PROBE_PACKETS: usize = 1 << 16; /// The bytes of file after which [`PacketReader::new`] and [`probe`] stop waiting for header /// packets: room for two streams with the largest headers kept. @@ -804,11 +876,16 @@ pub const PROBE_BYTES: u64 = 2 * MAX_HEADER_BYTES as u64; /// whole file as [`open`] does. /// /// [`new`](PacketReader::new) reads the first pages, as [`probe`] does, so [`streams`](PacketReader::streams) -/// gives each stream's codec and header packets before the first data packet is read. +/// gives each stream's codec and header packets before the first data packet is read. When +/// reading stops at [`PROBE_PACKETS`] or [`PROBE_BYTES`], a stream can still lack header packets, +/// and a stream whose first packet has not completed has no headers and the codec +/// [`Codec::Unknown`]; `next_packet` files the missing headers as their pages are reached. /// [`next_packet`](PacketReader::next_packet) then returns the data packets of every stream in the /// order they complete in the file. Header packets are not returned: they stay in `streams`, where /// the later links of a chained file appear as new streams when their pages are reached. Data -/// packets are not kept, so `Stream::packets` stays empty and memory does not grow with the file. +/// packets are not kept, so `Stream::packets` stays empty and memory does not grow with the count +/// of data packets; each stream and its header packets stay in `streams`, so every link of a +/// chained file adds to it. After `next_packet` fails, a later call goes on from where it stopped. /// Damaged pages are skipped as in [`open`], with the same recovery budget and warnings; the cap /// on kept packets does not apply. pub struct PacketReader { diff --git a/crates/media/src/ogg/tests.rs b/crates/media/src/ogg/tests.rs index 6617c8e2db..d84c3032c2 100644 --- a/crates/media/src/ogg/tests.rs +++ b/crates/media/src/ogg/tests.rs @@ -804,15 +804,24 @@ fn assert_reader_matches_open(f: &[u8]) { for (s, (rs, os)) in r.streams().iter().zip(&o.streams).enumerate() { assert_eq!((rs.serial, rs.codec, &rs.headers, rs.pages, rs.saw_eos), (os.serial, os.codec, &os.headers, os.pages, os.saw_eos)); assert!(rs.packets.is_empty()); - let mine: Vec<&ReadPacket> =got.iter().filter(|g| g.0 == s).collect(); + let mine: Vec<&ReadPacket> = got.iter().filter(|g| g.0 == s).collect(); assert_eq!(mine.len(), os.packets.len(), "stream {s}"); for (i, (g, p)) in mine.iter().zip(&os.packets).enumerate() { assert_eq!(&g.1, p, "stream {s} packet {i}"); assert_eq!(g.2, o.read_packet(f, s, i).unwrap(), "stream {s} packet {i}"); } } - // file order: each packet lies after the one before it - assert!(got.windows(2).all(|w| w[0].1.parts.last().map(|p| p.0) < w[1].1.parts.last().map(|p| p.0))); + // file order: packets come in the order of the pages they complete on (from a walk of the + // pages), and within a page in their own order + let mut d = Demux::new(f.len() as u64, None); + let mut rank = HashMap::new(); + while let Some((s, _)) = d.next_page(f, u64::MAX).unwrap() { + rank.insert((s, d.streams[s].pages - 1), rank.len()); + d.streams[s].packets.clear(); + } + let mut want: Vec<(usize, &Packet)> = o.streams.iter().enumerate().flat_map(|(s, st)| st.packets.iter().map(move |p| (s, p))).collect(); + want.sort_by_key(|&(s, p)| rank[&(s, p.page)]); + assert!(got.iter().map(|g| (g.0, &g.1)).eq(want)); assert_eq!(r.warnings(), o.warnings); } @@ -880,6 +889,19 @@ fn probe_waits_for_the_headers_of_every_stream() { assert!(matches!(PacketReader::new(&b"OggS but nothing after it".to_vec()), Err(Error::NotOgg))); } +#[test] +fn probe_does_not_wait_for_a_stream_a_new_link_replaced() { + // stream 1 begins with a packet that never completes, then a new link reuses its serial: the + // probe stops after the new link's header pages + let mut f = Vec::new(); + page(&mut f, 0x02, -1, 1, 0, &[255], &[7; 255]); + opus_pages(&mut f, 1, 50, 40, true); + let o = probe(&f).unwrap(); + assert_eq!(o.streams.len(), 2); + assert!(o.streams[0].headers.is_empty()); + assert_eq!((o.streams[1].codec, o.streams[1].headers.len(), o.streams[1].packets.len()), (Codec::Opus, 2, 0)); +} + #[test] fn probe_stops_waiting_after_probe_packets() { // stream 2 begins with a page that completes no packet and never has another, while stream 1 @@ -966,6 +988,133 @@ fn packet_reader_returns_what_open_indexes() { f[starts[k] + 30] ^= 0xFF; } assert_reader_matches_open(&f); + // stream 1 begins a packet, stream 2 completes one, then stream 1 completes its packet with + // a zero lacing value: stream 2's packet comes first, though its bytes lie after stream 1's + let mut f = Vec::new(); + let (l, b) = lace(&[&opus_head(0)], false); + page(&mut f, 0x02, 0, 1, 0, &l, &b); + page(&mut f, 0x02, 0, 2, 0, &l, &b); + let (l, b) = lace(&[b"OpusTags"], false); + page(&mut f, 0, 0, 1, 1, &l, &b); + page(&mut f, 0, 0, 2, 1, &l, &b); + page(&mut f, 0, -1, 1, 2, &[255], &pkt(0, 255)); + let (l, b) = lace(&[&pkt(1, 30)], false); + page(&mut f, 0x04, 960, 2, 2, &l, &b); + page(&mut f, 0x01 | 0x04, 960, 1, 3, &[0], &[]); + assert_reader_matches_open(&f); +} + +/// A source that fails the first read starting at `at`. +struct FailOnce { + data: Vec, + at: u64, + armed: std::cell::Cell, +} + +impl ByteSource for FailOnce { + fn len(&self) -> u64 { + self.data.len() as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + if offset == self.at && self.armed.replace(false) { + return Err(io::Error::other("injected read failure")); + } + self.data.read_at(offset, buf) + } +} + +#[test] +fn a_read_that_fails_while_filing_headers_can_be_tried_again() { + // a chained file whose second link has both Opus headers on its first page; reading the second + // header fails once, after the first one is filed + let mut f = Vec::new(); + opus_pages(&mut f, 1, 2, 40, true); + let link = f.len(); + let head = opus_head(0); + let tags = b"OpusTags\x00\x00\x00\x00\x00\x00\x00\x00".to_vec(); + let (l, b) = lace(&[&head, &tags], false); + page(&mut f, 0x02, 0, 2, 0, &l, &b); + let tags_at = (link + 27 + l.len() + head.len()) as u64; + let (l, b) = lace(&[&pkt(5, 40)], false); + page(&mut f, 0x04, 960, 2, 1, &l, &b); + let src = FailOnce { data: f.clone(), at: tags_at, armed: std::cell::Cell::new(true) }; + let mut r = PacketReader::new(&src).unwrap(); + let mut buf = Vec::new(); + let mut got = Vec::new(); + let mut failed = 0; + loop { + match r.next_packet(&mut buf) { + Ok(Some((s, _))) => got.push((s, buf.clone())), + Ok(None) => break, + Err(e) => { + assert!(matches!(e, Error::Io(_)), "{e}"); + failed += 1; + assert!(failed < 2, "the read failed again"); + } + } + } + assert_eq!(failed, 1); + let (want, w) = read_all(f.as_slice()); + assert_eq!(got, want.into_iter().map(|(s, _, b)| (s, b)).collect::>()); + assert_eq!(r.streams().len(), 2); + assert_eq!(r.streams()[1].headers, [head, tags]); + assert_eq!(r.warnings(), w.warnings()); +} + +/// A source of zeros with `head` at its start and `tail` at `at`, for files too large to hold. +struct Sparse { + head: Vec, + at: u64, + tail: Vec, +} + +impl Sparse { + /// Copy the part of `data`, placed at `at`, that `buf` at `offset` covers. + fn place(buf: &mut [u8], offset: u64, data: &[u8], at: u64) { + let start = offset.max(at); + let end = (offset + buf.len() as u64).min(at + data.len() as u64); + if start < end { + buf[(start - offset) as usize..(end - offset) as usize].copy_from_slice(&data[(start - at) as usize..(end - at) as usize]); + } + } +} + +impl ByteSource for Sparse { + fn len(&self) -> u64 { + self.at + self.tail.len() as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + if offset.checked_add(buf.len() as u64).is_none_or(|end| end > self.len()) { + return Err(io::Error::from(io::ErrorKind::UnexpectedEof)); + } + buf.fill(0); + Sparse::place(buf, offset, &self.head, 0); + Sparse::place(buf, offset, &self.tail, self.at); + Ok(()) + } +} + +#[test] +fn lost_sync_across_the_probe_stop_is_reported_from_where_it_began() { + // an OpusHead page, junk, then the OpusTags page at PROBE_BYTES or just after it: the probe + // stops in the junk, and the reader reports the lost-sync region open reports + let mut head = Vec::new(); + let (l, b) = lace(&[&opus_head(0)], false); + page(&mut head, 0x02, 0, 1, 0, &l, &b); + let mut tail = Vec::new(); + let (l, b) = lace(&[b"OpusTags"], false); + page(&mut tail, 0, 0, 1, 1, &l, &b); + let (l, b) = lace(&[&pkt(0, 30)], false); + page(&mut tail, 0x04, 960, 1, 2, &l, &b); + for at in [PROBE_BYTES, PROBE_BYTES + 100] { + let src = Sparse { head: head.clone(), at, tail: tail.clone() }; + let o = open(&src).unwrap(); + assert_eq!(o.warnings, [format!("lost sync at byte {}; resumed at {at}", head.len())]); + let (got, r) = read_all(&src); + assert_eq!(r.streams()[0].headers, o.streams[0].headers); + assert_eq!(got.len(), 1); + assert_eq!(r.warnings(), o.warnings, "page at {at}"); + } } #[test]