diff --git a/crates/ec-ogg/Cargo.toml b/crates/ec-ogg/Cargo.toml new file mode 100644 index 00000000..b6da65c4 --- /dev/null +++ b/crates/ec-ogg/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-ogg" +description = "Ogg (RFC 3533) demuxer and muxer with the Vorbis, Opus (RFC 7845) and FLAC mappings." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true diff --git a/crates/ec-ogg/src/crc.rs b/crates/ec-ogg/src/crc.rs new file mode 100644 index 00000000..64059c17 --- /dev/null +++ b/crates/ec-ogg/src/crc.rs @@ -0,0 +1,60 @@ +//! The Ogg page checksum. +//! +//! CRC-32 with the Ethernet polynomial `0x04c11db7`, but — unlike almost every +//! other CRC-32 in use — with no bit reflection, no initial value and no final +//! inversion. Feeding a byte stream through the reflected variant every other +//! format uses is the classic way to produce pages a real player rejects, so +//! this is its own small module with its own table. + +/// Bit-per-bit table for the unreflected polynomial. +const fn build_table() -> [u32; 256] { + let mut table = [0u32; 256]; + let mut i = 0; + while i < 256 { + let mut r = (i as u32) << 24; + let mut bit = 0; + while bit < 8 { + r = match r & 0x8000_0000 { + 0 => r << 1, + _ => (r << 1) ^ 0x04c1_1db7, + }; + bit += 1; + } + table[i] = r; + i += 1; + } + table +} + +static TABLE: [u32; 256] = build_table(); + +/// Checksum of `chunks` concatenated — the page header (with its checksum field +/// zeroed) followed by the page body. +pub fn crc32(chunks: &[&[u8]]) -> u32 { + let mut crc = 0u32; + for chunk in chunks { + for &byte in *chunk { + crc = (crc << 8) ^ TABLE[(((crc >> 24) as u8) ^ byte) as usize]; + } + } + crc +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_known_vectors() { + // Nothing checksums to zero, and the catalogue check value for this + // variant (poly 04C11DB7, init 0, no reflection, no final xor) is + // 0x89a1897f over the ASCII digits — the value that separates it from + // the reflected CRC-32 every zip file uses. + assert_eq!(crc32(&[]), 0); + assert_eq!(crc32(&[b"123456789"]), 0x89a1_897f); + // Chunking must not change the answer — the muxer feeds header and body + // as two slices, the demuxer as three. + let all = b"OggS\x00\x02longer body bytes"; + assert_eq!(crc32(&[all]), crc32(&[&all[..4], &all[4..7], &all[7..]])); + } +} diff --git a/crates/ec-ogg/src/demux.rs b/crates/ec-ogg/src/demux.rs new file mode 100644 index 00000000..4233df7d --- /dev/null +++ b/crates/ec-ogg/src/demux.rs @@ -0,0 +1,522 @@ +//! Reading: pages in, packets out. +//! +//! Three things make an Ogg demuxer more than a loop over pages. Packets are +//! *not* page-sized — one packet can span pages and one page can hold dozens — +//! so segments are reassembled across pages. Timing comes from the page, not +//! the packet: a granule position states where the last packet finishing on +//! that page ends, so packet timestamps are carried forward from each page +//! boundary and re-synchronised at the next one (exactly, for a mapping that +//! states per-packet durations; page by page for one that does not — see +//! [`Mapping::packet_duration`]). And a page whose checksum fails is not fatal: +//! the reader drops it, discards whatever packet it was assembling and scans +//! on for the next capture pattern, so damage costs the packets inside the +//! damaged page and nothing after it. + +use std::collections::VecDeque; +use std::io::{BufReader, Read, Seek, SeekFrom}; + +use ec_core::{ + Buf, CodecParameters, Demuxer, Error, MediaParameters, Packet, Result, SeekMode, StreamInfo, + Timestamp, +}; + +use crate::mapping::Mapping; +use crate::page::{self, PageHeader}; +use crate::{granule_side_data, xiph_lace}; + +/// One page, read and verified. +struct RawPage { + header: PageHeader, + body: Vec, + /// Byte offset of the capture pattern. + offset: u64, +} + +/// What one attempt at reading a page produced. +enum Step { + /// A page whose checksum verified. + Page(RawPage), + /// A capture pattern whose page did not verify; scanning resumes just past + /// it. + Damaged, + /// No further page in the file. + End, +} + +/// Per logical stream state, in discovery order. +struct Track { + serial: u32, + mapping: Mapping, + /// Header packets, in order, until [`Mapping::header_packets`] are in. + headers: Vec>, + /// Bytes of a packet still being assembled across a page boundary. + partial: Vec, + /// A packet is mid-assembly (true even when its bytes so far are empty, + /// which happens when a page ends exactly on a 255-byte segment). + assembling: bool, + /// Granule position the next packet starts at. + pos: i64, + /// False between a packet of unknown duration and the next page granule. + pos_known: bool, + /// The stream has seen its end-of-stream page. + eos: bool, +} + +impl Track { + fn headers_complete(&self) -> bool { + self.headers.len() >= self.mapping.header_packets() + } +} + +/// An Ogg reader over anything seekable. +/// +/// [`OggDemuxer::open`] consumes the header packets of every logical stream, so +/// [`Demuxer::streams`] is complete before the first [`Demuxer::next_packet`], +/// and header packets are never handed out as packets — they live in +/// [`CodecParameters::extradata`], Xiph-laced for Vorbis, the raw `OpusHead` +/// for Opus. +pub struct OggDemuxer { + inner: BufReader, + streams: Vec, + tracks: Vec, + queue: VecDeque, + /// Offset of the first page past the last header page. + data_start: u64, + /// Pages dropped for a failed checksum. + damaged: u64, +} + +impl OggDemuxer { + /// Read every stream's headers and stop at the first audio page. + pub fn open(inner: R) -> Result> { + let mut demuxer = OggDemuxer { + inner: BufReader::new(inner), + streams: Vec::new(), + tracks: Vec::new(), + queue: VecDeque::new(), + data_start: 0, + damaged: 0, + }; + demuxer.read_headers()?; + demuxer.measure_durations()?; + Ok(demuxer) + } + + /// How many pages were dropped because their checksum did not verify. + pub fn damaged_pages(&self) -> u64 { + self.damaged + } + + /// The mapping of stream `index`, for callers that need the pre-skip or the + /// granule clock behind [`StreamInfo::time_base`]. + pub fn mapping(&self, index: usize) -> Option { + self.tracks.get(index).map(|t| t.mapping) + } + + /// Read pages until every discovered stream has all of its header packets. + fn read_headers(&mut self) -> Result<()> { + loop { + if !self.tracks.is_empty() && self.tracks.iter().all(Track::headers_complete) { + self.data_start = self.inner.stream_position()?; + return Ok(()); + } + match read_page(&mut self.inner)? { + Step::Page(page) => self.consume(page)?, + Step::Damaged => self.damaged += 1, + Step::End => match self.tracks.is_empty() { + true => { + return Err(Error::corrupt( + "Ogg: no logical stream with a known mapping", + )); + } + // Headers that never completed: whatever streams were found + // are described as far as their headers went. + false => { + self.data_start = self.inner.stream_position()?; + return Ok(()); + } + }, + } + } + } + + /// Walk to the end once to learn each stream's last granule position, then + /// come back. Cheap (a bounded tail scan) and it is the only way an Ogg + /// file states its duration at all. + fn measure_durations(&mut self) -> Result<()> { + let resume = self.inner.stream_position()?; + let end = self.inner.seek(SeekFrom::End(0))?; + // Tail window, widened until a page for every stream turns up or the + // whole file has been walked. + let mut window = 64 * 1024; + let mut last: Vec> = vec![None; self.tracks.len()]; + loop { + let from = end.saturating_sub(window); + self.inner.seek(SeekFrom::Start(from))?; + loop { + match read_page(&mut self.inner)? { + Step::Page(page) => { + if let Some(i) = self.track_index(page.header.serial) + && page.header.granule != page::NO_GRANULE + { + last[i] = Some(page.header.granule); + } + } + Step::Damaged => continue, + Step::End => break, + } + } + if last.iter().all(Option::is_some) || from == 0 { + break; + } + window *= 8; + } + for (i, granule) in last.into_iter().enumerate() { + if let Some(granule) = granule { + let start = self.streams[i].start_time.unwrap_or(0); + self.streams[i].duration = Some((granule - start).max(0)); + } + } + self.inner.seek(SeekFrom::Start(resume))?; + Ok(()) + } + + fn track_index(&self, serial: u32) -> Option { + self.tracks.iter().position(|t| t.serial == serial) + } + + /// Turn one page into packets: header packets into the stream description, + /// audio packets into the queue. + fn consume(&mut self, page: RawPage) -> Result<()> { + let serial = page.header.serial; + let index = match self.track_index(serial) { + Some(i) => i, + None => match page.header.bos { + true => match self.start_track(&page) { + Some(i) => i, + // A mapping nothing in this family claims (Theora, Skeleton, + // a private stream): its pages are skipped, not an error — + // the audio streams beside it still read. + None => return Ok(()), + }, + false => return Ok(()), + }, + }; + + let mapping = self.tracks[index].mapping; + let time_base = self.streams[index].time_base; + let mut packet = std::mem::take(&mut self.tracks[index].partial); + let mut assembling = self.tracks[index].assembling; + let mut pos = self.tracks[index].pos; + let mut pos_known = self.tracks[index].pos_known; + let mut headers_done = self.tracks[index].headers_complete(); + let mut at = 0usize; + let mut segments = &page.header.segments[..]; + + match (page.header.continued, assembling) { + // The head of this packet was in a page we never saw: drop segments + // up to and including the first terminator. + (true, false) => { + let mut skipped = 0; + for (i, &lace) in segments.iter().enumerate() { + at += usize::from(lace); + skipped = i + 1; + if lace < 255 { + break; + } + } + segments = &segments[skipped..]; + } + // A packet was mid-assembly and this page does not continue it: the + // partial is orphaned. + (false, true) => { + packet.clear(); + assembling = false; + } + _ => {} + } + + let first_new = self.queue.len(); + for &lace in segments { + let end = at + usize::from(lace); + let Some(slice) = page.body.get(at..end) else { + // The segment table promised more body than the page carried. + return Err(Error::corrupt("Ogg page: segment table overruns the body")); + }; + packet.extend_from_slice(slice); + at = end; + if lace == 255 { + assembling = true; + continue; + } + assembling = false; + let done = std::mem::take(&mut packet); + match headers_done { + false => { + self.tracks[index].headers.push(done); + if self.tracks[index].headers_complete() { + headers_done = true; + self.finish_stream(index)?; + } + } + true => { + // The zero-length segment a muxer uses to carry an + // end-of-stream flag on an otherwise empty page is not a + // packet; handing it out would inflate every packet count. + if done.is_empty() { + continue; + } + let duration = mapping.packet_duration(&done); + let mut out = Packet::new(index as u32, time_base, done); + out.pts = pos_known.then_some(pos); + out.dts = out.pts; + out.duration = duration; + // Every Ogg audio packet is a decodable entry point as far + // as the container is concerned; codec pre-roll (a Vorbis + // block needs its predecessor to overlap) is the decoder's. + out.flags.keyframe = true; + match duration { + Some(d) if pos_known => pos += d, + Some(_) => {} + None => pos_known = false, + } + self.queue.push_back(out); + } + } + } + let track = &mut self.tracks[index]; + track.partial = packet; + track.assembling = assembling; + track.pos = pos; + track.pos_known = pos_known; + track.eos |= page.header.eos; + + // The granule is where the last packet finishing on this page ends, so + // it is also where the next one starts — the point every mapping's + // timing is re-anchored to. + if page.header.granule != page::NO_GRANULE { + if self.queue.len() > first_new { + let last = self.queue.len() - 1; + self.queue[last] + .side_data + .push(granule_side_data(page.header.granule)); + } + let track = &mut self.tracks[index]; + track.pos = page.header.granule; + track.pos_known = true; + } + Ok(()) + } + + /// A beginning-of-stream page: identify the mapping from its first packet. + fn start_track(&mut self, page: &RawPage) -> Option { + let len = usize::from(*page.header.segments.first()?); + let first = page.body.get(..len)?; + let mapping = Mapping::identify(first)?; + let mut params = CodecParameters::new(mapping.codec()); + if let MediaParameters::Audio(audio) = &mut params.media { + audio.sample_rate = mapping.sample_rate(); + audio.layout = mapping.layout(); + } + let index = self.tracks.len(); + let mut info = StreamInfo::new(index as u32, mapping.time_base(), params); + info.start_time = Some(match mapping { + // Opus granules include the samples a decoder throws away, so + // presentation starts at the pre-skip rather than at zero. + Mapping::Opus { pre_skip, .. } => i64::from(pre_skip), + _ => 0, + }); + self.streams.push(info); + self.tracks.push(Track { + serial: page.header.serial, + mapping, + headers: Vec::new(), + partial: Vec::new(), + assembling: false, + pos: 0, + pos_known: true, + eos: false, + }); + Some(index) + } + + /// All header packets are in: publish them as `extradata`. + fn finish_stream(&mut self, index: usize) -> Result<()> { + let track = &self.tracks[index]; + let extradata = match track.mapping { + // The three-packet triplet, laced the way every consumer of Vorbis + // extradata outside Ogg expects it. + Mapping::Vorbis { .. } => { + let refs: Vec<&[u8]> = track.headers.iter().map(Vec::as_slice).collect(); + xiph_lace(&refs) + } + // RFC 7845 identification header, verbatim; the tags packet is + // metadata, not decoder setup. + Mapping::Opus { .. } | Mapping::Flac { .. } => Some(track.headers[0].clone()), + }; + self.streams[index].params.extradata = extradata.map(Buf::from_vec); + Ok(()) + } + + /// Scan forward from `offset` for the next page of `serial`. + fn page_at_or_after(&mut self, offset: u64, serial: u32) -> Result> { + self.inner.seek(SeekFrom::Start(offset))?; + loop { + match read_page(&mut self.inner)? { + Step::Page(page) if page.header.serial == serial => { + return Ok(Some((page.offset, page.header.granule))); + } + Step::Page(_) | Step::Damaged => continue, + Step::End => return Ok(None), + } + } + } + + /// Drop assembly state and queued packets after a jump. + fn reset_state(&mut self) { + self.queue.clear(); + for track in &mut self.tracks { + track.partial.clear(); + track.assembling = false; + track.pos_known = false; + track.eos = false; + } + } +} + +impl Demuxer for OggDemuxer { + fn streams(&self) -> &[StreamInfo] { + &self.streams + } + + fn next_packet(&mut self) -> Result { + loop { + if let Some(packet) = self.queue.pop_front() { + return Ok(packet); + } + match read_page(&mut self.inner)? { + Step::Page(page) => self.consume(page)?, + Step::Damaged => self.damaged += 1, + Step::End => return Err(Error::Eof), + } + } + } + + /// Land on a page boundary at or before `to` by bisecting the file on + /// granule positions — the only index Ogg has. + /// + /// [`SeekMode::Exact`] is served as [`SeekMode::SyncBefore`]: pages are the + /// finest position the container offers, and a decoder that needs the + /// sample exactly discards forward from there. + fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { + let index = usize::try_from(stream).unwrap_or(usize::MAX); + let info = self + .streams + .get(index) + .ok_or_else(|| Error::corrupt(format!("Ogg seek: no stream {stream}")))?; + let serial = self.tracks[index].serial; + let target = to.rescale(info.time_base, ec_core::Rounding::Down).ticks; + + let end = self.inner.seek(SeekFrom::End(0))?; + let mut lo = self.data_start; + let mut hi = end; + // Last page start whose granule is at or before the target, and the + // first one at or after it — one bisection answers both. + let mut before = self.data_start; + let mut after = None; + while lo < hi { + let mid = lo + (hi - lo) / 2; + match self.page_at_or_after(mid, serial)? { + Some((offset, granule)) if granule != page::NO_GRANULE && granule <= target => { + before = offset; + // Always make progress: the found page may start before mid. + lo = offset.max(mid) + 1; + } + Some((offset, granule)) if granule != page::NO_GRANULE => { + after = Some(offset); + hi = match offset > mid { + true => mid, + false => offset, + }; + } + // A page with no granule says nothing about position; step past + // it rather than splitting the same interval forever. + Some((offset, _)) => lo = offset.max(mid) + 1, + None => hi = mid, + } + } + let landing = match mode { + SeekMode::SyncAfter => after.unwrap_or(before), + _ => before, + }; + self.reset_state(); + self.inner.seek(SeekFrom::Start(landing))?; + Ok(()) + } +} + +/// Read one page: scan for the capture pattern, verify the checksum, hand back +/// header and body. +fn read_page(inner: &mut BufReader) -> Result { + let mut fixed = [0u8; page::HEADER_LEN]; + let mut window = 0usize; + // Scan for "OggS". The pattern has no proper prefix that is also a suffix, + // so a failed match can never hide the start of a real one. + while window < 4 { + let mut byte = [0u8; 1]; + match inner.read(&mut byte) { + Ok(0) => return Ok(Step::End), + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(e) => return Err(e.into()), + } + window = match byte[0] == page::CAPTURE[window] { + true => window + 1, + false => usize::from(byte[0] == page::CAPTURE[0]), + }; + } + let offset = inner.stream_position()? - 4; + fixed[..4].copy_from_slice(&page::CAPTURE); + if read_exact_or_end(inner, &mut fixed[4..])? { + return Ok(Step::End); + } + + let Ok((mut header, nsegs)) = PageHeader::parse_fixed(&fixed) else { + inner.seek(SeekFrom::Start(offset + 4))?; + return Ok(Step::Damaged); + }; + let mut segments = vec![0u8; nsegs]; + if read_exact_or_end(inner, &mut segments)? { + return Ok(Step::End); + } + header.segments = segments; + let mut body = vec![0u8; header.body_len()]; + if read_exact_or_end(inner, &mut body)? { + return Ok(Step::End); + } + + let stored = PageHeader::stored_crc(&fixed); + let mut zeroed = fixed; + zeroed[22..26].fill(0); + if crate::crc::crc32(&[&zeroed, &header.segments, &body]) != stored { + // Damage is local: resume scanning right after this capture pattern so + // the very next intact page is found. + inner.seek(SeekFrom::Start(offset + 4))?; + return Ok(Step::Damaged); + } + Ok(Step::Page(RawPage { + header, + body, + offset, + })) +} + +/// `read_exact`, with a truncated file reported as end rather than as an error: +/// a half-written page at EOF is the normal shape of an interrupted recording. +fn read_exact_or_end(inner: &mut BufReader, buf: &mut [u8]) -> Result { + match inner.read_exact(buf) { + Ok(()) => Ok(false), + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(true), + Err(e) => Err(e.into()), + } +} diff --git a/crates/ec-ogg/src/lib.rs b/crates/ec-ogg/src/lib.rs new file mode 100644 index 00000000..47e60c9f --- /dev/null +++ b/crates/ec-ogg/src/lib.rs @@ -0,0 +1,89 @@ +//! Ogg (RFC 3533): the container Vorbis, Opus and FLAC-in-Ogg travel in. +//! +//! [`OggDemuxer`] reads pages into packets — continuations reassembled, page +//! checksums verified, damaged pages skipped rather than fatal — and +//! [`OggMuxer`] writes packets back into pages with correct lacing, granule +//! positions and beginning/end-of-stream flags. Both speak the family IR, so an +//! Ogg file is `Demuxer` in and `Muxer` out like every other container here. +//! +//! What a granule position *means* belongs to the mapping, not to Ogg +//! ([`Mapping`]): Vorbis and FLAC count samples at the stream's own rate, Opus +//! counts 48 kHz samples including the pre-skip a decoder discards. Timestamps +//! are therefore exact per packet where the mapping states packet durations +//! (Opus does, in its TOC byte) and per page boundary where it does not (Vorbis +//! hides block sizes behind the setup header's codebooks, which is the Vorbis +//! decoder's parse, not the container's). +//! +//! Because a page states where its *last finishing packet* ends, a remux has to +//! carry that position through: [`OggDemuxer`] attaches it to the packet it +//! belongs to as [`SideData::Custom`] with kind [`GRANULE_KIND`], and +//! [`OggMuxer`] reads it back with [`granule_of`]. A packet without one is +//! still written — it simply cannot be the last packet on a page. +//! +//! Not covered: chained streams (a second beginning-of-stream group after the +//! first ends) are read as far as the first chain and no further, Skeleton +//! indexes are ignored, and Theora/Speex pages are skipped rather than +//! described. Each is a mapping this family does not carry yet, not a silent +//! misread. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod crc; +mod demux; +mod mapping; +mod mux; +mod page; + +pub use demux::OggDemuxer; +pub use ec_core::{Error, Result}; +pub use mapping::{Mapping, opus_packet_samples}; +pub use mux::{DEFAULT_PAGE_TARGET, OggMuxer}; +pub use page::{PageHeader, lacing, xiph_lace, xiph_unlace}; + +use ec_core::{Buf, Packet, SideData}; + +/// [`SideData::Custom`] kind carrying an Ogg granule position: eight +/// little-endian bytes of `i64`, the position at which the packet ends in its +/// mapping's own units. +/// +/// Ogg states positions per page rather than per packet, and only for the last +/// packet finishing on each page, so this is present on exactly those packets — +/// it is the one piece of Ogg timing that has nowhere else to live in a +/// `Packet`, and without it a remux would have to guess where its pages end. +pub const GRANULE_KIND: u32 = u32::from_be_bytes(*b"OggS"); + +/// Side data stating that a packet ends at `granule`. +pub fn granule_side_data(granule: i64) -> SideData { + SideData::Custom { + kind: GRANULE_KIND, + data: Buf::from_vec(granule.to_le_bytes().to_vec()), + } +} + +/// The granule position attached to `packet`, if any. +pub fn granule_of(packet: &Packet) -> Option { + packet.side_data.iter().find_map(|side| match side { + SideData::Custom { kind, data } if *kind == GRANULE_KIND && data.len() == 8 => { + Some(i64::from_le_bytes(data[..8].try_into().ok()?)) + } + _ => None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use ec_core::TimeBase; + + #[test] + fn granule_side_data_round_trips() { + let mut packet = Packet::new(0, TimeBase::from_rate(48_000), vec![1, 2, 3]); + assert_eq!(granule_of(&packet), None); + packet.side_data.push(granule_side_data(-1)); + assert_eq!(granule_of(&packet), Some(-1)); + let mut other = Packet::new(0, TimeBase::from_rate(44_100), vec![]); + other.side_data.push(granule_side_data(1_234_567_890_123)); + assert_eq!(granule_of(&other), Some(1_234_567_890_123)); + } +} diff --git a/crates/ec-ogg/src/mapping.rs b/crates/ec-ogg/src/mapping.rs new file mode 100644 index 00000000..ce4e74ea --- /dev/null +++ b/crates/ec-ogg/src/mapping.rs @@ -0,0 +1,237 @@ +//! What a logical stream carries, and what its granule positions mean. +//! +//! Ogg itself says nothing about time: a granule position is an opaque integer +//! whose meaning belongs to the *mapping* named by the first packet. Vorbis and +//! FLAC count samples at the stream's own rate; Opus counts samples at 48 kHz +//! whatever the input rate was, and its count includes the pre-skip a decoder +//! throws away (RFC 7845 §4). Everything timing-related in this crate goes +//! through this module so those three conventions live in one place. + +use ec_core::{ChannelLayout, CodecId, TimeBase}; + +/// A recognised logical-stream mapping, with what its identification header +/// stated. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mapping { + /// Vorbis I: three header packets, granule counts samples at `rate`. + Vorbis { + /// Sample rate from the identification header. + rate: u32, + /// Channel count from the identification header. + channels: u8, + }, + /// Opus (RFC 7845): `OpusHead` then `OpusTags`, granule counts 48 kHz + /// samples and starts `pre_skip` above the first decoded sample. + Opus { + /// Output channel count. + channels: u8, + /// Samples (at 48 kHz) a decoder discards from the head of the stream. + pre_skip: u16, + /// Rate the encoder was fed, informational only — granules stay 48 kHz. + input_rate: u32, + }, + /// FLAC-in-Ogg: `\x7fFLAC` mapping header carrying `fLaC` + STREAMINFO, + /// granule counts samples at `rate`. + Flac { + /// Sample rate from STREAMINFO. + rate: u32, + /// Channel count from STREAMINFO. + channels: u8, + /// Header packets this stream declares, the identification one included. + headers: usize, + }, +} + +impl Mapping { + /// Recognise a mapping from the first packet of a logical stream, or + /// [`None`] when nothing in the family claims it (Theora, Speex, Skeleton, + /// a private mapping — all valid Ogg, none of them ours). + pub fn identify(bos: &[u8]) -> Option { + if bos.len() >= 16 && bos[0] == 1 && &bos[1..7] == b"vorbis" { + return Some(Mapping::Vorbis { + rate: u32::from_le_bytes(bos[12..16].try_into().ok()?), + channels: bos[11], + }); + } + if bos.len() >= 19 && &bos[..8] == b"OpusHead" { + return Some(Mapping::Opus { + channels: bos[9], + pre_skip: u16::from_le_bytes(bos[10..12].try_into().ok()?), + input_rate: u32::from_le_bytes(bos[12..16].try_into().ok()?), + }); + } + if bos.len() >= 51 && bos[0] == 0x7f && &bos[1..5] == b"FLAC" && &bos[9..13] == b"fLaC" { + // STREAMINFO starts after the mapping header and the metadata block + // header; its rate is 20 bits, then 3 bits of channel count - 1. + let si = &bos[17..51]; + let rate = + (u32::from(si[10]) << 12) | (u32::from(si[11]) << 4) | u32::from(si[12] >> 4); + let declared = usize::from(u16::from_be_bytes([bos[7], bos[8]])); + return Some(Mapping::Flac { + rate, + channels: ((si[12] >> 1) & 0x07) + 1, + // A zero here means "not stated"; the comment header still + // follows, so two is the floor. + headers: (declared + 1).max(2), + }); + } + None + } + + /// Which codec decodes this stream's packets. + pub fn codec(&self) -> CodecId { + match self { + Mapping::Vorbis { .. } => CodecId::Vorbis, + Mapping::Opus { .. } => CodecId::Opus, + Mapping::Flac { .. } => CodecId::Flac, + } + } + + /// The clock granule positions are counted in. + pub fn time_base(&self) -> TimeBase { + match self { + // Opus granules are always 48 kHz, whatever the encoder was fed. + Mapping::Opus { .. } => TimeBase::from_rate(48_000), + Mapping::Vorbis { rate, .. } | Mapping::Flac { rate, .. } => { + TimeBase::try_new(1, i64::from(*rate)).unwrap_or(TimeBase::from_rate(48_000)) + } + } + } + + /// Decoded sample rate. + pub fn sample_rate(&self) -> u32 { + match self { + Mapping::Opus { .. } => 48_000, + Mapping::Vorbis { rate, .. } | Mapping::Flac { rate, .. } => *rate, + } + } + + /// Channel layout, by count — Vorbis and Opus both order channels the way + /// [`ChannelLayout`] does for the layouts it names. + pub fn layout(&self) -> ChannelLayout { + let channels = match self { + Mapping::Vorbis { channels, .. } + | Mapping::Opus { channels, .. } + | Mapping::Flac { channels, .. } => *channels, + }; + ChannelLayout::from_count(usize::from(channels).max(1)) + } + + /// How many packets belong to the stream's header, the identification + /// packet included. Audio starts after them. + pub fn header_packets(&self) -> usize { + match self { + Mapping::Vorbis { .. } => 3, + Mapping::Opus { .. } => 2, + Mapping::Flac { headers, .. } => *headers, + } + } + + /// Samples this packet decodes to, in granule units, when the mapping makes + /// that cheap to know. + /// + /// Opus states it in the first byte of every packet, so its timing is exact + /// packet by packet. Vorbis does not: the block size of a packet is a mode + /// number whose meaning lives at the end of the setup header, past the full + /// codebook parse, which belongs to the Vorbis decoder rather than here — + /// so this answers [`None`] and the demuxer re-synchronises on every page + /// granule instead (see [`crate::demux`]). FLAC frame headers do state a + /// block size, but reading it means the frame parser, same argument. + pub fn packet_duration(&self, data: &[u8]) -> Option { + match self { + Mapping::Opus { .. } => opus_packet_samples(data), + Mapping::Vorbis { .. } | Mapping::Flac { .. } => None, + } + } +} + +/// Samples at 48 kHz one Opus packet decodes to, from its TOC byte +/// (RFC 6716 §3.1): a configuration number picking the frame duration, and a +/// code picking how many frames are packed behind it. +pub fn opus_packet_samples(data: &[u8]) -> Option { + let toc = *data.first()?; + let config = usize::from(toc >> 3); + // Frame duration in 48 kHz samples, per configuration block: SILK modes + // step 10/20/40/60 ms, hybrid 10/20 ms, CELT 2.5/5/10/20 ms. + let samples = match config { + 0..=11 => [480, 960, 1920, 2880][config % 4], + 12..=15 => [480, 960][config % 2], + _ => [120, 240, 480, 960][config % 4], + }; + let frames = match toc & 0x03 { + 0 => 1, + 1 | 2 => 2, + // Code 3 states the count in the low six bits of the next byte. + _ => i64::from(*data.get(1)? & 0x3f), + }; + // RFC 6716 §3.1: a packet may not exceed 120 ms of audio. + match frames * samples { + n if n > 0 && n <= 5760 => Some(n), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn identifies_the_three_mappings() { + let mut vorbis = vec![1u8]; + vorbis.extend_from_slice(b"vorbis"); + vorbis.extend_from_slice(&0u32.to_le_bytes()); // version + vorbis.push(2); // channels + vorbis.extend_from_slice(&44_100u32.to_le_bytes()); + vorbis.resize(30, 0); + assert_eq!( + Mapping::identify(&vorbis), + Some(Mapping::Vorbis { + rate: 44_100, + channels: 2 + }) + ); + + let mut opus = Vec::from(*b"OpusHead"); + opus.push(1); // version + opus.push(6); // channels + opus.extend_from_slice(&312u16.to_le_bytes()); // pre-skip + opus.extend_from_slice(&48_000u32.to_le_bytes()); + opus.resize(19, 0); + let mapping = Mapping::identify(&opus).unwrap(); + assert_eq!( + mapping, + Mapping::Opus { + channels: 6, + pre_skip: 312, + input_rate: 48_000 + } + ); + // Whatever the input rate said, granules count 48 kHz samples. + assert_eq!(mapping.time_base(), TimeBase::from_rate(48_000)); + assert_eq!(mapping.layout(), ChannelLayout::Surround5_1); + assert_eq!(mapping.header_packets(), 2); + + assert_eq!(Mapping::identify(b"not a header at all"), None); + assert_eq!(Mapping::identify(&[]), None); + } + + #[test] + fn opus_durations_follow_the_toc() { + // config 16 (CELT 2.5 ms), one frame. + assert_eq!(opus_packet_samples(&[16 << 3]), Some(120)); + // config 31 (CELT 20 ms), one frame; the 960 that every 48 kHz encoder + // in this family emits by default. + assert_eq!(opus_packet_samples(&[31 << 3]), Some(960)); + // ...same config, code 1: two frames, so twice the samples. + assert_eq!(opus_packet_samples(&[(31 << 3) | 1]), Some(1920)); + // Code 3 takes its frame count from the next byte, and 120 ms is the + // ceiling the RFC sets — 7 frames of 20 ms is over it. + assert_eq!(opus_packet_samples(&[(31 << 3) | 3, 6]), Some(5760)); + assert_eq!(opus_packet_samples(&[(31 << 3) | 3, 7]), None); + assert_eq!(opus_packet_samples(&[(31 << 3) | 3, 0]), None); + assert_eq!(opus_packet_samples(&[(31 << 3) | 3]), None); + // SILK 60 ms narrowband. + assert_eq!(opus_packet_samples(&[3 << 3]), Some(2880)); + assert_eq!(opus_packet_samples(&[]), None); + } +} diff --git a/crates/ec-ogg/src/mux.rs b/crates/ec-ogg/src/mux.rs new file mode 100644 index 00000000..ccc7161f --- /dev/null +++ b/crates/ec-ogg/src/mux.rs @@ -0,0 +1,372 @@ +//! Writing: packets in, pages out. +//! +//! Two rules shape every page this writes. A granule position states where the +//! *last packet finishing on that page* ends, so a page is only ever closed +//! after a packet whose position is known — [`crate::granule_of`] on the packet, +//! or `pts + duration` when both are stated. And the header packets of every +//! mapping in this family get pages of their own: the identification packet +//! alone on the beginning-of-stream page, the rest flushed before the first +//! audio byte, which is what Vorbis I and RFC 7845 §3 both require. +//! +//! Page size is targeted, not fixed: packets are packed until the body passes +//! [`OggMuxer::set_page_target_bytes`] (4 KiB by default, the size RFC 3533 +//! calls usual) and the next packet boundary with a known granule arrives. +//! Packets larger than a page are split across pages with the continuation flag, +//! and a page never carries more than 255 segments. + +use std::io::Write; + +use ec_core::{Error, Muxer, Packet, Result, StreamInfo}; + +use crate::mapping::Mapping; +use crate::page::{self, PageHeader}; +use crate::{granule_of, xiph_unlace}; + +/// Default page body target: RFC 3533 describes pages as "usually 4-8 kB", and +/// one packet per page (the alternative) costs 28 bytes of header per 20 ms of +/// audio. +pub const DEFAULT_PAGE_TARGET: usize = 4096; + +/// Vendor string in a synthesized `OpusTags` packet. +const VENDOR: &str = "ec-ogg"; + +/// One logical stream being written. +struct MuxTrack { + serial: u32, + /// Header packets in order; the first goes on the beginning-of-stream page. + headers: Vec>, + /// True once the caller supplied headers explicitly, which replace whatever + /// `extradata` produced. + headers_from_caller: bool, + /// Lacing values of the page being built. + segments: Vec, + /// Body of the page being built. + body: Vec, + /// The page being built opens with the tail of a packet. + continued: bool, + /// Where the last packet finishing on this page ends, if one has. + page_granule: Option, + /// False when a packet finished on this page without stating its position: + /// the page cannot be closed here without lying about where it ends. + can_end: bool, + /// The first data page has not been written yet. It is closed at the first + /// position the stream states, whatever the size target says: a decoder + /// reads its head trim out of that first granule (a Vorbis stream whose + /// first page ends below what its packets decode to is saying "discard the + /// difference"), and a page target large enough to swallow it would silently + /// add the pre-roll back to the output. + first_page_pending: bool, + sequence: u32, + /// Position written on the last closed page, for the end-of-stream page. + last_granule: i64, +} + +impl MuxTrack { + fn pending(&self) -> bool { + !self.segments.is_empty() + } +} + +/// An Ogg writer over any sink. +pub struct OggMuxer { + out: W, + streams: Vec, + tracks: Vec, + page_target: usize, + headers_written: bool, + finished: bool, +} + +impl OggMuxer { + /// A writer with no streams yet. + pub fn new(out: W) -> OggMuxer { + OggMuxer { + out, + streams: Vec::new(), + tracks: Vec::new(), + page_target: DEFAULT_PAGE_TARGET, + headers_written: false, + finished: false, + } + } + + /// Aim for `bytes` of body per page; [`None`] restores + /// [`DEFAULT_PAGE_TARGET`]. A page still ends early when its segment table + /// fills, and still ends late when the next packet boundary has no granule. + pub fn set_page_target_bytes(&mut self, bytes: Option) { + self.page_target = bytes.unwrap_or(DEFAULT_PAGE_TARGET).max(1); + } + + /// Override the serial number of stream `index`. Serials only have to be + /// unique within the file; the default is derived from the index so that + /// two runs over the same input produce the same bytes. + pub fn set_serial(&mut self, index: u32, serial: u32) -> Result<()> { + let track = self + .tracks + .get_mut(index as usize) + .ok_or_else(|| Error::corrupt(format!("Ogg mux: no stream {index}")))?; + track.serial = serial; + Ok(()) + } + + /// Write the beginning-of-stream and remaining header pages of every + /// stream. Called automatically before the first data packet; public + /// because a caller that declares streams and then hits an error still + /// wants a readable file. + pub fn write_headers(&mut self) -> Result<()> { + if self.headers_written { + return Ok(()); + } + if self.tracks.is_empty() { + return Err(Error::corrupt("Ogg mux: no streams were declared")); + } + // Every beginning-of-stream page first, in declaration order, before any + // other page in the file (RFC 3533 §4). + for index in 0..self.tracks.len() { + let first = match self.tracks[index].headers.first() { + Some(packet) => packet.clone(), + None => { + return Err(Error::corrupt(format!( + "Ogg mux: stream {index} has no identification header (extradata was empty \ + and no header packet was written)" + ))); + } + }; + self.push_packet(index, &first, Some(0))?; + self.flush_page(index, true, false)?; + } + // Then the remaining headers, each stream's flushed before any audio. + for index in 0..self.tracks.len() { + let rest: Vec> = self.tracks[index].headers[1..].to_vec(); + for packet in rest { + self.push_packet(index, &packet, Some(0))?; + } + if self.tracks[index].pending() { + self.flush_page(index, false, false)?; + } + } + self.headers_written = true; + Ok(()) + } + + /// Append one packet's segments to the page being built, splitting across + /// pages when the segment table fills. + fn push_packet(&mut self, index: usize, data: &[u8], granule: Option) -> Result<()> { + // Prefer a clean packet boundary to a continuation: if the packet cannot + // fit in what is left of the segment table, close the page first — as + // long as closing it here would state a truthful position. + let needed = data.len() / 255 + 1; + let track = &self.tracks[index]; + if track.pending() && track.can_end && track.segments.len() + needed > page::MAX_SEGMENTS { + self.flush_page(index, false, false)?; + } + + let mut at = 0usize; + for lace in page::lacing(data.len()) { + if self.tracks[index].segments.len() == page::MAX_SEGMENTS { + // Forced mid-packet: no packet finishes on this page, which is + // exactly what a -1 granule means. + self.flush_page(index, false, false)?; + self.tracks[index].continued = true; + } + let track = &mut self.tracks[index]; + track.segments.push(lace); + track + .body + .extend_from_slice(&data[at..at + usize::from(lace)]); + at += usize::from(lace); + } + + // A page may only end where the *last* packet finishing on it states + // its position, so this tracks the latest packet, not the latest known + // granule: one positionless packet after a positioned one closes the + // page again. + let track = &mut self.tracks[index]; + match granule { + Some(granule) => { + track.page_granule = Some(granule); + track.can_end = true; + } + None => track.can_end = false, + } + Ok(()) + } + + /// Write the page under construction. + fn flush_page(&mut self, index: usize, bos: bool, eos: bool) -> Result<()> { + let track = &mut self.tracks[index]; + if track.segments.is_empty() && !eos { + return Ok(()); + } + let granule = match (track.can_end, track.page_granule) { + (true, Some(granule)) => granule, + // An end-of-stream page with nothing left to carry still states + // where the stream ends, or a player has no length to trim to. + (_, None) if eos && track.segments.is_empty() => track.last_granule, + _ => page::NO_GRANULE, + }; + let header = PageHeader { + continued: track.continued, + bos, + eos, + granule, + serial: track.serial, + sequence: track.sequence, + // A page always carries at least one lacing value, even an + // end-of-stream page with nothing left to say. + segments: match track.segments.is_empty() { + true => vec![0], + false => std::mem::take(&mut track.segments), + }, + }; + let body = std::mem::take(&mut track.body); + track.sequence += 1; + track.continued = false; + track.page_granule = None; + track.can_end = true; + if granule != page::NO_GRANULE { + track.last_granule = granule; + } + + let mut bytes = Vec::with_capacity(page::HEADER_LEN + header.segments.len() + body.len()); + header.write_page(&body, &mut bytes); + self.out.write_all(&bytes)?; + Ok(()) + } + + /// Header packets from `extradata`, per mapping. + fn headers_from_extradata(info: &StreamInfo) -> Result>> { + let Some(extradata) = info.params.extradata.as_ref().filter(|e| !e.is_empty()) else { + return Ok(Vec::new()); + }; + // Xiph-laced extradata carries the whole triplet; a bare identification + // packet does not, and Vorbis has no way to invent the other two. + if let Ok(packets) = xiph_unlace(extradata) + && packets.len() >= 2 + && Mapping::identify(packets[0]).is_some() + { + return Ok(packets.into_iter().map(<[u8]>::to_vec).collect()); + } + match Mapping::identify(extradata) { + Some(Mapping::Opus { .. }) => Ok(vec![extradata.to_vec(), opus_tags()]), + Some(Mapping::Vorbis { .. }) => Err(Error::corrupt( + "Ogg mux: Vorbis extradata holds only the identification header; the comment and \ + setup headers are needed too (Xiph-laced, as xiph_lace produces)", + )), + // Anything else — a FLAC mapping header, a codec this crate does not + // name — is written verbatim as the first header packet, with the + // rest expected as header-flagged packets. + _ => Ok(vec![extradata.to_vec()]), + } + } +} + +/// A minimal `OpusTags` packet: RFC 7845 §5 requires one, and a remux that only +/// carried `OpusHead` has no comments to preserve. +fn opus_tags() -> Vec { + let mut out = Vec::from(*b"OpusTags"); + out.extend_from_slice(&(VENDOR.len() as u32).to_le_bytes()); + out.extend_from_slice(VENDOR.as_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); // comment count + out +} + +impl Muxer for OggMuxer { + fn add_stream(&mut self, info: StreamInfo) -> Result { + if self.headers_written { + return Err(Error::corrupt( + "Ogg mux: every stream is declared before the first packet", + )); + } + let index = self.tracks.len() as u32; + let headers = OggMuxer::::headers_from_extradata(&info)?; + self.tracks.push(MuxTrack { + // Unique within the file and stable across runs, which keeps a + // remux byte-comparable with itself. + serial: 0x4544_0000 ^ index, + headers, + headers_from_caller: false, + segments: Vec::new(), + body: Vec::new(), + continued: false, + page_granule: None, + can_end: true, + first_page_pending: true, + sequence: 0, + last_granule: 0, + }); + let mut info = info; + info.index = index; + self.streams.push(info); + Ok(index) + } + + /// Write one packet. + /// + /// A packet flagged [`ec_core::PacketFlags::header`] before any audio joins + /// the stream's header packets — the first one replaces whatever + /// `extradata` gave, so a remux can carry the original `OpusTags` through. + /// Otherwise the packet's granule position is [`crate::granule_of`], or + /// `pts + duration` when both are known, or unknown — and a page never ends + /// on a packet whose position is unknown. + fn write_packet(&mut self, packet: &Packet) -> Result<()> { + let index = packet.stream as usize; + if index >= self.tracks.len() { + return Err(Error::corrupt(format!( + "Ogg mux: packet for stream {} of {} declared", + packet.stream, + self.tracks.len() + ))); + } + if packet.flags.header && !self.headers_written { + let track = &mut self.tracks[index]; + if !track.headers_from_caller { + track.headers.clear(); + track.headers_from_caller = true; + } + track.headers.push(packet.data.to_vec()); + return Ok(()); + } + self.write_headers()?; + + // The page is closed *before* the packet that would overflow it, never + // after: that keeps at least one packet pending at all times, so the + // end-of-stream flag rides a page that carries audio. A page whose only + // content is a zero-length packet is legal Ogg and ffmpeg reads it as a + // packet — "Packet processing failed", a decode error in a file that is + // otherwise perfect. + let track = &self.tracks[index]; + let due = track.body.len() >= self.page_target || track.first_page_pending; + if track.pending() && track.can_end && due { + self.flush_page(index, false, false)?; + self.tracks[index].first_page_pending = false; + } + let granule = granule_of(packet).or_else(|| packet.end_pts()); + let data = packet.data.clone(); + self.push_packet(index, &data, granule)?; + Ok(()) + } + + fn finish(&mut self) -> Result<()> { + if self.finished { + return Ok(()); + } + self.write_headers()?; + for index in 0..self.tracks.len() { + // The end-of-stream flag rides the last page — which still carries + // audio, because packets are only paged out on the arrival of the + // next one. Empty only when the stream had no data packets at all. + self.flush_page(index, false, true)?; + } + self.out.flush()?; + self.finished = true; + Ok(()) + } +} + +impl OggMuxer { + /// The sink, for callers that wrote into a buffer and want it back. + pub fn into_inner(self) -> W { + self.out + } +} diff --git a/crates/ec-ogg/src/page.rs b/crates/ec-ogg/src/page.rs new file mode 100644 index 00000000..da8dca18 --- /dev/null +++ b/crates/ec-ogg/src/page.rs @@ -0,0 +1,258 @@ +//! The page: Ogg's only structural unit (RFC 3533 §6). +//! +//! A page is a 27-byte fixed header, a segment table of 1..=255 lacing values, +//! and a body whose length is the sum of those values. Packets are cut into +//! 255-byte segments; a segment shorter than 255 ends its packet, which is why +//! a packet whose length is an exact multiple of 255 needs a trailing zero-length +//! segment — the single most-missed rule in the format, and the one that makes a +//! decoder wait forever for a packet that already ended. + +use ec_core::{Error, Result}; + +use crate::crc; + +/// Capture pattern every page starts with. +pub const CAPTURE: [u8; 4] = *b"OggS"; +/// Bytes before the segment table. +pub const HEADER_LEN: usize = 27; +/// Most lacing values one page can carry. +pub const MAX_SEGMENTS: usize = 255; +/// Granule position meaning "no packet ends on this page" (RFC 3533 §6.1). +pub const NO_GRANULE: i64 = -1; + +/// `header_type` bits. +const FLAG_CONTINUED: u8 = 0x01; +const FLAG_BOS: u8 = 0x02; +const FLAG_EOS: u8 = 0x04; + +/// A page header, decoded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PageHeader { + /// The first segment continues a packet started on an earlier page. + pub continued: bool, + /// Beginning of stream: this page carries the stream's first packet. + pub bos: bool, + /// End of stream: the last page of this logical stream. + pub eos: bool, + /// Position of the last packet *completed* on this page, in the mapping's + /// own units, or [`NO_GRANULE`] when no packet ends here. + pub granule: i64, + /// Which logical stream this page belongs to. + pub serial: u32, + /// Page counter within the logical stream, from zero. + pub sequence: u32, + /// Lacing values, in order. + pub segments: Vec, +} + +impl PageHeader { + /// Total body length: the sum of the lacing values. + pub fn body_len(&self) -> usize { + self.segments.iter().map(|&s| usize::from(s)).sum() + } + + /// Decode the fixed part of a header. `buf` must hold at least + /// [`HEADER_LEN`] bytes; the segment table is read by the caller, which + /// knows how much more input it can supply. + /// + /// Returns the header with an empty segment table plus the segment count. + pub fn parse_fixed(buf: &[u8]) -> Result<(PageHeader, usize)> { + if buf.len() < HEADER_LEN { + return Err(Error::NeedMore); + } + if buf[..4] != CAPTURE { + return Err(Error::corrupt("Ogg page: no OggS capture pattern")); + } + if buf[4] != 0 { + return Err(Error::unsupported( + format!("Ogg stream structure version {}", buf[4]), + "only version 0 is defined", + )); + } + let flags = buf[5]; + let header = PageHeader { + continued: flags & FLAG_CONTINUED != 0, + bos: flags & FLAG_BOS != 0, + eos: flags & FLAG_EOS != 0, + granule: i64::from_le_bytes(buf[6..14].try_into().unwrap()), + serial: u32::from_le_bytes(buf[14..18].try_into().unwrap()), + sequence: u32::from_le_bytes(buf[18..22].try_into().unwrap()), + segments: Vec::new(), + }; + Ok((header, usize::from(buf[26]))) + } + + /// The checksum stored in a fixed header. + pub fn stored_crc(buf: &[u8]) -> u32 { + u32::from_le_bytes(buf[22..26].try_into().unwrap()) + } + + /// Serialize header and segment table, checksum included, and append the + /// body — the exact bytes of one page. + pub fn write_page(&self, body: &[u8], out: &mut Vec) { + debug_assert_eq!(self.body_len(), body.len()); + debug_assert!(!self.segments.is_empty() && self.segments.len() <= MAX_SEGMENTS); + let start = out.len(); + out.extend_from_slice(&CAPTURE); + out.push(0); + let mut flags = 0u8; + if self.continued { + flags |= FLAG_CONTINUED; + } + if self.bos { + flags |= FLAG_BOS; + } + if self.eos { + flags |= FLAG_EOS; + } + out.push(flags); + out.extend_from_slice(&self.granule.to_le_bytes()); + out.extend_from_slice(&self.serial.to_le_bytes()); + out.extend_from_slice(&self.sequence.to_le_bytes()); + out.extend_from_slice(&[0; 4]); // checksum, filled in below + out.push(self.segments.len() as u8); + out.extend_from_slice(&self.segments); + out.extend_from_slice(body); + // The checksum covers the whole page with its own field read as zero. + let sum = crc::crc32(&[&out[start..]]); + out[start + 22..start + 26].copy_from_slice(&sum.to_le_bytes()); + } +} + +/// The lacing values a packet of `len` bytes becomes: `len / 255` values of 255 +/// then the remainder — including the explicit zero that terminates a packet +/// whose length is a multiple of 255. +pub fn lacing(len: usize) -> impl Iterator { + let full = len / 255; + (0..=full).map(move |i| match i < full { + true => 255, + false => (len % 255) as u8, + }) +} + +/// The three Xiph header packets, laced the way `CodecParameters::extradata` +/// carries them: two length prefixes in the 255-plus-remainder form, then the +/// packets back to back, all behind a leading count of `2`. +/// +/// This is the shape ffmpeg calls "Xiph extradata" and the one Vorbis, Theora +/// and Speex setup data travels in outside of Ogg. [`None`] when a header is +/// too long to describe (the format has no escape beyond a 255 run) or when the +/// packet count is not the two-prefixed-plus-one this layout can express. +pub fn xiph_lace(packets: &[&[u8]]) -> Option> { + if packets.len() < 2 || packets.len() > 256 { + return None; + } + let mut out = vec![(packets.len() - 1) as u8]; + for packet in &packets[..packets.len() - 1] { + out.extend(lacing(packet.len())); + } + for packet in packets { + out.extend_from_slice(packet); + } + Some(out) +} + +/// The inverse of [`xiph_lace`]: split laced extradata back into packets. +pub fn xiph_unlace(data: &[u8]) -> Result> { + let short = || Error::corrupt("Xiph extradata: truncated lacing"); + let count = usize::from(*data.first().ok_or_else(short)?) + 1; + let mut at = 1; + let mut lengths = Vec::with_capacity(count); + for _ in 0..count - 1 { + let mut len = 0usize; + loop { + let lace = usize::from(*data.get(at).ok_or_else(short)?); + at += 1; + len += lace; + if lace < 255 { + break; + } + } + lengths.push(len); + } + let mut out = Vec::with_capacity(count); + for len in lengths { + let end = at.checked_add(len).ok_or_else(short)?; + out.push(data.get(at..end).ok_or_else(short)?); + at = end; + } + // The last packet runs to the end: its length is the one the layout does + // not store. + out.push(&data[at..]); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lacing_terminates_multiples_of_255() { + assert_eq!(lacing(0).collect::>(), vec![0]); + assert_eq!(lacing(1).collect::>(), vec![1]); + assert_eq!(lacing(254).collect::>(), vec![254]); + // The rule that matters: 255 is *not* one segment of 255, it is a 255 + // and a 0, or the packet never ends. + assert_eq!(lacing(255).collect::>(), vec![255, 0]); + assert_eq!(lacing(256).collect::>(), vec![255, 1]); + assert_eq!(lacing(510).collect::>(), vec![255, 255, 0]); + for len in [0, 1, 255, 256, 700, 65_535] { + let sum: usize = lacing(len).map(usize::from).sum(); + assert_eq!(sum, len, "lacing must sum back to the packet length"); + } + } + + #[test] + fn page_round_trips_through_its_own_checksum() { + let body: Vec = (0..600u32).map(|i| (i % 251) as u8).collect(); + let header = PageHeader { + continued: true, + bos: false, + eos: true, + granule: 123_456, + serial: 0xdead_beef, + sequence: 7, + segments: lacing(body.len()).collect(), + }; + let mut bytes = Vec::new(); + header.write_page(&body, &mut bytes); + + let (parsed, nsegs) = PageHeader::parse_fixed(&bytes).unwrap(); + let segments = bytes[HEADER_LEN..HEADER_LEN + nsegs].to_vec(); + let parsed = PageHeader { segments, ..parsed }; + assert_eq!(parsed, header); + assert_eq!(parsed.body_len(), body.len()); + + // The stored checksum verifies with its own field zeroed. + let stored = PageHeader::stored_crc(&bytes); + let mut zeroed = bytes.clone(); + zeroed[22..26].fill(0); + assert_eq!(crc::crc32(&[&zeroed]), stored); + // ...and a single flipped body byte breaks it. + let mut damaged = zeroed.clone(); + let last = damaged.len() - 1; + damaged[last] ^= 0x01; + assert_ne!(crc::crc32(&[&damaged]), stored); + + assert!(PageHeader::parse_fixed(&bytes[..10]).is_err()); + assert!(PageHeader::parse_fixed(b"NotAnOggPageHeaderAtAll....").is_err()); + } + + #[test] + fn xiph_lacing_round_trips() { + let ident = [1u8; 30]; + let comment = [2u8; 300]; + let setup = [3u8; 4000]; + let packets = [&ident[..], &comment[..], &setup[..]]; + let laced = xiph_lace(&packets).unwrap(); + assert_eq!(laced[0], 2, "count byte is packets - 1"); + let back = xiph_unlace(&laced).unwrap(); + assert_eq!(back.len(), 3); + assert_eq!(back[0], &ident[..]); + assert_eq!(back[1], &comment[..]); + assert_eq!(back[2], &setup[..]); + assert!(xiph_lace(&[&ident[..]]).is_none()); + assert!(xiph_unlace(&[]).is_err()); + assert!(xiph_unlace(&[2, 255]).is_err()); + } +} diff --git a/crates/ec-ogg/tests/ogg.rs b/crates/ec-ogg/tests/ogg.rs new file mode 100644 index 00000000..ea767e6a --- /dev/null +++ b/crates/ec-ogg/tests/ogg.rs @@ -0,0 +1,594 @@ +//! The fixture matrix, the remux round trip and what damage costs. +//! +//! ffprobe is the oracle for structure (packet counts, duration, "does this +//! file parse at all") and ffmpeg for content: a remuxed file has to decode to +//! the same PCM, byte for byte, as the file its packets came from. Both are +//! required — a remux that ffprobe likes but whose audio drifted is exactly the +//! failure this crate exists to avoid. +//! +//! Run the tables: +//! cargo test -p ec-ogg --test ogg -- --nocapture + +use std::io::Cursor; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_core::{ + Buf, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet, PacketFlags, SeekMode, + StreamInfo, TimeBase, Timestamp, +}; +use ec_ogg::{Mapping, OggDemuxer, OggMuxer, granule_of, granule_side_data}; + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") +} + +/// Working directory keyed by test name: these tests are threads of one +/// process, so a shared temp directory would have them deleting each other's +/// files. +fn workdir(test: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ec-ogg-{}-{test}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create work dir"); + dir +} + +/// Every Ogg fixture on disk, sorted so the table reads the same every run. +fn ogg_fixtures() -> Vec { + let Ok(entries) = std::fs::read_dir(fixtures()) else { + return Vec::new(); + }; + let mut out: Vec = entries + .flatten() + .map(|e| e.path()) + .filter(|p| { + matches!( + p.extension().and_then(|s| s.to_str()), + Some("ogg") | Some("opus") + ) + }) + .collect(); + out.sort(); + out +} + +/// Audio packets ffprobe counts in a file — header packets excluded, which is +/// also what this demuxer hands out. +fn ffprobe_packets(path: &Path) -> u64 { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "a:0", + "-count_packets", + "-show_entries", + "stream=nb_read_packets", + "-of", + "csv=p=0", + ]) + .arg(path) + .output() + .expect("ffprobe must be installed: it is the oracle for this crate"); + String::from_utf8_lossy(&out.stdout) + .trim() + .parse() + .unwrap_or_else(|e| panic!("ffprobe packet count for {}: {e}", path.display())) +} + +/// ffprobe's own duration for the file, in seconds. +fn ffprobe_duration(path: &Path) -> f64 { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-show_entries", + "format=duration", + "-of", + "csv=p=0", + ]) + .arg(path) + .output() + .expect("ffprobe"); + String::from_utf8_lossy(&out.stdout).trim().parse().unwrap() +} + +/// Decode a file to raw 32-bit float samples with ffmpeg. Errors are fatal: an +/// unreadable file is the failure being tested for. +fn decode_pcm(path: &Path) -> Vec { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "f32le", "-"]) + .output() + .expect("ffmpeg"); + assert!( + out.status.success(), + "ffmpeg failed to decode {}: {}", + path.display(), + String::from_utf8_lossy(&out.stderr) + ); + out.stdout +} + +/// ffprobe with errors escalated: the structural verdict on a file we wrote. +fn ffprobe_clean(path: &Path) -> String { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-show_entries", + "stream=codec_name,sample_rate,channels", + "-of", + "csv=p=0", + ]) + .arg(path) + .output() + .expect("ffprobe"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.trim().is_empty(), + "ffprobe complained about {}: {stderr}", + path.display() + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +/// Read every packet of a file through our demuxer. +fn demux_all(path: &Path) -> (Vec, Vec, u64) { + let file = std::fs::File::open(path).unwrap(); + let mut demuxer = OggDemuxer::open(file).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let streams = demuxer.streams().to_vec(); + let mut packets = Vec::new(); + loop { + match demuxer.next_packet() { + Ok(p) => packets.push(p), + Err(e) if e.is_eof() => break, + Err(e) => panic!("{}: {e}", path.display()), + } + } + (streams, packets, demuxer.damaged_pages()) +} + +#[test] +fn demuxes_every_fixture_to_eof() { + let files = ogg_fixtures(); + if files.is_empty() { + eprintln!("fixtures/audio absent (gitignored) — skipping"); + return; + } + println!( + "{:<28} {:>8} {:>8} {:>10} {:>10}", + "file", "ours", "ffprobe", "dur", "ffprobe" + ); + for path in &files { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let (streams, packets, damaged) = demux_all(path); + assert_eq!(damaged, 0, "{name}: an intact fixture has no damaged pages"); + assert_eq!(streams.len(), 1, "{name}: one logical stream expected"); + let info = &streams[0]; + let expected_codec = match name.starts_with("opus") { + true => CodecId::Opus, + false => CodecId::Vorbis, + }; + assert_eq!(info.params.codec, expected_codec, "{name}"); + assert!( + info.params + .extradata + .as_ref() + .is_some_and(|e| !e.is_empty()), + "{name}: setup data must reach the decoder" + ); + + // The generator names rate and layout in the file name. + let MediaParameters::Audio(audio) = &info.params.media else { + panic!("{name}: audio parameters expected"); + }; + let expect_rate: u32 = name + .rsplit('-') + .next() + .unwrap() + .split('.') + .next() + .unwrap() + .parse() + .unwrap(); + let expect_channels = match true { + _ if name.contains("mono") => 1, + _ if name.contains("stereo") => 2, + _ => 6, + }; + assert_eq!(audio.layout.channel_count(), expect_channels, "{name}"); + match expected_codec { + // Opus always decodes at 48 kHz whatever it was fed. + CodecId::Opus => assert_eq!(audio.sample_rate, 48_000, "{name}"), + _ => assert_eq!(audio.sample_rate, expect_rate, "{name}"), + } + + let ours = packets.len() as u64; + let theirs = ffprobe_packets(path); + assert_eq!(ours, theirs, "{name}: packet count"); + + // Duration: ours is the playable length, so Opus differs from ffprobe's + // by exactly the pre-skip it reports as part of the granule count. + let secs = |ticks: i64| ticks as f64 * info.time_base.as_secs_f64(); + let our_dur = secs(info.duration.unwrap()); + let their_dur = ffprobe_duration(path); + let pre_skip = secs(info.start_time.unwrap()); + assert!( + (our_dur + pre_skip - their_dur).abs() < 1e-6, + "{name}: duration {our_dur} + pre-skip {pre_skip} vs ffprobe {their_dur}" + ); + println!("{name:<28} {ours:>8} {theirs:>8} {our_dur:>10.4} {their_dur:>10.4}"); + + // Timestamps are monotonic where the mapping states them, and Opus + // states one for every packet. + let stamped = packets.iter().filter(|p| p.pts.is_some()).count(); + match expected_codec { + CodecId::Opus => assert_eq!(stamped, packets.len(), "{name}: every Opus pts"), + _ => assert!(stamped > 0, "{name}: at least the page-boundary timestamps"), + } + let mut last = i64::MIN; + for p in packets.iter().filter_map(|p| p.pts) { + assert!(p >= last, "{name}: timestamps must not go backwards"); + last = p; + } + // The last packet ends where the file says the stream ends. + assert_eq!( + granule_of(packets.last().unwrap()), + Some(info.duration.unwrap() + info.start_time.unwrap()), + "{name}: the end-of-stream granule reaches the last packet" + ); + } + assert!( + files.len() >= 9, + "expected the nine Ogg fixtures, saw {}", + files.len() + ); +} + +/// Demux a fixture, write its packets back out, and require ffmpeg to decode +/// the result to the same samples. +fn remux_case(path: &Path, page_target: Option) { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let (streams, packets, _) = demux_all(path); + let out_path = workdir("remux").join(format!("remux-{name}")); + + let file = std::fs::File::create(&out_path).unwrap(); + let mut muxer = OggMuxer::new(std::io::BufWriter::new(file)); + muxer.add_stream(streams[0].clone()).unwrap(); + muxer.set_page_target_bytes(page_target); + for packet in &packets { + muxer.write_packet(packet).unwrap(); + } + muxer.finish().unwrap(); + + // Structure: ffprobe reads it without a word of complaint, sees the same + // stream and counts the same packets. + let described = ffprobe_clean(&out_path); + assert!(!described.is_empty(), "{name}: ffprobe described nothing"); + assert_eq!( + ffprobe_packets(&out_path), + packets.len() as u64, + "{name}: remuxed packet count" + ); + assert!( + (ffprobe_duration(&out_path) - ffprobe_duration(path)).abs() < 1e-6, + "{name}: remuxed duration" + ); + + // Content: same samples, byte for byte. + let before = decode_pcm(path); + let after = decode_pcm(&out_path); + assert_eq!( + after.len(), + before.len(), + "{name}: remux decoded to {} bytes, source to {}", + after.len(), + before.len() + ); + assert!( + after == before, + "{name}: remuxed audio differs from the source" + ); + + // And our own demuxer reads back exactly the packets that went in. + let (round, again, _) = demux_all(&out_path); + assert_eq!( + again.len(), + packets.len(), + "{name}: round-trip packet count" + ); + for (a, b) in again.iter().zip(&packets) { + assert_eq!(a.data, b.data, "{name}: payload changed in the round trip"); + } + assert_eq!(round[0].params.codec, streams[0].params.codec); + println!( + "remux {name:<24} {described} ok ({} packets)", + packets.len() + ); +} + +#[test] +fn remuxes_every_fixture_bit_identically() { + let files = ogg_fixtures(); + if files.is_empty() { + eprintln!("fixtures/audio absent (gitignored) — skipping"); + return; + } + for path in &files { + remux_case(path, None); + } +} + +/// The page-size knob must not change what comes out: one packet per page and +/// one page for the lot both have to decode identically. +#[test] +fn page_size_does_not_change_the_audio() { + let files = ogg_fixtures(); + let Some(path) = files + .iter() + .find(|p| p.to_string_lossy().contains("vorbis-ogg-stereo-48000")) + else { + eprintln!("fixtures absent — skipping"); + return; + }; + remux_case(path, Some(1)); + remux_case(path, Some(1 << 20)); +} + +#[test] +fn damage_costs_one_page_and_no_more() { + let files = ogg_fixtures(); + let Some(path) = files + .iter() + .find(|p| p.to_string_lossy().contains("vorbis-ogg-stereo-44100")) + else { + eprintln!("fixtures absent — skipping"); + return; + }; + let (_, clean, _) = demux_all(path); + let bytes = std::fs::read(path).unwrap(); + + // Flip a bit in the middle of the file: that lands inside a page body, so + // the page's checksum fails and its packets are lost — and nothing else is. + let mut damaged = bytes.clone(); + let at = damaged.len() / 2; + damaged[at] ^= 0x40; + let out = workdir("damage").join("flipped.ogg"); + std::fs::write(&out, &damaged).unwrap(); + + let (streams, packets, dropped) = demux_all(&out); + assert_eq!(streams.len(), 1, "the stream is still described"); + assert_eq!(dropped, 1, "exactly one page fails its checksum"); + assert!( + packets.len() < clean.len(), + "the damaged page's packets are gone: {} vs {}", + packets.len(), + clean.len() + ); + // Recovery, not collapse: what is lost is the damaged page and nothing + // else, so every packet after it is still there, byte for byte, in order. + // What survives is a prefix of the clean read plus a suffix of it: the + // packets of the damaged page, and only those, are missing from the middle. + let kept = packets.len(); + let head = packets + .iter() + .zip(&clean) + .take_while(|(a, b)| a.data == b.data) + .count(); + let tail = packets + .iter() + .rev() + .zip(clean.iter().rev()) + .take_while(|(a, b)| a.data == b.data) + .count(); + assert!(head > 0, "nothing before the damage was read"); + assert!(tail > 0, "nothing after the damage was recovered"); + assert_eq!( + head + tail, + kept, + "recovery is a prefix of {head} and a suffix of {tail} out of {kept} packets" + ); + println!( + "damage: {kept} of {} packets survived — {head} before the bad page, {tail} after it", + clean.len() + ); +} + +#[test] +fn seeks_land_at_or_before_the_target() { + let files = ogg_fixtures(); + if files.is_empty() { + eprintln!("fixtures absent — skipping"); + return; + } + for path in files.iter().filter(|p| { + let n = p.to_string_lossy().to_string(); + n.contains("stereo-48000") || n.contains("5.1-44100") + }) { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let file = std::fs::File::open(path).unwrap(); + let mut demuxer = OggDemuxer::open(file).unwrap(); + let info = demuxer.streams()[0].clone(); + let duration = info.duration.unwrap(); + for fraction in [0, 1, 2, 3, 4] { + let target = duration * fraction / 4; + let to = Timestamp::new(target + info.start_time.unwrap(), info.time_base); + demuxer.seek(0, to, SeekMode::SyncBefore).unwrap(); + let packet = match demuxer.next_packet() { + Ok(p) => p, + // Seeking to the very end can land on the end-of-stream page. + Err(e) if e.is_eof() => continue, + Err(e) => panic!("{name}: {e}"), + }; + if let Some(pts) = packet.pts { + assert!( + pts <= target + info.start_time.unwrap(), + "{name}: seek to {target} landed at {pts}" + ); + } + // Whatever it landed on, the rest of the file still reads. + let mut rest = 1; + while let Ok(_p) = demuxer.next_packet() { + rest += 1; + } + assert!(rest > 0, "{name}: nothing readable after the seek"); + } + // Seeking forwards then back to zero returns the whole stream. + demuxer + .seek(0, Timestamp::new(0, info.time_base), SeekMode::SyncBefore) + .unwrap(); + let mut count = 0; + while demuxer.next_packet().is_ok() { + count += 1; + } + let (_, all, _) = demux_all(path); + assert!( + count >= all.len() - 2, + "{name}: after seeking home {count} of {} packets remained", + all.len() + ); + } +} + +/// Payload sizes Ogg's own lacing has to work for, none of which the fixtures +/// contain: a packet that is exactly a multiple of 255, one that fills more +/// than one page's segment table, and an empty one. +#[test] +fn round_trips_awkward_packet_sizes_through_memory() { + let sizes = [ + 1usize, 254, 255, 256, 509, 510, 511, 64_000, 65_025, 300_000, + ]; + let rate = 48_000; + let time_base = TimeBase::from_rate(rate); + + let mut params = CodecParameters::new(CodecId::Vorbis); + if let MediaParameters::Audio(audio) = &mut params.media { + audio.sample_rate = rate; + } + // A Vorbis triplet is what the mapping requires; the contents only have to + // identify, since nothing decodes them here. + let mut ident = vec![1u8]; + ident.extend_from_slice(b"vorbis"); + ident.extend_from_slice(&0u32.to_le_bytes()); + ident.push(2); + ident.extend_from_slice(&rate.to_le_bytes()); + ident.resize(30, 0); + let comment = vec![3u8; 400]; + let setup = vec![5u8; 9000]; + params.extradata = Some(Buf::from_vec( + ec_ogg::xiph_lace(&[&ident, &comment, &setup]).unwrap(), + )); + let info = StreamInfo::new(0, time_base, params); + + let mut muxer = OggMuxer::new(Cursor::new(Vec::new())); + muxer.add_stream(info).unwrap(); + // One packet per page, so every packet carries the page granule back out. + muxer.set_page_target_bytes(Some(1)); + let mut granule = 0i64; + let mut written = Vec::new(); + for (i, size) in sizes.iter().enumerate() { + let data: Vec = (0..*size) + .map(|n| (n as u32 % 251) as u8 ^ i as u8) + .collect(); + granule += 1024; + let mut packet = Packet::new(0, time_base, data.clone()); + packet.side_data.push(granule_side_data(granule)); + muxer.write_packet(&packet).unwrap(); + written.push(data); + } + muxer.finish().unwrap(); + let bytes = muxer.into_inner().into_inner(); + + let mut demuxer = OggDemuxer::open(Cursor::new(bytes)).unwrap(); + assert_eq!(demuxer.streams()[0].params.codec, CodecId::Vorbis); + assert_eq!( + demuxer.mapping(0), + Some(Mapping::Vorbis { rate, channels: 2 }) + ); + // Setup data survived the trip laced the way it arrived. + let extradata = demuxer.streams()[0].params.extradata.clone().unwrap(); + let unlaced = ec_ogg::xiph_unlace(&extradata).unwrap(); + assert_eq!(unlaced.len(), 3); + assert_eq!(unlaced[2], &setup[..]); + + let mut read = Vec::new(); + while let Ok(packet) = demuxer.next_packet() { + read.push(packet); + } + assert_eq!(read.len(), written.len(), "one packet in, one packet out"); + for (i, (got, want)) in read.iter().zip(&written).enumerate() { + assert_eq!( + &got.data[..], + &want[..], + "packet {i} of {} bytes", + want.len() + ); + assert_eq!( + granule_of(got), + Some((i as i64 + 1) * 1024), + "packet {i}: granule position" + ); + } +} + +/// Header packets written by the caller replace what extradata would have +/// produced — the path a remux takes to carry the original `OpusTags` through. +#[test] +fn caller_supplied_headers_win_over_extradata() { + let time_base = TimeBase::from_rate(48_000); + let mut head = Vec::from(*b"OpusHead"); + head.extend_from_slice(&[1, 2]); + head.extend_from_slice(&312u16.to_le_bytes()); + head.extend_from_slice(&48_000u32.to_le_bytes()); + head.resize(19, 0); + + let mut params = CodecParameters::new(CodecId::Opus); + params.extradata = Some(Buf::from_vec(head.clone())); + let info = StreamInfo::new(0, time_base, params); + + let mut tags = Vec::from(*b"OpusTags"); + tags.extend_from_slice(&4u32.to_le_bytes()); + tags.extend_from_slice(b"mine"); + tags.extend_from_slice(&0u32.to_le_bytes()); + + let mut muxer = OggMuxer::new(Cursor::new(Vec::new())); + muxer.add_stream(info).unwrap(); + for header in [&head, &tags] { + let mut packet = Packet::new(0, time_base, header.clone()); + packet.flags = PacketFlags { + header: true, + ..PacketFlags::default() + }; + muxer.write_packet(&packet).unwrap(); + } + // One CELT 20 ms packet, so the stream has audio to end on. + let mut audio = Packet::new(0, time_base, vec![(31 << 3) as u8, 0, 0, 0]); + audio.side_data.push(granule_side_data(960)); + muxer.write_packet(&audio).unwrap(); + muxer.finish().unwrap(); + + let bytes = muxer.into_inner().into_inner(); + // The tags packet we supplied is in the file; the synthesized one is not. + let haystack = String::from_utf8_lossy(&bytes).to_string(); + assert!( + haystack.contains("mine"), + "caller's OpusTags must be written" + ); + assert!( + !haystack.contains("ec-ogg"), + "synthesized tags must not appear" + ); + + let mut demuxer = OggDemuxer::open(Cursor::new(bytes)).unwrap(); + assert_eq!(demuxer.streams()[0].params.codec, CodecId::Opus); + assert_eq!( + demuxer.streams()[0].start_time, + Some(312), + "presentation starts at the pre-skip" + ); + let packet = demuxer.next_packet().unwrap(); + assert_eq!(packet.duration, Some(960), "TOC states the packet duration"); + assert_eq!(packet.pts, Some(0)); + assert!(demuxer.next_packet().unwrap_err().is_eof()); +} diff --git a/shims/oxideav-ogg/Cargo.toml b/shims/oxideav-ogg/Cargo.toml new file mode 100644 index 00000000..eae6fe7f --- /dev/null +++ b/shims/oxideav-ogg/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "oxideav-ogg" +description = "Compatibility shim: the oxideav-ogg mux surface edith consumes, over ec-ogg." +version = "0.1.8" +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +ec-core = { path = "../../crates/ec-core", version = "0.1.0" } +ec-ogg = { path = "../../crates/ec-ogg", version = "0.1.0" } +oxideav-core = { path = "../oxideav-core", version = "0.1.34" } diff --git a/shims/oxideav-ogg/src/lib.rs b/shims/oxideav-ogg/src/lib.rs new file mode 100644 index 00000000..4c55f8aa --- /dev/null +++ b/shims/oxideav-ogg/src/lib.rs @@ -0,0 +1,28 @@ +//! `oxideav-ogg` as edith consumes it, over [`ec_ogg`]. +//! +//! A shim, not a port: it carries the incumbent's package name and version so +//! the swap is a `[patch.crates-io]` line, and it exposes exactly the items the +//! replica names — `mux::xiph_lace`, `mux::open_concrete`, and the concrete +//! muxer's `set_page_target_bytes` beside the `oxideav_core::Muxer` methods +//! (`export.rs:2942,2957,2961`). +//! +//! One semantic difference is owned here rather than at the call site. The +//! replica states a packet's *granule position* — where it ends — in the +//! packet's `pts`, because that is what the incumbent's muxer wrote onto the +//! page; `ec_ogg` keeps `pts` meaning presentation start and carries granule +//! positions in side data ([`ec_ogg::granule_side_data`]). The translation is +//! [`mux::OggMuxer::write_packet`], once, for every caller. + +#![forbid(unsafe_code)] + +use std::io::{Seek, Write}; + +/// A sink an Ogg file can be written to. The incumbent puts this trait in +/// `oxideav-core`; nothing in the replica names it directly (it only ever +/// passes a `Box::new(File::create(..)?)`), so it lives here until the atomic +/// oxideav swap decides where the family keeps it. +pub trait WriteSeek: Write + Seek + Send {} + +impl WriteSeek for T {} + +pub mod mux; diff --git a/shims/oxideav-ogg/src/mux.rs b/shims/oxideav-ogg/src/mux.rs new file mode 100644 index 00000000..ce89d558 --- /dev/null +++ b/shims/oxideav-ogg/src/mux.rs @@ -0,0 +1,90 @@ +//! The muxing half — the only half the replica calls. + +use ec_core::Muxer as _; +use ec_ogg::granule_side_data; +use oxideav_core::{Error, Muxer, Packet, Result, StreamInfo}; + +use crate::WriteSeek; + +/// Lace header packets into the `extradata` form Vorbis setup data travels in: +/// [`None`] when they cannot be described that way. +pub fn xiph_lace(packets: &[&[u8]]) -> Option> { + ec_ogg::xiph_lace(packets) +} + +/// Open a writer over `output` with `streams` already declared. +pub fn open_concrete(output: Box, streams: &[StreamInfo]) -> Result { + let mut inner = ec_ogg::OggMuxer::new(output); + for stream in streams { + inner.add_stream(to_ec_stream(stream)?)?; + } + Ok(OggMuxer { inner }) +} + +/// The concrete muxer, so callers reach [`OggMuxer::set_page_target_bytes`] +/// without a downcast. +pub struct OggMuxer { + inner: ec_ogg::OggMuxer>, +} + +impl OggMuxer { + /// Aim for `bytes` of body per page; [`None`] restores the default. + pub fn set_page_target_bytes(&mut self, bytes: Option) { + self.inner.set_page_target_bytes(bytes); + } +} + +impl Muxer for OggMuxer { + fn format_name(&self) -> &str { + "ogg" + } + + fn write_header(&mut self) -> Result<()> { + Ok(self.inner.write_headers()?) + } + + /// The caller's `pts` *is* the granule position — where this packet ends — + /// which is the convention the incumbent muxer wrote onto its pages. It is + /// moved into the side data `ec_ogg` reads positions from, and the packet + /// keeps no start timestamp, because Ogg does not carry one. + fn write_packet(&mut self, packet: &Packet) -> Result<()> { + let mut out = packet.clone(); + if let Some(granule) = packet.pts { + out.side_data.push(granule_side_data(granule)); + } + out.pts = None; + out.dts = None; + Ok(self.inner.write_packet(&out)?) + } + + fn write_trailer(&mut self) -> Result<()> { + Ok(self.inner.finish()?) + } +} + +/// The replica's stream description, in family terms. +fn to_ec_stream(stream: &StreamInfo) -> Result { + let params = &stream.params; + let codec = params.codec_id.to_ec().ok_or_else(|| { + Error::Unsupported(format!( + "Ogg mux: codec {} is not one this family carries", + params.codec_id + )) + })?; + let mut out = ec_core::CodecParameters::new(codec); + if let ec_core::MediaParameters::Audio(audio) = &mut out.media { + if let Some(rate) = params.sample_rate { + audio.sample_rate = rate; + } + if let Some(channels) = params.channels { + audio.layout = ec_core::ChannelLayout::from_count(usize::from(channels).max(1)); + } + } + if !params.extradata.is_empty() { + out.extradata = Some(ec_core::Buf::copy_from_slice(¶ms.extradata)); + } + let mut info = ec_core::StreamInfo::new(stream.index, stream.time_base, out); + info.duration = stream.duration; + info.start_time = stream.start_time; + Ok(info) +} diff --git a/shims/oxideav-ogg/tests/edith_surface.rs b/shims/oxideav-ogg/tests/edith_surface.rs new file mode 100644 index 00000000..78dd5b70 --- /dev/null +++ b/shims/oxideav-ogg/tests/edith_surface.rs @@ -0,0 +1,123 @@ +//! The replica's own call sequence, run against the shim. +//! +//! `export.rs:2942-2982` laces three Vorbis headers, describes one stream, +//! opens a concrete muxer, sets the page target, then writes header, packets +//! and trailer — with each packet's *granule* in its `pts`. This drives exactly +//! that, with real Vorbis packets taken out of a fixture, and asks ffmpeg +//! whether the result is the same audio. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_core::Demuxer as _; +use oxideav_core::{CodecId, CodecParameters, Muxer as _, Packet, StreamInfo, TimeBase}; + +fn fixture() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio/vorbis-ogg-stereo-44100.ogg") +} + +fn decode_pcm(path: &Path) -> Vec { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "f32le", "-"]) + .output() + .expect("ffmpeg"); + assert!( + out.status.success(), + "ffmpeg failed on {}: {}", + path.display(), + String::from_utf8_lossy(&out.stderr) + ); + out.stdout +} + +#[test] +fn writes_a_vorbis_file_the_way_the_replica_does() { + let source = fixture(); + if !source.exists() { + eprintln!("fixtures/audio absent (gitignored) — skipping"); + return; + } + + // Packets and setup data out of a real file, standing in for the encoder + // the replica feeds this from. + let mut demuxer = ec_ogg::OggDemuxer::open(std::fs::File::open(&source).unwrap()).unwrap(); + let info = demuxer.streams()[0].clone(); + let extradata = info.params.extradata.clone().unwrap(); + let headers = ec_ogg::xiph_unlace(&extradata).unwrap(); + let mut packets = Vec::new(); + while let Ok(packet) = demuxer.next_packet() { + packets.push(packet); + } + assert_eq!(headers.len(), 3, "a Vorbis stream is three headers"); + + // From here on, the replica's code, line for line. + let laced = super_xiph_lace(&headers).expect("the three headers would not lace"); + assert_eq!(&laced[..], &extradata[..], "lacing must round-trip"); + + let rate = 44_100u32; + let time_base = TimeBase::new(1, i64::from(rate)); + let mut params = CodecParameters::audio(CodecId::new("vorbis")); + params.sample_rate = Some(rate); + params.channels = Some(2); + params.extradata = laced; + let stream = StreamInfo { + index: 0, + time_base, + duration: info.duration, + start_time: Some(0), + params, + }; + + let out_path = + std::env::temp_dir().join(format!("oxideav-ogg-shim-{}.ogg", std::process::id())); + let file = std::fs::File::create(&out_path).unwrap(); + let mut muxer = oxideav_ogg::mux::open_concrete(Box::new(file), &[stream]).unwrap(); + muxer.set_page_target_bytes(Some(4096)); + muxer.write_header().unwrap(); + for packet in &packets { + // The replica states the granule position in `pts`; the shim is what + // knows that is what it means. + let mut out = Packet::new(0, time_base, packet.data.to_vec()); + out.pts = ec_ogg::granule_of(packet); + out.duration = packet.duration; + muxer.write_packet(&out).unwrap(); + } + muxer.write_trailer().unwrap(); + + // ffprobe reads it without complaint, and it is the same audio. + let probe = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "a:0", + "-count_packets", + "-show_entries", + "stream=codec_name,sample_rate,channels,nb_read_packets", + "-of", + "csv=p=0", + ]) + .arg(&out_path) + .output() + .expect("ffprobe"); + let stderr = String::from_utf8_lossy(&probe.stderr); + assert!(stderr.trim().is_empty(), "ffprobe complained: {stderr}"); + assert_eq!( + String::from_utf8_lossy(&probe.stdout).trim(), + format!("vorbis,{rate},2,{}", packets.len()), + "ffprobe must see the stream the replica described" + ); + assert_eq!( + decode_pcm(&out_path), + decode_pcm(&source), + "the shim's file must decode to the samples that went into it" + ); + let _ = std::fs::remove_file(&out_path); +} + +/// Named apart so the call above reads like the replica's line. +fn super_xiph_lace(headers: &[&[u8]]) -> Option> { + oxideav_ogg::mux::xiph_lace(headers) +}