Ogg demux/mux with Vorbis, Opus and FLAC mappings
Browse files at this commit47772cbfdee175e22888744221b1303f35a03481Parent: 81a11c6- feat
- Ogg demux/mux with Vorbis, Opus and FLAC mappings
12 changed files +2396 -0
- crates/ec-ogg/Cargo.toml +10 -0
- crates/ec-ogg/src/crc.rs +60 -0
- crates/ec-ogg/src/demux.rs +522 -0
- crates/ec-ogg/src/lib.rs +89 -0
- crates/ec-ogg/src/mapping.rs +237 -0
- crates/ec-ogg/src/mux.rs +372 -0
- crates/ec-ogg/src/page.rs +258 -0
- crates/ec-ogg/tests/ogg.rs +594 -0
- shims/oxideav-ogg/Cargo.toml +13 -0
- shims/oxideav-ogg/src/lib.rs +28 -0
- shims/oxideav-ogg/src/mux.rs +90 -0
- shims/oxideav-ogg/tests/edith_surface.rs +123 -0
crates/ec-ogg/Cargo.tomladded+10 -0
| @@ -0,0 +1,10 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-ogg" | ||
| 3 | +description = "Ogg (RFC 3533) demuxer and muxer with the Vorbis, Opus (RFC 7845) and FLAC mappings." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +[dependencies] | ||
| 10 | +ec-core.workspace = true | ||
crates/ec-ogg/src/crc.rsadded+60 -0
| @@ -0,0 +1,60 @@ | |||
| 1 | +//! The Ogg page checksum. | ||
| 2 | +//! | ||
| 3 | +//! CRC-32 with the Ethernet polynomial `0x04c11db7`, but — unlike almost every | ||
| 4 | +//! other CRC-32 in use — with no bit reflection, no initial value and no final | ||
| 5 | +//! inversion. Feeding a byte stream through the reflected variant every other | ||
| 6 | +//! format uses is the classic way to produce pages a real player rejects, so | ||
| 7 | +//! this is its own small module with its own table. | ||
| 8 | + | ||
| 9 | +/// Bit-per-bit table for the unreflected polynomial. | ||
| 10 | +const fn build_table() -> [u32; 256] { | ||
| 11 | + let mut table = [0u32; 256]; | ||
| 12 | + let mut i = 0; | ||
| 13 | + while i < 256 { | ||
| 14 | + let mut r = (i as u32) << 24; | ||
| 15 | + let mut bit = 0; | ||
| 16 | + while bit < 8 { | ||
| 17 | + r = match r & 0x8000_0000 { | ||
| 18 | + 0 => r << 1, | ||
| 19 | + _ => (r << 1) ^ 0x04c1_1db7, | ||
| 20 | + }; | ||
| 21 | + bit += 1; | ||
| 22 | + } | ||
| 23 | + table[i] = r; | ||
| 24 | + i += 1; | ||
| 25 | + } | ||
| 26 | + table | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +static TABLE: [u32; 256] = build_table(); | ||
| 30 | + | ||
| 31 | +/// Checksum of `chunks` concatenated — the page header (with its checksum field | ||
| 32 | +/// zeroed) followed by the page body. | ||
| 33 | +pub fn crc32(chunks: &[&[u8]]) -> u32 { | ||
| 34 | + let mut crc = 0u32; | ||
| 35 | + for chunk in chunks { | ||
| 36 | + for &byte in *chunk { | ||
| 37 | + crc = (crc << 8) ^ TABLE[(((crc >> 24) as u8) ^ byte) as usize]; | ||
| 38 | + } | ||
| 39 | + } | ||
| 40 | + crc | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +#[cfg(test)] | ||
| 44 | +mod tests { | ||
| 45 | + use super::*; | ||
| 46 | + | ||
| 47 | + #[test] | ||
| 48 | + fn matches_known_vectors() { | ||
| 49 | + // Nothing checksums to zero, and the catalogue check value for this | ||
| 50 | + // variant (poly 04C11DB7, init 0, no reflection, no final xor) is | ||
| 51 | + // 0x89a1897f over the ASCII digits — the value that separates it from | ||
| 52 | + // the reflected CRC-32 every zip file uses. | ||
| 53 | + assert_eq!(crc32(&[]), 0); | ||
| 54 | + assert_eq!(crc32(&[b"123456789"]), 0x89a1_897f); | ||
| 55 | + // Chunking must not change the answer — the muxer feeds header and body | ||
| 56 | + // as two slices, the demuxer as three. | ||
| 57 | + let all = b"OggS\x00\x02longer body bytes"; | ||
| 58 | + assert_eq!(crc32(&[all]), crc32(&[&all[..4], &all[4..7], &all[7..]])); | ||
| 59 | + } | ||
| 60 | +} | ||
crates/ec-ogg/src/demux.rsadded+522 -0
| @@ -0,0 +1,522 @@ | |||
| 1 | +//! Reading: pages in, packets out. | ||
| 2 | +//! | ||
| 3 | +//! Three things make an Ogg demuxer more than a loop over pages. Packets are | ||
| 4 | +//! *not* page-sized — one packet can span pages and one page can hold dozens — | ||
| 5 | +//! so segments are reassembled across pages. Timing comes from the page, not | ||
| 6 | +//! the packet: a granule position states where the last packet finishing on | ||
| 7 | +//! that page ends, so packet timestamps are carried forward from each page | ||
| 8 | +//! boundary and re-synchronised at the next one (exactly, for a mapping that | ||
| 9 | +//! states per-packet durations; page by page for one that does not — see | ||
| 10 | +//! [`Mapping::packet_duration`]). And a page whose checksum fails is not fatal: | ||
| 11 | +//! the reader drops it, discards whatever packet it was assembling and scans | ||
| 12 | +//! on for the next capture pattern, so damage costs the packets inside the | ||
| 13 | +//! damaged page and nothing after it. | ||
| 14 | + | ||
| 15 | +use std::collections::VecDeque; | ||
| 16 | +use std::io::{BufReader, Read, Seek, SeekFrom}; | ||
| 17 | + | ||
| 18 | +use ec_core::{ | ||
| 19 | + Buf, CodecParameters, Demuxer, Error, MediaParameters, Packet, Result, SeekMode, StreamInfo, | ||
| 20 | + Timestamp, | ||
| 21 | +}; | ||
| 22 | + | ||
| 23 | +use crate::mapping::Mapping; | ||
| 24 | +use crate::page::{self, PageHeader}; | ||
| 25 | +use crate::{granule_side_data, xiph_lace}; | ||
| 26 | + | ||
| 27 | +/// One page, read and verified. | ||
| 28 | +struct RawPage { | ||
| 29 | + header: PageHeader, | ||
| 30 | + body: Vec<u8>, | ||
| 31 | + /// Byte offset of the capture pattern. | ||
| 32 | + offset: u64, | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +/// What one attempt at reading a page produced. | ||
| 36 | +enum Step { | ||
| 37 | + /// A page whose checksum verified. | ||
| 38 | + Page(RawPage), | ||
| 39 | + /// A capture pattern whose page did not verify; scanning resumes just past | ||
| 40 | + /// it. | ||
| 41 | + Damaged, | ||
| 42 | + /// No further page in the file. | ||
| 43 | + End, | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/// Per logical stream state, in discovery order. | ||
| 47 | +struct Track { | ||
| 48 | + serial: u32, | ||
| 49 | + mapping: Mapping, | ||
| 50 | + /// Header packets, in order, until [`Mapping::header_packets`] are in. | ||
| 51 | + headers: Vec<Vec<u8>>, | ||
| 52 | + /// Bytes of a packet still being assembled across a page boundary. | ||
| 53 | + partial: Vec<u8>, | ||
| 54 | + /// A packet is mid-assembly (true even when its bytes so far are empty, | ||
| 55 | + /// which happens when a page ends exactly on a 255-byte segment). | ||
| 56 | + assembling: bool, | ||
| 57 | + /// Granule position the next packet starts at. | ||
| 58 | + pos: i64, | ||
| 59 | + /// False between a packet of unknown duration and the next page granule. | ||
| 60 | + pos_known: bool, | ||
| 61 | + /// The stream has seen its end-of-stream page. | ||
| 62 | + eos: bool, | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +impl Track { | ||
| 66 | + fn headers_complete(&self) -> bool { | ||
| 67 | + self.headers.len() >= self.mapping.header_packets() | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// An Ogg reader over anything seekable. | ||
| 72 | +/// | ||
| 73 | +/// [`OggDemuxer::open`] consumes the header packets of every logical stream, so | ||
| 74 | +/// [`Demuxer::streams`] is complete before the first [`Demuxer::next_packet`], | ||
| 75 | +/// and header packets are never handed out as packets — they live in | ||
| 76 | +/// [`CodecParameters::extradata`], Xiph-laced for Vorbis, the raw `OpusHead` | ||
| 77 | +/// for Opus. | ||
| 78 | +pub struct OggDemuxer<R: Read + Seek> { | ||
| 79 | + inner: BufReader<R>, | ||
| 80 | + streams: Vec<StreamInfo>, | ||
| 81 | + tracks: Vec<Track>, | ||
| 82 | + queue: VecDeque<Packet>, | ||
| 83 | + /// Offset of the first page past the last header page. | ||
| 84 | + data_start: u64, | ||
| 85 | + /// Pages dropped for a failed checksum. | ||
| 86 | + damaged: u64, | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +impl<R: Read + Seek> OggDemuxer<R> { | ||
| 90 | + /// Read every stream's headers and stop at the first audio page. | ||
| 91 | + pub fn open(inner: R) -> Result<OggDemuxer<R>> { | ||
| 92 | + let mut demuxer = OggDemuxer { | ||
| 93 | + inner: BufReader::new(inner), | ||
| 94 | + streams: Vec::new(), | ||
| 95 | + tracks: Vec::new(), | ||
| 96 | + queue: VecDeque::new(), | ||
| 97 | + data_start: 0, | ||
| 98 | + damaged: 0, | ||
| 99 | + }; | ||
| 100 | + demuxer.read_headers()?; | ||
| 101 | + demuxer.measure_durations()?; | ||
| 102 | + Ok(demuxer) | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + /// How many pages were dropped because their checksum did not verify. | ||
| 106 | + pub fn damaged_pages(&self) -> u64 { | ||
| 107 | + self.damaged | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + /// The mapping of stream `index`, for callers that need the pre-skip or the | ||
| 111 | + /// granule clock behind [`StreamInfo::time_base`]. | ||
| 112 | + pub fn mapping(&self, index: usize) -> Option<Mapping> { | ||
| 113 | + self.tracks.get(index).map(|t| t.mapping) | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + /// Read pages until every discovered stream has all of its header packets. | ||
| 117 | + fn read_headers(&mut self) -> Result<()> { | ||
| 118 | + loop { | ||
| 119 | + if !self.tracks.is_empty() && self.tracks.iter().all(Track::headers_complete) { | ||
| 120 | + self.data_start = self.inner.stream_position()?; | ||
| 121 | + return Ok(()); | ||
| 122 | + } | ||
| 123 | + match read_page(&mut self.inner)? { | ||
| 124 | + Step::Page(page) => self.consume(page)?, | ||
| 125 | + Step::Damaged => self.damaged += 1, | ||
| 126 | + Step::End => match self.tracks.is_empty() { | ||
| 127 | + true => { | ||
| 128 | + return Err(Error::corrupt( | ||
| 129 | + "Ogg: no logical stream with a known mapping", | ||
| 130 | + )); | ||
| 131 | + } | ||
| 132 | + // Headers that never completed: whatever streams were found | ||
| 133 | + // are described as far as their headers went. | ||
| 134 | + false => { | ||
| 135 | + self.data_start = self.inner.stream_position()?; | ||
| 136 | + return Ok(()); | ||
| 137 | + } | ||
| 138 | + }, | ||
| 139 | + } | ||
| 140 | + } | ||
| 141 | + } | ||
| 142 | + | ||
| 143 | + /// Walk to the end once to learn each stream's last granule position, then | ||
| 144 | + /// come back. Cheap (a bounded tail scan) and it is the only way an Ogg | ||
| 145 | + /// file states its duration at all. | ||
| 146 | + fn measure_durations(&mut self) -> Result<()> { | ||
| 147 | + let resume = self.inner.stream_position()?; | ||
| 148 | + let end = self.inner.seek(SeekFrom::End(0))?; | ||
| 149 | + // Tail window, widened until a page for every stream turns up or the | ||
| 150 | + // whole file has been walked. | ||
| 151 | + let mut window = 64 * 1024; | ||
| 152 | + let mut last: Vec<Option<i64>> = vec![None; self.tracks.len()]; | ||
| 153 | + loop { | ||
| 154 | + let from = end.saturating_sub(window); | ||
| 155 | + self.inner.seek(SeekFrom::Start(from))?; | ||
| 156 | + loop { | ||
| 157 | + match read_page(&mut self.inner)? { | ||
| 158 | + Step::Page(page) => { | ||
| 159 | + if let Some(i) = self.track_index(page.header.serial) | ||
| 160 | + && page.header.granule != page::NO_GRANULE | ||
| 161 | + { | ||
| 162 | + last[i] = Some(page.header.granule); | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + Step::Damaged => continue, | ||
| 166 | + Step::End => break, | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | + if last.iter().all(Option::is_some) || from == 0 { | ||
| 170 | + break; | ||
| 171 | + } | ||
| 172 | + window *= 8; | ||
| 173 | + } | ||
| 174 | + for (i, granule) in last.into_iter().enumerate() { | ||
| 175 | + if let Some(granule) = granule { | ||
| 176 | + let start = self.streams[i].start_time.unwrap_or(0); | ||
| 177 | + self.streams[i].duration = Some((granule - start).max(0)); | ||
| 178 | + } | ||
| 179 | + } | ||
| 180 | + self.inner.seek(SeekFrom::Start(resume))?; | ||
| 181 | + Ok(()) | ||
| 182 | + } | ||
| 183 | + | ||
| 184 | + fn track_index(&self, serial: u32) -> Option<usize> { | ||
| 185 | + self.tracks.iter().position(|t| t.serial == serial) | ||
| 186 | + } | ||
| 187 | + | ||
| 188 | + /// Turn one page into packets: header packets into the stream description, | ||
| 189 | + /// audio packets into the queue. | ||
| 190 | + fn consume(&mut self, page: RawPage) -> Result<()> { | ||
| 191 | + let serial = page.header.serial; | ||
| 192 | + let index = match self.track_index(serial) { | ||
| 193 | + Some(i) => i, | ||
| 194 | + None => match page.header.bos { | ||
| 195 | + true => match self.start_track(&page) { | ||
| 196 | + Some(i) => i, | ||
| 197 | + // A mapping nothing in this family claims (Theora, Skeleton, | ||
| 198 | + // a private stream): its pages are skipped, not an error — | ||
| 199 | + // the audio streams beside it still read. | ||
| 200 | + None => return Ok(()), | ||
| 201 | + }, | ||
| 202 | + false => return Ok(()), | ||
| 203 | + }, | ||
| 204 | + }; | ||
| 205 | + | ||
| 206 | + let mapping = self.tracks[index].mapping; | ||
| 207 | + let time_base = self.streams[index].time_base; | ||
| 208 | + let mut packet = std::mem::take(&mut self.tracks[index].partial); | ||
| 209 | + let mut assembling = self.tracks[index].assembling; | ||
| 210 | + let mut pos = self.tracks[index].pos; | ||
| 211 | + let mut pos_known = self.tracks[index].pos_known; | ||
| 212 | + let mut headers_done = self.tracks[index].headers_complete(); | ||
| 213 | + let mut at = 0usize; | ||
| 214 | + let mut segments = &page.header.segments[..]; | ||
| 215 | + | ||
| 216 | + match (page.header.continued, assembling) { | ||
| 217 | + // The head of this packet was in a page we never saw: drop segments | ||
| 218 | + // up to and including the first terminator. | ||
| 219 | + (true, false) => { | ||
| 220 | + let mut skipped = 0; | ||
| 221 | + for (i, &lace) in segments.iter().enumerate() { | ||
| 222 | + at += usize::from(lace); | ||
| 223 | + skipped = i + 1; | ||
| 224 | + if lace < 255 { | ||
| 225 | + break; | ||
| 226 | + } | ||
| 227 | + } | ||
| 228 | + segments = &segments[skipped..]; | ||
| 229 | + } | ||
| 230 | + // A packet was mid-assembly and this page does not continue it: the | ||
| 231 | + // partial is orphaned. | ||
| 232 | + (false, true) => { | ||
| 233 | + packet.clear(); | ||
| 234 | + assembling = false; | ||
| 235 | + } | ||
| 236 | + _ => {} | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + let first_new = self.queue.len(); | ||
| 240 | + for &lace in segments { | ||
| 241 | + let end = at + usize::from(lace); | ||
| 242 | + let Some(slice) = page.body.get(at..end) else { | ||
| 243 | + // The segment table promised more body than the page carried. | ||
| 244 | + return Err(Error::corrupt("Ogg page: segment table overruns the body")); | ||
| 245 | + }; | ||
| 246 | + packet.extend_from_slice(slice); | ||
| 247 | + at = end; | ||
| 248 | + if lace == 255 { | ||
| 249 | + assembling = true; | ||
| 250 | + continue; | ||
| 251 | + } | ||
| 252 | + assembling = false; | ||
| 253 | + let done = std::mem::take(&mut packet); | ||
| 254 | + match headers_done { | ||
| 255 | + false => { | ||
| 256 | + self.tracks[index].headers.push(done); | ||
| 257 | + if self.tracks[index].headers_complete() { | ||
| 258 | + headers_done = true; | ||
| 259 | + self.finish_stream(index)?; | ||
| 260 | + } | ||
| 261 | + } | ||
| 262 | + true => { | ||
| 263 | + // The zero-length segment a muxer uses to carry an | ||
| 264 | + // end-of-stream flag on an otherwise empty page is not a | ||
| 265 | + // packet; handing it out would inflate every packet count. | ||
| 266 | + if done.is_empty() { | ||
| 267 | + continue; | ||
| 268 | + } | ||
| 269 | + let duration = mapping.packet_duration(&done); | ||
| 270 | + let mut out = Packet::new(index as u32, time_base, done); | ||
| 271 | + out.pts = pos_known.then_some(pos); | ||
| 272 | + out.dts = out.pts; | ||
| 273 | + out.duration = duration; | ||
| 274 | + // Every Ogg audio packet is a decodable entry point as far | ||
| 275 | + // as the container is concerned; codec pre-roll (a Vorbis | ||
| 276 | + // block needs its predecessor to overlap) is the decoder's. | ||
| 277 | + out.flags.keyframe = true; | ||
| 278 | + match duration { | ||
| 279 | + Some(d) if pos_known => pos += d, | ||
| 280 | + Some(_) => {} | ||
| 281 | + None => pos_known = false, | ||
| 282 | + } | ||
| 283 | + self.queue.push_back(out); | ||
| 284 | + } | ||
| 285 | + } | ||
| 286 | + } | ||
| 287 | + let track = &mut self.tracks[index]; | ||
| 288 | + track.partial = packet; | ||
| 289 | + track.assembling = assembling; | ||
| 290 | + track.pos = pos; | ||
| 291 | + track.pos_known = pos_known; | ||
| 292 | + track.eos |= page.header.eos; | ||
| 293 | + | ||
| 294 | + // The granule is where the last packet finishing on this page ends, so | ||
| 295 | + // it is also where the next one starts — the point every mapping's | ||
| 296 | + // timing is re-anchored to. | ||
| 297 | + if page.header.granule != page::NO_GRANULE { | ||
| 298 | + if self.queue.len() > first_new { | ||
| 299 | + let last = self.queue.len() - 1; | ||
| 300 | + self.queue[last] | ||
| 301 | + .side_data | ||
| 302 | + .push(granule_side_data(page.header.granule)); | ||
| 303 | + } | ||
| 304 | + let track = &mut self.tracks[index]; | ||
| 305 | + track.pos = page.header.granule; | ||
| 306 | + track.pos_known = true; | ||
| 307 | + } | ||
| 308 | + Ok(()) | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + /// A beginning-of-stream page: identify the mapping from its first packet. | ||
| 312 | + fn start_track(&mut self, page: &RawPage) -> Option<usize> { | ||
| 313 | + let len = usize::from(*page.header.segments.first()?); | ||
| 314 | + let first = page.body.get(..len)?; | ||
| 315 | + let mapping = Mapping::identify(first)?; | ||
| 316 | + let mut params = CodecParameters::new(mapping.codec()); | ||
| 317 | + if let MediaParameters::Audio(audio) = &mut params.media { | ||
| 318 | + audio.sample_rate = mapping.sample_rate(); | ||
| 319 | + audio.layout = mapping.layout(); | ||
| 320 | + } | ||
| 321 | + let index = self.tracks.len(); | ||
| 322 | + let mut info = StreamInfo::new(index as u32, mapping.time_base(), params); | ||
| 323 | + info.start_time = Some(match mapping { | ||
| 324 | + // Opus granules include the samples a decoder throws away, so | ||
| 325 | + // presentation starts at the pre-skip rather than at zero. | ||
| 326 | + Mapping::Opus { pre_skip, .. } => i64::from(pre_skip), | ||
| 327 | + _ => 0, | ||
| 328 | + }); | ||
| 329 | + self.streams.push(info); | ||
| 330 | + self.tracks.push(Track { | ||
| 331 | + serial: page.header.serial, | ||
| 332 | + mapping, | ||
| 333 | + headers: Vec::new(), | ||
| 334 | + partial: Vec::new(), | ||
| 335 | + assembling: false, | ||
| 336 | + pos: 0, | ||
| 337 | + pos_known: true, | ||
| 338 | + eos: false, | ||
| 339 | + }); | ||
| 340 | + Some(index) | ||
| 341 | + } | ||
| 342 | + | ||
| 343 | + /// All header packets are in: publish them as `extradata`. | ||
| 344 | + fn finish_stream(&mut self, index: usize) -> Result<()> { | ||
| 345 | + let track = &self.tracks[index]; | ||
| 346 | + let extradata = match track.mapping { | ||
| 347 | + // The three-packet triplet, laced the way every consumer of Vorbis | ||
| 348 | + // extradata outside Ogg expects it. | ||
| 349 | + Mapping::Vorbis { .. } => { | ||
| 350 | + let refs: Vec<&[u8]> = track.headers.iter().map(Vec::as_slice).collect(); | ||
| 351 | + xiph_lace(&refs) | ||
| 352 | + } | ||
| 353 | + // RFC 7845 identification header, verbatim; the tags packet is | ||
| 354 | + // metadata, not decoder setup. | ||
| 355 | + Mapping::Opus { .. } | Mapping::Flac { .. } => Some(track.headers[0].clone()), | ||
| 356 | + }; | ||
| 357 | + self.streams[index].params.extradata = extradata.map(Buf::from_vec); | ||
| 358 | + Ok(()) | ||
| 359 | + } | ||
| 360 | + | ||
| 361 | + /// Scan forward from `offset` for the next page of `serial`. | ||
| 362 | + fn page_at_or_after(&mut self, offset: u64, serial: u32) -> Result<Option<(u64, i64)>> { | ||
| 363 | + self.inner.seek(SeekFrom::Start(offset))?; | ||
| 364 | + loop { | ||
| 365 | + match read_page(&mut self.inner)? { | ||
| 366 | + Step::Page(page) if page.header.serial == serial => { | ||
| 367 | + return Ok(Some((page.offset, page.header.granule))); | ||
| 368 | + } | ||
| 369 | + Step::Page(_) | Step::Damaged => continue, | ||
| 370 | + Step::End => return Ok(None), | ||
| 371 | + } | ||
| 372 | + } | ||
| 373 | + } | ||
| 374 | + | ||
| 375 | + /// Drop assembly state and queued packets after a jump. | ||
| 376 | + fn reset_state(&mut self) { | ||
| 377 | + self.queue.clear(); | ||
| 378 | + for track in &mut self.tracks { | ||
| 379 | + track.partial.clear(); | ||
| 380 | + track.assembling = false; | ||
| 381 | + track.pos_known = false; | ||
| 382 | + track.eos = false; | ||
| 383 | + } | ||
| 384 | + } | ||
| 385 | +} | ||
| 386 | + | ||
| 387 | +impl<R: Read + Seek + Send> Demuxer for OggDemuxer<R> { | ||
| 388 | + fn streams(&self) -> &[StreamInfo] { | ||
| 389 | + &self.streams | ||
| 390 | + } | ||
| 391 | + | ||
| 392 | + fn next_packet(&mut self) -> Result<Packet> { | ||
| 393 | + loop { | ||
| 394 | + if let Some(packet) = self.queue.pop_front() { | ||
| 395 | + return Ok(packet); | ||
| 396 | + } | ||
| 397 | + match read_page(&mut self.inner)? { | ||
| 398 | + Step::Page(page) => self.consume(page)?, | ||
| 399 | + Step::Damaged => self.damaged += 1, | ||
| 400 | + Step::End => return Err(Error::Eof), | ||
| 401 | + } | ||
| 402 | + } | ||
| 403 | + } | ||
| 404 | + | ||
| 405 | + /// Land on a page boundary at or before `to` by bisecting the file on | ||
| 406 | + /// granule positions — the only index Ogg has. | ||
| 407 | + /// | ||
| 408 | + /// [`SeekMode::Exact`] is served as [`SeekMode::SyncBefore`]: pages are the | ||
| 409 | + /// finest position the container offers, and a decoder that needs the | ||
| 410 | + /// sample exactly discards forward from there. | ||
| 411 | + fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { | ||
| 412 | + let index = usize::try_from(stream).unwrap_or(usize::MAX); | ||
| 413 | + let info = self | ||
| 414 | + .streams | ||
| 415 | + .get(index) | ||
| 416 | + .ok_or_else(|| Error::corrupt(format!("Ogg seek: no stream {stream}")))?; | ||
| 417 | + let serial = self.tracks[index].serial; | ||
| 418 | + let target = to.rescale(info.time_base, ec_core::Rounding::Down).ticks; | ||
| 419 | + | ||
| 420 | + let end = self.inner.seek(SeekFrom::End(0))?; | ||
| 421 | + let mut lo = self.data_start; | ||
| 422 | + let mut hi = end; | ||
| 423 | + // Last page start whose granule is at or before the target, and the | ||
| 424 | + // first one at or after it — one bisection answers both. | ||
| 425 | + let mut before = self.data_start; | ||
| 426 | + let mut after = None; | ||
| 427 | + while lo < hi { | ||
| 428 | + let mid = lo + (hi - lo) / 2; | ||
| 429 | + match self.page_at_or_after(mid, serial)? { | ||
| 430 | + Some((offset, granule)) if granule != page::NO_GRANULE && granule <= target => { | ||
| 431 | + before = offset; | ||
| 432 | + // Always make progress: the found page may start before mid. | ||
| 433 | + lo = offset.max(mid) + 1; | ||
| 434 | + } | ||
| 435 | + Some((offset, granule)) if granule != page::NO_GRANULE => { | ||
| 436 | + after = Some(offset); | ||
| 437 | + hi = match offset > mid { | ||
| 438 | + true => mid, | ||
| 439 | + false => offset, | ||
| 440 | + }; | ||
| 441 | + } | ||
| 442 | + // A page with no granule says nothing about position; step past | ||
| 443 | + // it rather than splitting the same interval forever. | ||
| 444 | + Some((offset, _)) => lo = offset.max(mid) + 1, | ||
| 445 | + None => hi = mid, | ||
| 446 | + } | ||
| 447 | + } | ||
| 448 | + let landing = match mode { | ||
| 449 | + SeekMode::SyncAfter => after.unwrap_or(before), | ||
| 450 | + _ => before, | ||
| 451 | + }; | ||
| 452 | + self.reset_state(); | ||
| 453 | + self.inner.seek(SeekFrom::Start(landing))?; | ||
| 454 | + Ok(()) | ||
| 455 | + } | ||
| 456 | +} | ||
| 457 | + | ||
| 458 | +/// Read one page: scan for the capture pattern, verify the checksum, hand back | ||
| 459 | +/// header and body. | ||
| 460 | +fn read_page<R: Read + Seek>(inner: &mut BufReader<R>) -> Result<Step> { | ||
| 461 | + let mut fixed = [0u8; page::HEADER_LEN]; | ||
| 462 | + let mut window = 0usize; | ||
| 463 | + // Scan for "OggS". The pattern has no proper prefix that is also a suffix, | ||
| 464 | + // so a failed match can never hide the start of a real one. | ||
| 465 | + while window < 4 { | ||
| 466 | + let mut byte = [0u8; 1]; | ||
| 467 | + match inner.read(&mut byte) { | ||
| 468 | + Ok(0) => return Ok(Step::End), | ||
| 469 | + Ok(_) => {} | ||
| 470 | + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, | ||
| 471 | + Err(e) => return Err(e.into()), | ||
| 472 | + } | ||
| 473 | + window = match byte[0] == page::CAPTURE[window] { | ||
| 474 | + true => window + 1, | ||
| 475 | + false => usize::from(byte[0] == page::CAPTURE[0]), | ||
| 476 | + }; | ||
| 477 | + } | ||
| 478 | + let offset = inner.stream_position()? - 4; | ||
| 479 | + fixed[..4].copy_from_slice(&page::CAPTURE); | ||
| 480 | + if read_exact_or_end(inner, &mut fixed[4..])? { | ||
| 481 | + return Ok(Step::End); | ||
| 482 | + } | ||
| 483 | + | ||
| 484 | + let Ok((mut header, nsegs)) = PageHeader::parse_fixed(&fixed) else { | ||
| 485 | + inner.seek(SeekFrom::Start(offset + 4))?; | ||
| 486 | + return Ok(Step::Damaged); | ||
| 487 | + }; | ||
| 488 | + let mut segments = vec![0u8; nsegs]; | ||
| 489 | + if read_exact_or_end(inner, &mut segments)? { | ||
| 490 | + return Ok(Step::End); | ||
| 491 | + } | ||
| 492 | + header.segments = segments; | ||
| 493 | + let mut body = vec![0u8; header.body_len()]; | ||
| 494 | + if read_exact_or_end(inner, &mut body)? { | ||
| 495 | + return Ok(Step::End); | ||
| 496 | + } | ||
| 497 | + | ||
| 498 | + let stored = PageHeader::stored_crc(&fixed); | ||
| 499 | + let mut zeroed = fixed; | ||
| 500 | + zeroed[22..26].fill(0); | ||
| 501 | + if crate::crc::crc32(&[&zeroed, &header.segments, &body]) != stored { | ||
| 502 | + // Damage is local: resume scanning right after this capture pattern so | ||
| 503 | + // the very next intact page is found. | ||
| 504 | + inner.seek(SeekFrom::Start(offset + 4))?; | ||
| 505 | + return Ok(Step::Damaged); | ||
| 506 | + } | ||
| 507 | + Ok(Step::Page(RawPage { | ||
| 508 | + header, | ||
| 509 | + body, | ||
| 510 | + offset, | ||
| 511 | + })) | ||
| 512 | +} | ||
| 513 | + | ||
| 514 | +/// `read_exact`, with a truncated file reported as end rather than as an error: | ||
| 515 | +/// a half-written page at EOF is the normal shape of an interrupted recording. | ||
| 516 | +fn read_exact_or_end<R: Read>(inner: &mut BufReader<R>, buf: &mut [u8]) -> Result<bool> { | ||
| 517 | + match inner.read_exact(buf) { | ||
| 518 | + Ok(()) => Ok(false), | ||
| 519 | + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(true), | ||
| 520 | + Err(e) => Err(e.into()), | ||
| 521 | + } | ||
| 522 | +} | ||
crates/ec-ogg/src/lib.rsadded+89 -0
| @@ -0,0 +1,89 @@ | |||
| 1 | +//! Ogg (RFC 3533): the container Vorbis, Opus and FLAC-in-Ogg travel in. | ||
| 2 | +//! | ||
| 3 | +//! [`OggDemuxer`] reads pages into packets — continuations reassembled, page | ||
| 4 | +//! checksums verified, damaged pages skipped rather than fatal — and | ||
| 5 | +//! [`OggMuxer`] writes packets back into pages with correct lacing, granule | ||
| 6 | +//! positions and beginning/end-of-stream flags. Both speak the family IR, so an | ||
| 7 | +//! Ogg file is `Demuxer` in and `Muxer` out like every other container here. | ||
| 8 | +//! | ||
| 9 | +//! What a granule position *means* belongs to the mapping, not to Ogg | ||
| 10 | +//! ([`Mapping`]): Vorbis and FLAC count samples at the stream's own rate, Opus | ||
| 11 | +//! counts 48 kHz samples including the pre-skip a decoder discards. Timestamps | ||
| 12 | +//! are therefore exact per packet where the mapping states packet durations | ||
| 13 | +//! (Opus does, in its TOC byte) and per page boundary where it does not (Vorbis | ||
| 14 | +//! hides block sizes behind the setup header's codebooks, which is the Vorbis | ||
| 15 | +//! decoder's parse, not the container's). | ||
| 16 | +//! | ||
| 17 | +//! Because a page states where its *last finishing packet* ends, a remux has to | ||
| 18 | +//! carry that position through: [`OggDemuxer`] attaches it to the packet it | ||
| 19 | +//! belongs to as [`SideData::Custom`] with kind [`GRANULE_KIND`], and | ||
| 20 | +//! [`OggMuxer`] reads it back with [`granule_of`]. A packet without one is | ||
| 21 | +//! still written — it simply cannot be the last packet on a page. | ||
| 22 | +//! | ||
| 23 | +//! Not covered: chained streams (a second beginning-of-stream group after the | ||
| 24 | +//! first ends) are read as far as the first chain and no further, Skeleton | ||
| 25 | +//! indexes are ignored, and Theora/Speex pages are skipped rather than | ||
| 26 | +//! described. Each is a mapping this family does not carry yet, not a silent | ||
| 27 | +//! misread. | ||
| 28 | + | ||
| 29 | +#![forbid(unsafe_code)] | ||
| 30 | +#![warn(missing_docs)] | ||
| 31 | + | ||
| 32 | +mod crc; | ||
| 33 | +mod demux; | ||
| 34 | +mod mapping; | ||
| 35 | +mod mux; | ||
| 36 | +mod page; | ||
| 37 | + | ||
| 38 | +pub use demux::OggDemuxer; | ||
| 39 | +pub use ec_core::{Error, Result}; | ||
| 40 | +pub use mapping::{Mapping, opus_packet_samples}; | ||
| 41 | +pub use mux::{DEFAULT_PAGE_TARGET, OggMuxer}; | ||
| 42 | +pub use page::{PageHeader, lacing, xiph_lace, xiph_unlace}; | ||
| 43 | + | ||
| 44 | +use ec_core::{Buf, Packet, SideData}; | ||
| 45 | + | ||
| 46 | +/// [`SideData::Custom`] kind carrying an Ogg granule position: eight | ||
| 47 | +/// little-endian bytes of `i64`, the position at which the packet ends in its | ||
| 48 | +/// mapping's own units. | ||
| 49 | +/// | ||
| 50 | +/// Ogg states positions per page rather than per packet, and only for the last | ||
| 51 | +/// packet finishing on each page, so this is present on exactly those packets — | ||
| 52 | +/// it is the one piece of Ogg timing that has nowhere else to live in a | ||
| 53 | +/// `Packet`, and without it a remux would have to guess where its pages end. | ||
| 54 | +pub const GRANULE_KIND: u32 = u32::from_be_bytes(*b"OggS"); | ||
| 55 | + | ||
| 56 | +/// Side data stating that a packet ends at `granule`. | ||
| 57 | +pub fn granule_side_data(granule: i64) -> SideData { | ||
| 58 | + SideData::Custom { | ||
| 59 | + kind: GRANULE_KIND, | ||
| 60 | + data: Buf::from_vec(granule.to_le_bytes().to_vec()), | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// The granule position attached to `packet`, if any. | ||
| 65 | +pub fn granule_of(packet: &Packet) -> Option<i64> { | ||
| 66 | + packet.side_data.iter().find_map(|side| match side { | ||
| 67 | + SideData::Custom { kind, data } if *kind == GRANULE_KIND && data.len() == 8 => { | ||
| 68 | + Some(i64::from_le_bytes(data[..8].try_into().ok()?)) | ||
| 69 | + } | ||
| 70 | + _ => None, | ||
| 71 | + }) | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +#[cfg(test)] | ||
| 75 | +mod tests { | ||
| 76 | + use super::*; | ||
| 77 | + use ec_core::TimeBase; | ||
| 78 | + | ||
| 79 | + #[test] | ||
| 80 | + fn granule_side_data_round_trips() { | ||
| 81 | + let mut packet = Packet::new(0, TimeBase::from_rate(48_000), vec![1, 2, 3]); | ||
| 82 | + assert_eq!(granule_of(&packet), None); | ||
| 83 | + packet.side_data.push(granule_side_data(-1)); | ||
| 84 | + assert_eq!(granule_of(&packet), Some(-1)); | ||
| 85 | + let mut other = Packet::new(0, TimeBase::from_rate(44_100), vec![]); | ||
| 86 | + other.side_data.push(granule_side_data(1_234_567_890_123)); | ||
| 87 | + assert_eq!(granule_of(&other), Some(1_234_567_890_123)); | ||
| 88 | + } | ||
| 89 | +} | ||
crates/ec-ogg/src/mapping.rsadded+237 -0
| @@ -0,0 +1,237 @@ | |||
| 1 | +//! What a logical stream carries, and what its granule positions mean. | ||
| 2 | +//! | ||
| 3 | +//! Ogg itself says nothing about time: a granule position is an opaque integer | ||
| 4 | +//! whose meaning belongs to the *mapping* named by the first packet. Vorbis and | ||
| 5 | +//! FLAC count samples at the stream's own rate; Opus counts samples at 48 kHz | ||
| 6 | +//! whatever the input rate was, and its count includes the pre-skip a decoder | ||
| 7 | +//! throws away (RFC 7845 §4). Everything timing-related in this crate goes | ||
| 8 | +//! through this module so those three conventions live in one place. | ||
| 9 | + | ||
| 10 | +use ec_core::{ChannelLayout, CodecId, TimeBase}; | ||
| 11 | + | ||
| 12 | +/// A recognised logical-stream mapping, with what its identification header | ||
| 13 | +/// stated. | ||
| 14 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 15 | +pub enum Mapping { | ||
| 16 | + /// Vorbis I: three header packets, granule counts samples at `rate`. | ||
| 17 | + Vorbis { | ||
| 18 | + /// Sample rate from the identification header. | ||
| 19 | + rate: u32, | ||
| 20 | + /// Channel count from the identification header. | ||
| 21 | + channels: u8, | ||
| 22 | + }, | ||
| 23 | + /// Opus (RFC 7845): `OpusHead` then `OpusTags`, granule counts 48 kHz | ||
| 24 | + /// samples and starts `pre_skip` above the first decoded sample. | ||
| 25 | + Opus { | ||
| 26 | + /// Output channel count. | ||
| 27 | + channels: u8, | ||
| 28 | + /// Samples (at 48 kHz) a decoder discards from the head of the stream. | ||
| 29 | + pre_skip: u16, | ||
| 30 | + /// Rate the encoder was fed, informational only — granules stay 48 kHz. | ||
| 31 | + input_rate: u32, | ||
| 32 | + }, | ||
| 33 | + /// FLAC-in-Ogg: `\x7fFLAC` mapping header carrying `fLaC` + STREAMINFO, | ||
| 34 | + /// granule counts samples at `rate`. | ||
| 35 | + Flac { | ||
| 36 | + /// Sample rate from STREAMINFO. | ||
| 37 | + rate: u32, | ||
| 38 | + /// Channel count from STREAMINFO. | ||
| 39 | + channels: u8, | ||
| 40 | + /// Header packets this stream declares, the identification one included. | ||
| 41 | + headers: usize, | ||
| 42 | + }, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +impl Mapping { | ||
| 46 | + /// Recognise a mapping from the first packet of a logical stream, or | ||
| 47 | + /// [`None`] when nothing in the family claims it (Theora, Speex, Skeleton, | ||
| 48 | + /// a private mapping — all valid Ogg, none of them ours). | ||
| 49 | + pub fn identify(bos: &[u8]) -> Option<Mapping> { | ||
| 50 | + if bos.len() >= 16 && bos[0] == 1 && &bos[1..7] == b"vorbis" { | ||
| 51 | + return Some(Mapping::Vorbis { | ||
| 52 | + rate: u32::from_le_bytes(bos[12..16].try_into().ok()?), | ||
| 53 | + channels: bos[11], | ||
| 54 | + }); | ||
| 55 | + } | ||
| 56 | + if bos.len() >= 19 && &bos[..8] == b"OpusHead" { | ||
| 57 | + return Some(Mapping::Opus { | ||
| 58 | + channels: bos[9], | ||
| 59 | + pre_skip: u16::from_le_bytes(bos[10..12].try_into().ok()?), | ||
| 60 | + input_rate: u32::from_le_bytes(bos[12..16].try_into().ok()?), | ||
| 61 | + }); | ||
| 62 | + } | ||
| 63 | + if bos.len() >= 51 && bos[0] == 0x7f && &bos[1..5] == b"FLAC" && &bos[9..13] == b"fLaC" { | ||
| 64 | + // STREAMINFO starts after the mapping header and the metadata block | ||
| 65 | + // header; its rate is 20 bits, then 3 bits of channel count - 1. | ||
| 66 | + let si = &bos[17..51]; | ||
| 67 | + let rate = | ||
| 68 | + (u32::from(si[10]) << 12) | (u32::from(si[11]) << 4) | u32::from(si[12] >> 4); | ||
| 69 | + let declared = usize::from(u16::from_be_bytes([bos[7], bos[8]])); | ||
| 70 | + return Some(Mapping::Flac { | ||
| 71 | + rate, | ||
| 72 | + channels: ((si[12] >> 1) & 0x07) + 1, | ||
| 73 | + // A zero here means "not stated"; the comment header still | ||
| 74 | + // follows, so two is the floor. | ||
| 75 | + headers: (declared + 1).max(2), | ||
| 76 | + }); | ||
| 77 | + } | ||
| 78 | + None | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + /// Which codec decodes this stream's packets. | ||
| 82 | + pub fn codec(&self) -> CodecId { | ||
| 83 | + match self { | ||
| 84 | + Mapping::Vorbis { .. } => CodecId::Vorbis, | ||
| 85 | + Mapping::Opus { .. } => CodecId::Opus, | ||
| 86 | + Mapping::Flac { .. } => CodecId::Flac, | ||
| 87 | + } | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + /// The clock granule positions are counted in. | ||
| 91 | + pub fn time_base(&self) -> TimeBase { | ||
| 92 | + match self { | ||
| 93 | + // Opus granules are always 48 kHz, whatever the encoder was fed. | ||
| 94 | + Mapping::Opus { .. } => TimeBase::from_rate(48_000), | ||
| 95 | + Mapping::Vorbis { rate, .. } | Mapping::Flac { rate, .. } => { | ||
| 96 | + TimeBase::try_new(1, i64::from(*rate)).unwrap_or(TimeBase::from_rate(48_000)) | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + /// Decoded sample rate. | ||
| 102 | + pub fn sample_rate(&self) -> u32 { | ||
| 103 | + match self { | ||
| 104 | + Mapping::Opus { .. } => 48_000, | ||
| 105 | + Mapping::Vorbis { rate, .. } | Mapping::Flac { rate, .. } => *rate, | ||
| 106 | + } | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + /// Channel layout, by count — Vorbis and Opus both order channels the way | ||
| 110 | + /// [`ChannelLayout`] does for the layouts it names. | ||
| 111 | + pub fn layout(&self) -> ChannelLayout { | ||
| 112 | + let channels = match self { | ||
| 113 | + Mapping::Vorbis { channels, .. } | ||
| 114 | + | Mapping::Opus { channels, .. } | ||
| 115 | + | Mapping::Flac { channels, .. } => *channels, | ||
| 116 | + }; | ||
| 117 | + ChannelLayout::from_count(usize::from(channels).max(1)) | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + /// How many packets belong to the stream's header, the identification | ||
| 121 | + /// packet included. Audio starts after them. | ||
| 122 | + pub fn header_packets(&self) -> usize { | ||
| 123 | + match self { | ||
| 124 | + Mapping::Vorbis { .. } => 3, | ||
| 125 | + Mapping::Opus { .. } => 2, | ||
| 126 | + Mapping::Flac { headers, .. } => *headers, | ||
| 127 | + } | ||
| 128 | + } | ||
| 129 | + | ||
| 130 | + /// Samples this packet decodes to, in granule units, when the mapping makes | ||
| 131 | + /// that cheap to know. | ||
| 132 | + /// | ||
| 133 | + /// Opus states it in the first byte of every packet, so its timing is exact | ||
| 134 | + /// packet by packet. Vorbis does not: the block size of a packet is a mode | ||
| 135 | + /// number whose meaning lives at the end of the setup header, past the full | ||
| 136 | + /// codebook parse, which belongs to the Vorbis decoder rather than here — | ||
| 137 | + /// so this answers [`None`] and the demuxer re-synchronises on every page | ||
| 138 | + /// granule instead (see [`crate::demux`]). FLAC frame headers do state a | ||
| 139 | + /// block size, but reading it means the frame parser, same argument. | ||
| 140 | + pub fn packet_duration(&self, data: &[u8]) -> Option<i64> { | ||
| 141 | + match self { | ||
| 142 | + Mapping::Opus { .. } => opus_packet_samples(data), | ||
| 143 | + Mapping::Vorbis { .. } | Mapping::Flac { .. } => None, | ||
| 144 | + } | ||
| 145 | + } | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +/// Samples at 48 kHz one Opus packet decodes to, from its TOC byte | ||
| 149 | +/// (RFC 6716 §3.1): a configuration number picking the frame duration, and a | ||
| 150 | +/// code picking how many frames are packed behind it. | ||
| 151 | +pub fn opus_packet_samples(data: &[u8]) -> Option<i64> { | ||
| 152 | + let toc = *data.first()?; | ||
| 153 | + let config = usize::from(toc >> 3); | ||
| 154 | + // Frame duration in 48 kHz samples, per configuration block: SILK modes | ||
| 155 | + // step 10/20/40/60 ms, hybrid 10/20 ms, CELT 2.5/5/10/20 ms. | ||
| 156 | + let samples = match config { | ||
| 157 | + 0..=11 => [480, 960, 1920, 2880][config % 4], | ||
| 158 | + 12..=15 => [480, 960][config % 2], | ||
| 159 | + _ => [120, 240, 480, 960][config % 4], | ||
| 160 | + }; | ||
| 161 | + let frames = match toc & 0x03 { | ||
| 162 | + 0 => 1, | ||
| 163 | + 1 | 2 => 2, | ||
| 164 | + // Code 3 states the count in the low six bits of the next byte. | ||
| 165 | + _ => i64::from(*data.get(1)? & 0x3f), | ||
| 166 | + }; | ||
| 167 | + // RFC 6716 §3.1: a packet may not exceed 120 ms of audio. | ||
| 168 | + match frames * samples { | ||
| 169 | + n if n > 0 && n <= 5760 => Some(n), | ||
| 170 | + _ => None, | ||
| 171 | + } | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +#[cfg(test)] | ||
| 175 | +mod tests { | ||
| 176 | + use super::*; | ||
| 177 | + | ||
| 178 | + #[test] | ||
| 179 | + fn identifies_the_three_mappings() { | ||
| 180 | + let mut vorbis = vec![1u8]; | ||
| 181 | + vorbis.extend_from_slice(b"vorbis"); | ||
| 182 | + vorbis.extend_from_slice(&0u32.to_le_bytes()); // version | ||
| 183 | + vorbis.push(2); // channels | ||
| 184 | + vorbis.extend_from_slice(&44_100u32.to_le_bytes()); | ||
| 185 | + vorbis.resize(30, 0); | ||
| 186 | + assert_eq!( | ||
| 187 | + Mapping::identify(&vorbis), | ||
| 188 | + Some(Mapping::Vorbis { | ||
| 189 | + rate: 44_100, | ||
| 190 | + channels: 2 | ||
| 191 | + }) | ||
| 192 | + ); | ||
| 193 | + | ||
| 194 | + let mut opus = Vec::from(*b"OpusHead"); | ||
| 195 | + opus.push(1); // version | ||
| 196 | + opus.push(6); // channels | ||
| 197 | + opus.extend_from_slice(&312u16.to_le_bytes()); // pre-skip | ||
| 198 | + opus.extend_from_slice(&48_000u32.to_le_bytes()); | ||
| 199 | + opus.resize(19, 0); | ||
| 200 | + let mapping = Mapping::identify(&opus).unwrap(); | ||
| 201 | + assert_eq!( | ||
| 202 | + mapping, | ||
| 203 | + Mapping::Opus { | ||
| 204 | + channels: 6, | ||
| 205 | + pre_skip: 312, | ||
| 206 | + input_rate: 48_000 | ||
| 207 | + } | ||
| 208 | + ); | ||
| 209 | + // Whatever the input rate said, granules count 48 kHz samples. | ||
| 210 | + assert_eq!(mapping.time_base(), TimeBase::from_rate(48_000)); | ||
| 211 | + assert_eq!(mapping.layout(), ChannelLayout::Surround5_1); | ||
| 212 | + assert_eq!(mapping.header_packets(), 2); | ||
| 213 | + | ||
| 214 | + assert_eq!(Mapping::identify(b"not a header at all"), None); | ||
| 215 | + assert_eq!(Mapping::identify(&[]), None); | ||
| 216 | + } | ||
| 217 | + | ||
| 218 | + #[test] | ||
| 219 | + fn opus_durations_follow_the_toc() { | ||
| 220 | + // config 16 (CELT 2.5 ms), one frame. | ||
| 221 | + assert_eq!(opus_packet_samples(&[16 << 3]), Some(120)); | ||
| 222 | + // config 31 (CELT 20 ms), one frame; the 960 that every 48 kHz encoder | ||
| 223 | + // in this family emits by default. | ||
| 224 | + assert_eq!(opus_packet_samples(&[31 << 3]), Some(960)); | ||
| 225 | + // ...same config, code 1: two frames, so twice the samples. | ||
| 226 | + assert_eq!(opus_packet_samples(&[(31 << 3) | 1]), Some(1920)); | ||
| 227 | + // Code 3 takes its frame count from the next byte, and 120 ms is the | ||
| 228 | + // ceiling the RFC sets — 7 frames of 20 ms is over it. | ||
| 229 | + assert_eq!(opus_packet_samples(&[(31 << 3) | 3, 6]), Some(5760)); | ||
| 230 | + assert_eq!(opus_packet_samples(&[(31 << 3) | 3, 7]), None); | ||
| 231 | + assert_eq!(opus_packet_samples(&[(31 << 3) | 3, 0]), None); | ||
| 232 | + assert_eq!(opus_packet_samples(&[(31 << 3) | 3]), None); | ||
| 233 | + // SILK 60 ms narrowband. | ||
| 234 | + assert_eq!(opus_packet_samples(&[3 << 3]), Some(2880)); | ||
| 235 | + assert_eq!(opus_packet_samples(&[]), None); | ||
| 236 | + } | ||
| 237 | +} | ||
crates/ec-ogg/src/mux.rsadded+372 -0
| @@ -0,0 +1,372 @@ | |||
| 1 | +//! Writing: packets in, pages out. | ||
| 2 | +//! | ||
| 3 | +//! Two rules shape every page this writes. A granule position states where the | ||
| 4 | +//! *last packet finishing on that page* ends, so a page is only ever closed | ||
| 5 | +//! after a packet whose position is known — [`crate::granule_of`] on the packet, | ||
| 6 | +//! or `pts + duration` when both are stated. And the header packets of every | ||
| 7 | +//! mapping in this family get pages of their own: the identification packet | ||
| 8 | +//! alone on the beginning-of-stream page, the rest flushed before the first | ||
| 9 | +//! audio byte, which is what Vorbis I and RFC 7845 §3 both require. | ||
| 10 | +//! | ||
| 11 | +//! Page size is targeted, not fixed: packets are packed until the body passes | ||
| 12 | +//! [`OggMuxer::set_page_target_bytes`] (4 KiB by default, the size RFC 3533 | ||
| 13 | +//! calls usual) and the next packet boundary with a known granule arrives. | ||
| 14 | +//! Packets larger than a page are split across pages with the continuation flag, | ||
| 15 | +//! and a page never carries more than 255 segments. | ||
| 16 | + | ||
| 17 | +use std::io::Write; | ||
| 18 | + | ||
| 19 | +use ec_core::{Error, Muxer, Packet, Result, StreamInfo}; | ||
| 20 | + | ||
| 21 | +use crate::mapping::Mapping; | ||
| 22 | +use crate::page::{self, PageHeader}; | ||
| 23 | +use crate::{granule_of, xiph_unlace}; | ||
| 24 | + | ||
| 25 | +/// Default page body target: RFC 3533 describes pages as "usually 4-8 kB", and | ||
| 26 | +/// one packet per page (the alternative) costs 28 bytes of header per 20 ms of | ||
| 27 | +/// audio. | ||
| 28 | +pub const DEFAULT_PAGE_TARGET: usize = 4096; | ||
| 29 | + | ||
| 30 | +/// Vendor string in a synthesized `OpusTags` packet. | ||
| 31 | +const VENDOR: &str = "ec-ogg"; | ||
| 32 | + | ||
| 33 | +/// One logical stream being written. | ||
| 34 | +struct MuxTrack { | ||
| 35 | + serial: u32, | ||
| 36 | + /// Header packets in order; the first goes on the beginning-of-stream page. | ||
| 37 | + headers: Vec<Vec<u8>>, | ||
| 38 | + /// True once the caller supplied headers explicitly, which replace whatever | ||
| 39 | + /// `extradata` produced. | ||
| 40 | + headers_from_caller: bool, | ||
| 41 | + /// Lacing values of the page being built. | ||
| 42 | + segments: Vec<u8>, | ||
| 43 | + /// Body of the page being built. | ||
| 44 | + body: Vec<u8>, | ||
| 45 | + /// The page being built opens with the tail of a packet. | ||
| 46 | + continued: bool, | ||
| 47 | + /// Where the last packet finishing on this page ends, if one has. | ||
| 48 | + page_granule: Option<i64>, | ||
| 49 | + /// False when a packet finished on this page without stating its position: | ||
| 50 | + /// the page cannot be closed here without lying about where it ends. | ||
| 51 | + can_end: bool, | ||
| 52 | + /// The first data page has not been written yet. It is closed at the first | ||
| 53 | + /// position the stream states, whatever the size target says: a decoder | ||
| 54 | + /// reads its head trim out of that first granule (a Vorbis stream whose | ||
| 55 | + /// first page ends below what its packets decode to is saying "discard the | ||
| 56 | + /// difference"), and a page target large enough to swallow it would silently | ||
| 57 | + /// add the pre-roll back to the output. | ||
| 58 | + first_page_pending: bool, | ||
| 59 | + sequence: u32, | ||
| 60 | + /// Position written on the last closed page, for the end-of-stream page. | ||
| 61 | + last_granule: i64, | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +impl MuxTrack { | ||
| 65 | + fn pending(&self) -> bool { | ||
| 66 | + !self.segments.is_empty() | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// An Ogg writer over any sink. | ||
| 71 | +pub struct OggMuxer<W: Write> { | ||
| 72 | + out: W, | ||
| 73 | + streams: Vec<StreamInfo>, | ||
| 74 | + tracks: Vec<MuxTrack>, | ||
| 75 | + page_target: usize, | ||
| 76 | + headers_written: bool, | ||
| 77 | + finished: bool, | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +impl<W: Write> OggMuxer<W> { | ||
| 81 | + /// A writer with no streams yet. | ||
| 82 | + pub fn new(out: W) -> OggMuxer<W> { | ||
| 83 | + OggMuxer { | ||
| 84 | + out, | ||
| 85 | + streams: Vec::new(), | ||
| 86 | + tracks: Vec::new(), | ||
| 87 | + page_target: DEFAULT_PAGE_TARGET, | ||
| 88 | + headers_written: false, | ||
| 89 | + finished: false, | ||
| 90 | + } | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + /// Aim for `bytes` of body per page; [`None`] restores | ||
| 94 | + /// [`DEFAULT_PAGE_TARGET`]. A page still ends early when its segment table | ||
| 95 | + /// fills, and still ends late when the next packet boundary has no granule. | ||
| 96 | + pub fn set_page_target_bytes(&mut self, bytes: Option<usize>) { | ||
| 97 | + self.page_target = bytes.unwrap_or(DEFAULT_PAGE_TARGET).max(1); | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + /// Override the serial number of stream `index`. Serials only have to be | ||
| 101 | + /// unique within the file; the default is derived from the index so that | ||
| 102 | + /// two runs over the same input produce the same bytes. | ||
| 103 | + pub fn set_serial(&mut self, index: u32, serial: u32) -> Result<()> { | ||
| 104 | + let track = self | ||
| 105 | + .tracks | ||
| 106 | + .get_mut(index as usize) | ||
| 107 | + .ok_or_else(|| Error::corrupt(format!("Ogg mux: no stream {index}")))?; | ||
| 108 | + track.serial = serial; | ||
| 109 | + Ok(()) | ||
| 110 | + } | ||
| 111 | + | ||
| 112 | + /// Write the beginning-of-stream and remaining header pages of every | ||
| 113 | + /// stream. Called automatically before the first data packet; public | ||
| 114 | + /// because a caller that declares streams and then hits an error still | ||
| 115 | + /// wants a readable file. | ||
| 116 | + pub fn write_headers(&mut self) -> Result<()> { | ||
| 117 | + if self.headers_written { | ||
| 118 | + return Ok(()); | ||
| 119 | + } | ||
| 120 | + if self.tracks.is_empty() { | ||
| 121 | + return Err(Error::corrupt("Ogg mux: no streams were declared")); | ||
| 122 | + } | ||
| 123 | + // Every beginning-of-stream page first, in declaration order, before any | ||
| 124 | + // other page in the file (RFC 3533 §4). | ||
| 125 | + for index in 0..self.tracks.len() { | ||
| 126 | + let first = match self.tracks[index].headers.first() { | ||
| 127 | + Some(packet) => packet.clone(), | ||
| 128 | + None => { | ||
| 129 | + return Err(Error::corrupt(format!( | ||
| 130 | + "Ogg mux: stream {index} has no identification header (extradata was empty \ | ||
| 131 | + and no header packet was written)" | ||
| 132 | + ))); | ||
| 133 | + } | ||
| 134 | + }; | ||
| 135 | + self.push_packet(index, &first, Some(0))?; | ||
| 136 | + self.flush_page(index, true, false)?; | ||
| 137 | + } | ||
| 138 | + // Then the remaining headers, each stream's flushed before any audio. | ||
| 139 | + for index in 0..self.tracks.len() { | ||
| 140 | + let rest: Vec<Vec<u8>> = self.tracks[index].headers[1..].to_vec(); | ||
| 141 | + for packet in rest { | ||
| 142 | + self.push_packet(index, &packet, Some(0))?; | ||
| 143 | + } | ||
| 144 | + if self.tracks[index].pending() { | ||
| 145 | + self.flush_page(index, false, false)?; | ||
| 146 | + } | ||
| 147 | + } | ||
| 148 | + self.headers_written = true; | ||
| 149 | + Ok(()) | ||
| 150 | + } | ||
| 151 | + | ||
| 152 | + /// Append one packet's segments to the page being built, splitting across | ||
| 153 | + /// pages when the segment table fills. | ||
| 154 | + fn push_packet(&mut self, index: usize, data: &[u8], granule: Option<i64>) -> Result<()> { | ||
| 155 | + // Prefer a clean packet boundary to a continuation: if the packet cannot | ||
| 156 | + // fit in what is left of the segment table, close the page first — as | ||
| 157 | + // long as closing it here would state a truthful position. | ||
| 158 | + let needed = data.len() / 255 + 1; | ||
| 159 | + let track = &self.tracks[index]; | ||
| 160 | + if track.pending() && track.can_end && track.segments.len() + needed > page::MAX_SEGMENTS { | ||
| 161 | + self.flush_page(index, false, false)?; | ||
| 162 | + } | ||
| 163 | + | ||
| 164 | + let mut at = 0usize; | ||
| 165 | + for lace in page::lacing(data.len()) { | ||
| 166 | + if self.tracks[index].segments.len() == page::MAX_SEGMENTS { | ||
| 167 | + // Forced mid-packet: no packet finishes on this page, which is | ||
| 168 | + // exactly what a -1 granule means. | ||
| 169 | + self.flush_page(index, false, false)?; | ||
| 170 | + self.tracks[index].continued = true; | ||
| 171 | + } | ||
| 172 | + let track = &mut self.tracks[index]; | ||
| 173 | + track.segments.push(lace); | ||
| 174 | + track | ||
| 175 | + .body | ||
| 176 | + .extend_from_slice(&data[at..at + usize::from(lace)]); | ||
| 177 | + at += usize::from(lace); | ||
| 178 | + } | ||
| 179 | + | ||
| 180 | + // A page may only end where the *last* packet finishing on it states | ||
| 181 | + // its position, so this tracks the latest packet, not the latest known | ||
| 182 | + // granule: one positionless packet after a positioned one closes the | ||
| 183 | + // page again. | ||
| 184 | + let track = &mut self.tracks[index]; | ||
| 185 | + match granule { | ||
| 186 | + Some(granule) => { | ||
| 187 | + track.page_granule = Some(granule); | ||
| 188 | + track.can_end = true; | ||
| 189 | + } | ||
| 190 | + None => track.can_end = false, | ||
| 191 | + } | ||
| 192 | + Ok(()) | ||
| 193 | + } | ||
| 194 | + | ||
| 195 | + /// Write the page under construction. | ||
| 196 | + fn flush_page(&mut self, index: usize, bos: bool, eos: bool) -> Result<()> { | ||
| 197 | + let track = &mut self.tracks[index]; | ||
| 198 | + if track.segments.is_empty() && !eos { | ||
| 199 | + return Ok(()); | ||
| 200 | + } | ||
| 201 | + let granule = match (track.can_end, track.page_granule) { | ||
| 202 | + (true, Some(granule)) => granule, | ||
| 203 | + // An end-of-stream page with nothing left to carry still states | ||
| 204 | + // where the stream ends, or a player has no length to trim to. | ||
| 205 | + (_, None) if eos && track.segments.is_empty() => track.last_granule, | ||
| 206 | + _ => page::NO_GRANULE, | ||
| 207 | + }; | ||
| 208 | + let header = PageHeader { | ||
| 209 | + continued: track.continued, | ||
| 210 | + bos, | ||
| 211 | + eos, | ||
| 212 | + granule, | ||
| 213 | + serial: track.serial, | ||
| 214 | + sequence: track.sequence, | ||
| 215 | + // A page always carries at least one lacing value, even an | ||
| 216 | + // end-of-stream page with nothing left to say. | ||
| 217 | + segments: match track.segments.is_empty() { | ||
| 218 | + true => vec![0], | ||
| 219 | + false => std::mem::take(&mut track.segments), | ||
| 220 | + }, | ||
| 221 | + }; | ||
| 222 | + let body = std::mem::take(&mut track.body); | ||
| 223 | + track.sequence += 1; | ||
| 224 | + track.continued = false; | ||
| 225 | + track.page_granule = None; | ||
| 226 | + track.can_end = true; | ||
| 227 | + if granule != page::NO_GRANULE { | ||
| 228 | + track.last_granule = granule; | ||
| 229 | + } | ||
| 230 | + | ||
| 231 | + let mut bytes = Vec::with_capacity(page::HEADER_LEN + header.segments.len() + body.len()); | ||
| 232 | + header.write_page(&body, &mut bytes); | ||
| 233 | + self.out.write_all(&bytes)?; | ||
| 234 | + Ok(()) | ||
| 235 | + } | ||
| 236 | + | ||
| 237 | + /// Header packets from `extradata`, per mapping. | ||
| 238 | + fn headers_from_extradata(info: &StreamInfo) -> Result<Vec<Vec<u8>>> { | ||
| 239 | + let Some(extradata) = info.params.extradata.as_ref().filter(|e| !e.is_empty()) else { | ||
| 240 | + return Ok(Vec::new()); | ||
| 241 | + }; | ||
| 242 | + // Xiph-laced extradata carries the whole triplet; a bare identification | ||
| 243 | + // packet does not, and Vorbis has no way to invent the other two. | ||
| 244 | + if let Ok(packets) = xiph_unlace(extradata) | ||
| 245 | + && packets.len() >= 2 | ||
| 246 | + && Mapping::identify(packets[0]).is_some() | ||
| 247 | + { | ||
| 248 | + return Ok(packets.into_iter().map(<[u8]>::to_vec).collect()); | ||
| 249 | + } | ||
| 250 | + match Mapping::identify(extradata) { | ||
| 251 | + Some(Mapping::Opus { .. }) => Ok(vec![extradata.to_vec(), opus_tags()]), | ||
| 252 | + Some(Mapping::Vorbis { .. }) => Err(Error::corrupt( | ||
| 253 | + "Ogg mux: Vorbis extradata holds only the identification header; the comment and \ | ||
| 254 | + setup headers are needed too (Xiph-laced, as xiph_lace produces)", | ||
| 255 | + )), | ||
| 256 | + // Anything else — a FLAC mapping header, a codec this crate does not | ||
| 257 | + // name — is written verbatim as the first header packet, with the | ||
| 258 | + // rest expected as header-flagged packets. | ||
| 259 | + _ => Ok(vec![extradata.to_vec()]), | ||
| 260 | + } | ||
| 261 | + } | ||
| 262 | +} | ||
| 263 | + | ||
| 264 | +/// A minimal `OpusTags` packet: RFC 7845 §5 requires one, and a remux that only | ||
| 265 | +/// carried `OpusHead` has no comments to preserve. | ||
| 266 | +fn opus_tags() -> Vec<u8> { | ||
| 267 | + let mut out = Vec::from(*b"OpusTags"); | ||
| 268 | + out.extend_from_slice(&(VENDOR.len() as u32).to_le_bytes()); | ||
| 269 | + out.extend_from_slice(VENDOR.as_bytes()); | ||
| 270 | + out.extend_from_slice(&0u32.to_le_bytes()); // comment count | ||
| 271 | + out | ||
| 272 | +} | ||
| 273 | + | ||
| 274 | +impl<W: Write + Send> Muxer for OggMuxer<W> { | ||
| 275 | + fn add_stream(&mut self, info: StreamInfo) -> Result<u32> { | ||
| 276 | + if self.headers_written { | ||
| 277 | + return Err(Error::corrupt( | ||
| 278 | + "Ogg mux: every stream is declared before the first packet", | ||
| 279 | + )); | ||
| 280 | + } | ||
| 281 | + let index = self.tracks.len() as u32; | ||
| 282 | + let headers = OggMuxer::<W>::headers_from_extradata(&info)?; | ||
| 283 | + self.tracks.push(MuxTrack { | ||
| 284 | + // Unique within the file and stable across runs, which keeps a | ||
| 285 | + // remux byte-comparable with itself. | ||
| 286 | + serial: 0x4544_0000 ^ index, | ||
| 287 | + headers, | ||
| 288 | + headers_from_caller: false, | ||
| 289 | + segments: Vec::new(), | ||
| 290 | + body: Vec::new(), | ||
| 291 | + continued: false, | ||
| 292 | + page_granule: None, | ||
| 293 | + can_end: true, | ||
| 294 | + first_page_pending: true, | ||
| 295 | + sequence: 0, | ||
| 296 | + last_granule: 0, | ||
| 297 | + }); | ||
| 298 | + let mut info = info; | ||
| 299 | + info.index = index; | ||
| 300 | + self.streams.push(info); | ||
| 301 | + Ok(index) | ||
| 302 | + } | ||
| 303 | + | ||
| 304 | + /// Write one packet. | ||
| 305 | + /// | ||
| 306 | + /// A packet flagged [`ec_core::PacketFlags::header`] before any audio joins | ||
| 307 | + /// the stream's header packets — the first one replaces whatever | ||
| 308 | + /// `extradata` gave, so a remux can carry the original `OpusTags` through. | ||
| 309 | + /// Otherwise the packet's granule position is [`crate::granule_of`], or | ||
| 310 | + /// `pts + duration` when both are known, or unknown — and a page never ends | ||
| 311 | + /// on a packet whose position is unknown. | ||
| 312 | + fn write_packet(&mut self, packet: &Packet) -> Result<()> { | ||
| 313 | + let index = packet.stream as usize; | ||
| 314 | + if index >= self.tracks.len() { | ||
| 315 | + return Err(Error::corrupt(format!( | ||
| 316 | + "Ogg mux: packet for stream {} of {} declared", | ||
| 317 | + packet.stream, | ||
| 318 | + self.tracks.len() | ||
| 319 | + ))); | ||
| 320 | + } | ||
| 321 | + if packet.flags.header && !self.headers_written { | ||
| 322 | + let track = &mut self.tracks[index]; | ||
| 323 | + if !track.headers_from_caller { | ||
| 324 | + track.headers.clear(); | ||
| 325 | + track.headers_from_caller = true; | ||
| 326 | + } | ||
| 327 | + track.headers.push(packet.data.to_vec()); | ||
| 328 | + return Ok(()); | ||
| 329 | + } | ||
| 330 | + self.write_headers()?; | ||
| 331 | + | ||
| 332 | + // The page is closed *before* the packet that would overflow it, never | ||
| 333 | + // after: that keeps at least one packet pending at all times, so the | ||
| 334 | + // end-of-stream flag rides a page that carries audio. A page whose only | ||
| 335 | + // content is a zero-length packet is legal Ogg and ffmpeg reads it as a | ||
| 336 | + // packet — "Packet processing failed", a decode error in a file that is | ||
| 337 | + // otherwise perfect. | ||
| 338 | + let track = &self.tracks[index]; | ||
| 339 | + let due = track.body.len() >= self.page_target || track.first_page_pending; | ||
| 340 | + if track.pending() && track.can_end && due { | ||
| 341 | + self.flush_page(index, false, false)?; | ||
| 342 | + self.tracks[index].first_page_pending = false; | ||
| 343 | + } | ||
| 344 | + let granule = granule_of(packet).or_else(|| packet.end_pts()); | ||
| 345 | + let data = packet.data.clone(); | ||
| 346 | + self.push_packet(index, &data, granule)?; | ||
| 347 | + Ok(()) | ||
| 348 | + } | ||
| 349 | + | ||
| 350 | + fn finish(&mut self) -> Result<()> { | ||
| 351 | + if self.finished { | ||
| 352 | + return Ok(()); | ||
| 353 | + } | ||
| 354 | + self.write_headers()?; | ||
| 355 | + for index in 0..self.tracks.len() { | ||
| 356 | + // The end-of-stream flag rides the last page — which still carries | ||
| 357 | + // audio, because packets are only paged out on the arrival of the | ||
| 358 | + // next one. Empty only when the stream had no data packets at all. | ||
| 359 | + self.flush_page(index, false, true)?; | ||
| 360 | + } | ||
| 361 | + self.out.flush()?; | ||
| 362 | + self.finished = true; | ||
| 363 | + Ok(()) | ||
| 364 | + } | ||
| 365 | +} | ||
| 366 | + | ||
| 367 | +impl<W: Write> OggMuxer<W> { | ||
| 368 | + /// The sink, for callers that wrote into a buffer and want it back. | ||
| 369 | + pub fn into_inner(self) -> W { | ||
| 370 | + self.out | ||
| 371 | + } | ||
| 372 | +} | ||
crates/ec-ogg/src/page.rsadded+258 -0
| @@ -0,0 +1,258 @@ | |||
| 1 | +//! The page: Ogg's only structural unit (RFC 3533 §6). | ||
| 2 | +//! | ||
| 3 | +//! A page is a 27-byte fixed header, a segment table of 1..=255 lacing values, | ||
| 4 | +//! and a body whose length is the sum of those values. Packets are cut into | ||
| 5 | +//! 255-byte segments; a segment shorter than 255 ends its packet, which is why | ||
| 6 | +//! a packet whose length is an exact multiple of 255 needs a trailing zero-length | ||
| 7 | +//! segment — the single most-missed rule in the format, and the one that makes a | ||
| 8 | +//! decoder wait forever for a packet that already ended. | ||
| 9 | + | ||
| 10 | +use ec_core::{Error, Result}; | ||
| 11 | + | ||
| 12 | +use crate::crc; | ||
| 13 | + | ||
| 14 | +/// Capture pattern every page starts with. | ||
| 15 | +pub const CAPTURE: [u8; 4] = *b"OggS"; | ||
| 16 | +/// Bytes before the segment table. | ||
| 17 | +pub const HEADER_LEN: usize = 27; | ||
| 18 | +/// Most lacing values one page can carry. | ||
| 19 | +pub const MAX_SEGMENTS: usize = 255; | ||
| 20 | +/// Granule position meaning "no packet ends on this page" (RFC 3533 §6.1). | ||
| 21 | +pub const NO_GRANULE: i64 = -1; | ||
| 22 | + | ||
| 23 | +/// `header_type` bits. | ||
| 24 | +const FLAG_CONTINUED: u8 = 0x01; | ||
| 25 | +const FLAG_BOS: u8 = 0x02; | ||
| 26 | +const FLAG_EOS: u8 = 0x04; | ||
| 27 | + | ||
| 28 | +/// A page header, decoded. | ||
| 29 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 30 | +pub struct PageHeader { | ||
| 31 | + /// The first segment continues a packet started on an earlier page. | ||
| 32 | + pub continued: bool, | ||
| 33 | + /// Beginning of stream: this page carries the stream's first packet. | ||
| 34 | + pub bos: bool, | ||
| 35 | + /// End of stream: the last page of this logical stream. | ||
| 36 | + pub eos: bool, | ||
| 37 | + /// Position of the last packet *completed* on this page, in the mapping's | ||
| 38 | + /// own units, or [`NO_GRANULE`] when no packet ends here. | ||
| 39 | + pub granule: i64, | ||
| 40 | + /// Which logical stream this page belongs to. | ||
| 41 | + pub serial: u32, | ||
| 42 | + /// Page counter within the logical stream, from zero. | ||
| 43 | + pub sequence: u32, | ||
| 44 | + /// Lacing values, in order. | ||
| 45 | + pub segments: Vec<u8>, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +impl PageHeader { | ||
| 49 | + /// Total body length: the sum of the lacing values. | ||
| 50 | + pub fn body_len(&self) -> usize { | ||
| 51 | + self.segments.iter().map(|&s| usize::from(s)).sum() | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + /// Decode the fixed part of a header. `buf` must hold at least | ||
| 55 | + /// [`HEADER_LEN`] bytes; the segment table is read by the caller, which | ||
| 56 | + /// knows how much more input it can supply. | ||
| 57 | + /// | ||
| 58 | + /// Returns the header with an empty segment table plus the segment count. | ||
| 59 | + pub fn parse_fixed(buf: &[u8]) -> Result<(PageHeader, usize)> { | ||
| 60 | + if buf.len() < HEADER_LEN { | ||
| 61 | + return Err(Error::NeedMore); | ||
| 62 | + } | ||
| 63 | + if buf[..4] != CAPTURE { | ||
| 64 | + return Err(Error::corrupt("Ogg page: no OggS capture pattern")); | ||
| 65 | + } | ||
| 66 | + if buf[4] != 0 { | ||
| 67 | + return Err(Error::unsupported( | ||
| 68 | + format!("Ogg stream structure version {}", buf[4]), | ||
| 69 | + "only version 0 is defined", | ||
| 70 | + )); | ||
| 71 | + } | ||
| 72 | + let flags = buf[5]; | ||
| 73 | + let header = PageHeader { | ||
| 74 | + continued: flags & FLAG_CONTINUED != 0, | ||
| 75 | + bos: flags & FLAG_BOS != 0, | ||
| 76 | + eos: flags & FLAG_EOS != 0, | ||
| 77 | + granule: i64::from_le_bytes(buf[6..14].try_into().unwrap()), | ||
| 78 | + serial: u32::from_le_bytes(buf[14..18].try_into().unwrap()), | ||
| 79 | + sequence: u32::from_le_bytes(buf[18..22].try_into().unwrap()), | ||
| 80 | + segments: Vec::new(), | ||
| 81 | + }; | ||
| 82 | + Ok((header, usize::from(buf[26]))) | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + /// The checksum stored in a fixed header. | ||
| 86 | + pub fn stored_crc(buf: &[u8]) -> u32 { | ||
| 87 | + u32::from_le_bytes(buf[22..26].try_into().unwrap()) | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + /// Serialize header and segment table, checksum included, and append the | ||
| 91 | + /// body — the exact bytes of one page. | ||
| 92 | + pub fn write_page(&self, body: &[u8], out: &mut Vec<u8>) { | ||
| 93 | + debug_assert_eq!(self.body_len(), body.len()); | ||
| 94 | + debug_assert!(!self.segments.is_empty() && self.segments.len() <= MAX_SEGMENTS); | ||
| 95 | + let start = out.len(); | ||
| 96 | + out.extend_from_slice(&CAPTURE); | ||
| 97 | + out.push(0); | ||
| 98 | + let mut flags = 0u8; | ||
| 99 | + if self.continued { | ||
| 100 | + flags |= FLAG_CONTINUED; | ||
| 101 | + } | ||
| 102 | + if self.bos { | ||
| 103 | + flags |= FLAG_BOS; | ||
| 104 | + } | ||
| 105 | + if self.eos { | ||
| 106 | + flags |= FLAG_EOS; | ||
| 107 | + } | ||
| 108 | + out.push(flags); | ||
| 109 | + out.extend_from_slice(&self.granule.to_le_bytes()); | ||
| 110 | + out.extend_from_slice(&self.serial.to_le_bytes()); | ||
| 111 | + out.extend_from_slice(&self.sequence.to_le_bytes()); | ||
| 112 | + out.extend_from_slice(&[0; 4]); // checksum, filled in below | ||
| 113 | + out.push(self.segments.len() as u8); | ||
| 114 | + out.extend_from_slice(&self.segments); | ||
| 115 | + out.extend_from_slice(body); | ||
| 116 | + // The checksum covers the whole page with its own field read as zero. | ||
| 117 | + let sum = crc::crc32(&[&out[start..]]); | ||
| 118 | + out[start + 22..start + 26].copy_from_slice(&sum.to_le_bytes()); | ||
| 119 | + } | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// The lacing values a packet of `len` bytes becomes: `len / 255` values of 255 | ||
| 123 | +/// then the remainder — including the explicit zero that terminates a packet | ||
| 124 | +/// whose length is a multiple of 255. | ||
| 125 | +pub fn lacing(len: usize) -> impl Iterator<Item = u8> { | ||
| 126 | + let full = len / 255; | ||
| 127 | + (0..=full).map(move |i| match i < full { | ||
| 128 | + true => 255, | ||
| 129 | + false => (len % 255) as u8, | ||
| 130 | + }) | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +/// The three Xiph header packets, laced the way `CodecParameters::extradata` | ||
| 134 | +/// carries them: two length prefixes in the 255-plus-remainder form, then the | ||
| 135 | +/// packets back to back, all behind a leading count of `2`. | ||
| 136 | +/// | ||
| 137 | +/// This is the shape ffmpeg calls "Xiph extradata" and the one Vorbis, Theora | ||
| 138 | +/// and Speex setup data travels in outside of Ogg. [`None`] when a header is | ||
| 139 | +/// too long to describe (the format has no escape beyond a 255 run) or when the | ||
| 140 | +/// packet count is not the two-prefixed-plus-one this layout can express. | ||
| 141 | +pub fn xiph_lace(packets: &[&[u8]]) -> Option<Vec<u8>> { | ||
| 142 | + if packets.len() < 2 || packets.len() > 256 { | ||
| 143 | + return None; | ||
| 144 | + } | ||
| 145 | + let mut out = vec![(packets.len() - 1) as u8]; | ||
| 146 | + for packet in &packets[..packets.len() - 1] { | ||
| 147 | + out.extend(lacing(packet.len())); | ||
| 148 | + } | ||
| 149 | + for packet in packets { | ||
| 150 | + out.extend_from_slice(packet); | ||
| 151 | + } | ||
| 152 | + Some(out) | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +/// The inverse of [`xiph_lace`]: split laced extradata back into packets. | ||
| 156 | +pub fn xiph_unlace(data: &[u8]) -> Result<Vec<&[u8]>> { | ||
| 157 | + let short = || Error::corrupt("Xiph extradata: truncated lacing"); | ||
| 158 | + let count = usize::from(*data.first().ok_or_else(short)?) + 1; | ||
| 159 | + let mut at = 1; | ||
| 160 | + let mut lengths = Vec::with_capacity(count); | ||
| 161 | + for _ in 0..count - 1 { | ||
| 162 | + let mut len = 0usize; | ||
| 163 | + loop { | ||
| 164 | + let lace = usize::from(*data.get(at).ok_or_else(short)?); | ||
| 165 | + at += 1; | ||
| 166 | + len += lace; | ||
| 167 | + if lace < 255 { | ||
| 168 | + break; | ||
| 169 | + } | ||
| 170 | + } | ||
| 171 | + lengths.push(len); | ||
| 172 | + } | ||
| 173 | + let mut out = Vec::with_capacity(count); | ||
| 174 | + for len in lengths { | ||
| 175 | + let end = at.checked_add(len).ok_or_else(short)?; | ||
| 176 | + out.push(data.get(at..end).ok_or_else(short)?); | ||
| 177 | + at = end; | ||
| 178 | + } | ||
| 179 | + // The last packet runs to the end: its length is the one the layout does | ||
| 180 | + // not store. | ||
| 181 | + out.push(&data[at..]); | ||
| 182 | + Ok(out) | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +#[cfg(test)] | ||
| 186 | +mod tests { | ||
| 187 | + use super::*; | ||
| 188 | + | ||
| 189 | + #[test] | ||
| 190 | + fn lacing_terminates_multiples_of_255() { | ||
| 191 | + assert_eq!(lacing(0).collect::<Vec<_>>(), vec![0]); | ||
| 192 | + assert_eq!(lacing(1).collect::<Vec<_>>(), vec![1]); | ||
| 193 | + assert_eq!(lacing(254).collect::<Vec<_>>(), vec![254]); | ||
| 194 | + // The rule that matters: 255 is *not* one segment of 255, it is a 255 | ||
| 195 | + // and a 0, or the packet never ends. | ||
| 196 | + assert_eq!(lacing(255).collect::<Vec<_>>(), vec![255, 0]); | ||
| 197 | + assert_eq!(lacing(256).collect::<Vec<_>>(), vec![255, 1]); | ||
| 198 | + assert_eq!(lacing(510).collect::<Vec<_>>(), vec![255, 255, 0]); | ||
| 199 | + for len in [0, 1, 255, 256, 700, 65_535] { | ||
| 200 | + let sum: usize = lacing(len).map(usize::from).sum(); | ||
| 201 | + assert_eq!(sum, len, "lacing must sum back to the packet length"); | ||
| 202 | + } | ||
| 203 | + } | ||
| 204 | + | ||
| 205 | + #[test] | ||
| 206 | + fn page_round_trips_through_its_own_checksum() { | ||
| 207 | + let body: Vec<u8> = (0..600u32).map(|i| (i % 251) as u8).collect(); | ||
| 208 | + let header = PageHeader { | ||
| 209 | + continued: true, | ||
| 210 | + bos: false, | ||
| 211 | + eos: true, | ||
| 212 | + granule: 123_456, | ||
| 213 | + serial: 0xdead_beef, | ||
| 214 | + sequence: 7, | ||
| 215 | + segments: lacing(body.len()).collect(), | ||
| 216 | + }; | ||
| 217 | + let mut bytes = Vec::new(); | ||
| 218 | + header.write_page(&body, &mut bytes); | ||
| 219 | + | ||
| 220 | + let (parsed, nsegs) = PageHeader::parse_fixed(&bytes).unwrap(); | ||
| 221 | + let segments = bytes[HEADER_LEN..HEADER_LEN + nsegs].to_vec(); | ||
| 222 | + let parsed = PageHeader { segments, ..parsed }; | ||
| 223 | + assert_eq!(parsed, header); | ||
| 224 | + assert_eq!(parsed.body_len(), body.len()); | ||
| 225 | + | ||
| 226 | + // The stored checksum verifies with its own field zeroed. | ||
| 227 | + let stored = PageHeader::stored_crc(&bytes); | ||
| 228 | + let mut zeroed = bytes.clone(); | ||
| 229 | + zeroed[22..26].fill(0); | ||
| 230 | + assert_eq!(crc::crc32(&[&zeroed]), stored); | ||
| 231 | + // ...and a single flipped body byte breaks it. | ||
| 232 | + let mut damaged = zeroed.clone(); | ||
| 233 | + let last = damaged.len() - 1; | ||
| 234 | + damaged[last] ^= 0x01; | ||
| 235 | + assert_ne!(crc::crc32(&[&damaged]), stored); | ||
| 236 | + | ||
| 237 | + assert!(PageHeader::parse_fixed(&bytes[..10]).is_err()); | ||
| 238 | + assert!(PageHeader::parse_fixed(b"NotAnOggPageHeaderAtAll....").is_err()); | ||
| 239 | + } | ||
| 240 | + | ||
| 241 | + #[test] | ||
| 242 | + fn xiph_lacing_round_trips() { | ||
| 243 | + let ident = [1u8; 30]; | ||
| 244 | + let comment = [2u8; 300]; | ||
| 245 | + let setup = [3u8; 4000]; | ||
| 246 | + let packets = [&ident[..], &comment[..], &setup[..]]; | ||
| 247 | + let laced = xiph_lace(&packets).unwrap(); | ||
| 248 | + assert_eq!(laced[0], 2, "count byte is packets - 1"); | ||
| 249 | + let back = xiph_unlace(&laced).unwrap(); | ||
| 250 | + assert_eq!(back.len(), 3); | ||
| 251 | + assert_eq!(back[0], &ident[..]); | ||
| 252 | + assert_eq!(back[1], &comment[..]); | ||
| 253 | + assert_eq!(back[2], &setup[..]); | ||
| 254 | + assert!(xiph_lace(&[&ident[..]]).is_none()); | ||
| 255 | + assert!(xiph_unlace(&[]).is_err()); | ||
| 256 | + assert!(xiph_unlace(&[2, 255]).is_err()); | ||
| 257 | + } | ||
| 258 | +} | ||
crates/ec-ogg/tests/ogg.rsadded+594 -0
| @@ -0,0 +1,594 @@ | |||
| 1 | +//! The fixture matrix, the remux round trip and what damage costs. | ||
| 2 | +//! | ||
| 3 | +//! ffprobe is the oracle for structure (packet counts, duration, "does this | ||
| 4 | +//! file parse at all") and ffmpeg for content: a remuxed file has to decode to | ||
| 5 | +//! the same PCM, byte for byte, as the file its packets came from. Both are | ||
| 6 | +//! required — a remux that ffprobe likes but whose audio drifted is exactly the | ||
| 7 | +//! failure this crate exists to avoid. | ||
| 8 | +//! | ||
| 9 | +//! Run the tables: | ||
| 10 | +//! cargo test -p ec-ogg --test ogg -- --nocapture | ||
| 11 | + | ||
| 12 | +use std::io::Cursor; | ||
| 13 | +use std::path::{Path, PathBuf}; | ||
| 14 | +use std::process::Command; | ||
| 15 | + | ||
| 16 | +use ec_core::{ | ||
| 17 | + Buf, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet, PacketFlags, SeekMode, | ||
| 18 | + StreamInfo, TimeBase, Timestamp, | ||
| 19 | +}; | ||
| 20 | +use ec_ogg::{Mapping, OggDemuxer, OggMuxer, granule_of, granule_side_data}; | ||
| 21 | + | ||
| 22 | +fn fixtures() -> PathBuf { | ||
| 23 | + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// Working directory keyed by test name: these tests are threads of one | ||
| 27 | +/// process, so a shared temp directory would have them deleting each other's | ||
| 28 | +/// files. | ||
| 29 | +fn workdir(test: &str) -> PathBuf { | ||
| 30 | + let dir = std::env::temp_dir().join(format!("ec-ogg-{}-{test}", std::process::id())); | ||
| 31 | + std::fs::create_dir_all(&dir).expect("create work dir"); | ||
| 32 | + dir | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +/// Every Ogg fixture on disk, sorted so the table reads the same every run. | ||
| 36 | +fn ogg_fixtures() -> Vec<PathBuf> { | ||
| 37 | + let Ok(entries) = std::fs::read_dir(fixtures()) else { | ||
| 38 | + return Vec::new(); | ||
| 39 | + }; | ||
| 40 | + let mut out: Vec<PathBuf> = entries | ||
| 41 | + .flatten() | ||
| 42 | + .map(|e| e.path()) | ||
| 43 | + .filter(|p| { | ||
| 44 | + matches!( | ||
| 45 | + p.extension().and_then(|s| s.to_str()), | ||
| 46 | + Some("ogg") | Some("opus") | ||
| 47 | + ) | ||
| 48 | + }) | ||
| 49 | + .collect(); | ||
| 50 | + out.sort(); | ||
| 51 | + out | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// Audio packets ffprobe counts in a file — header packets excluded, which is | ||
| 55 | +/// also what this demuxer hands out. | ||
| 56 | +fn ffprobe_packets(path: &Path) -> u64 { | ||
| 57 | + let out = Command::new("ffprobe") | ||
| 58 | + .args([ | ||
| 59 | + "-v", | ||
| 60 | + "error", | ||
| 61 | + "-select_streams", | ||
| 62 | + "a:0", | ||
| 63 | + "-count_packets", | ||
| 64 | + "-show_entries", | ||
| 65 | + "stream=nb_read_packets", | ||
| 66 | + "-of", | ||
| 67 | + "csv=p=0", | ||
| 68 | + ]) | ||
| 69 | + .arg(path) | ||
| 70 | + .output() | ||
| 71 | + .expect("ffprobe must be installed: it is the oracle for this crate"); | ||
| 72 | + String::from_utf8_lossy(&out.stdout) | ||
| 73 | + .trim() | ||
| 74 | + .parse() | ||
| 75 | + .unwrap_or_else(|e| panic!("ffprobe packet count for {}: {e}", path.display())) | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// ffprobe's own duration for the file, in seconds. | ||
| 79 | +fn ffprobe_duration(path: &Path) -> f64 { | ||
| 80 | + let out = Command::new("ffprobe") | ||
| 81 | + .args([ | ||
| 82 | + "-v", | ||
| 83 | + "error", | ||
| 84 | + "-show_entries", | ||
| 85 | + "format=duration", | ||
| 86 | + "-of", | ||
| 87 | + "csv=p=0", | ||
| 88 | + ]) | ||
| 89 | + .arg(path) | ||
| 90 | + .output() | ||
| 91 | + .expect("ffprobe"); | ||
| 92 | + String::from_utf8_lossy(&out.stdout).trim().parse().unwrap() | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// Decode a file to raw 32-bit float samples with ffmpeg. Errors are fatal: an | ||
| 96 | +/// unreadable file is the failure being tested for. | ||
| 97 | +fn decode_pcm(path: &Path) -> Vec<u8> { | ||
| 98 | + let out = Command::new("ffmpeg") | ||
| 99 | + .args(["-v", "error", "-i"]) | ||
| 100 | + .arg(path) | ||
| 101 | + .args(["-f", "f32le", "-"]) | ||
| 102 | + .output() | ||
| 103 | + .expect("ffmpeg"); | ||
| 104 | + assert!( | ||
| 105 | + out.status.success(), | ||
| 106 | + "ffmpeg failed to decode {}: {}", | ||
| 107 | + path.display(), | ||
| 108 | + String::from_utf8_lossy(&out.stderr) | ||
| 109 | + ); | ||
| 110 | + out.stdout | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/// ffprobe with errors escalated: the structural verdict on a file we wrote. | ||
| 114 | +fn ffprobe_clean(path: &Path) -> String { | ||
| 115 | + let out = Command::new("ffprobe") | ||
| 116 | + .args([ | ||
| 117 | + "-v", | ||
| 118 | + "error", | ||
| 119 | + "-show_entries", | ||
| 120 | + "stream=codec_name,sample_rate,channels", | ||
| 121 | + "-of", | ||
| 122 | + "csv=p=0", | ||
| 123 | + ]) | ||
| 124 | + .arg(path) | ||
| 125 | + .output() | ||
| 126 | + .expect("ffprobe"); | ||
| 127 | + let stderr = String::from_utf8_lossy(&out.stderr); | ||
| 128 | + assert!( | ||
| 129 | + stderr.trim().is_empty(), | ||
| 130 | + "ffprobe complained about {}: {stderr}", | ||
| 131 | + path.display() | ||
| 132 | + ); | ||
| 133 | + String::from_utf8_lossy(&out.stdout).trim().to_string() | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// Read every packet of a file through our demuxer. | ||
| 137 | +fn demux_all(path: &Path) -> (Vec<StreamInfo>, Vec<Packet>, u64) { | ||
| 138 | + let file = std::fs::File::open(path).unwrap(); | ||
| 139 | + let mut demuxer = OggDemuxer::open(file).unwrap_or_else(|e| panic!("{}: {e}", path.display())); | ||
| 140 | + let streams = demuxer.streams().to_vec(); | ||
| 141 | + let mut packets = Vec::new(); | ||
| 142 | + loop { | ||
| 143 | + match demuxer.next_packet() { | ||
| 144 | + Ok(p) => packets.push(p), | ||
| 145 | + Err(e) if e.is_eof() => break, | ||
| 146 | + Err(e) => panic!("{}: {e}", path.display()), | ||
| 147 | + } | ||
| 148 | + } | ||
| 149 | + (streams, packets, demuxer.damaged_pages()) | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +#[test] | ||
| 153 | +fn demuxes_every_fixture_to_eof() { | ||
| 154 | + let files = ogg_fixtures(); | ||
| 155 | + if files.is_empty() { | ||
| 156 | + eprintln!("fixtures/audio absent (gitignored) — skipping"); | ||
| 157 | + return; | ||
| 158 | + } | ||
| 159 | + println!( | ||
| 160 | + "{:<28} {:>8} {:>8} {:>10} {:>10}", | ||
| 161 | + "file", "ours", "ffprobe", "dur", "ffprobe" | ||
| 162 | + ); | ||
| 163 | + for path in &files { | ||
| 164 | + let name = path.file_name().unwrap().to_string_lossy().to_string(); | ||
| 165 | + let (streams, packets, damaged) = demux_all(path); | ||
| 166 | + assert_eq!(damaged, 0, "{name}: an intact fixture has no damaged pages"); | ||
| 167 | + assert_eq!(streams.len(), 1, "{name}: one logical stream expected"); | ||
| 168 | + let info = &streams[0]; | ||
| 169 | + let expected_codec = match name.starts_with("opus") { | ||
| 170 | + true => CodecId::Opus, | ||
| 171 | + false => CodecId::Vorbis, | ||
| 172 | + }; | ||
| 173 | + assert_eq!(info.params.codec, expected_codec, "{name}"); | ||
| 174 | + assert!( | ||
| 175 | + info.params | ||
| 176 | + .extradata | ||
| 177 | + .as_ref() | ||
| 178 | + .is_some_and(|e| !e.is_empty()), | ||
| 179 | + "{name}: setup data must reach the decoder" | ||
| 180 | + ); | ||
| 181 | + | ||
| 182 | + // The generator names rate and layout in the file name. | ||
| 183 | + let MediaParameters::Audio(audio) = &info.params.media else { | ||
| 184 | + panic!("{name}: audio parameters expected"); | ||
| 185 | + }; | ||
| 186 | + let expect_rate: u32 = name | ||
| 187 | + .rsplit('-') | ||
| 188 | + .next() | ||
| 189 | + .unwrap() | ||
| 190 | + .split('.') | ||
| 191 | + .next() | ||
| 192 | + .unwrap() | ||
| 193 | + .parse() | ||
| 194 | + .unwrap(); | ||
| 195 | + let expect_channels = match true { | ||
| 196 | + _ if name.contains("mono") => 1, | ||
| 197 | + _ if name.contains("stereo") => 2, | ||
| 198 | + _ => 6, | ||
| 199 | + }; | ||
| 200 | + assert_eq!(audio.layout.channel_count(), expect_channels, "{name}"); | ||
| 201 | + match expected_codec { | ||
| 202 | + // Opus always decodes at 48 kHz whatever it was fed. | ||
| 203 | + CodecId::Opus => assert_eq!(audio.sample_rate, 48_000, "{name}"), | ||
| 204 | + _ => assert_eq!(audio.sample_rate, expect_rate, "{name}"), | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + let ours = packets.len() as u64; | ||
| 208 | + let theirs = ffprobe_packets(path); | ||
| 209 | + assert_eq!(ours, theirs, "{name}: packet count"); | ||
| 210 | + | ||
| 211 | + // Duration: ours is the playable length, so Opus differs from ffprobe's | ||
| 212 | + // by exactly the pre-skip it reports as part of the granule count. | ||
| 213 | + let secs = |ticks: i64| ticks as f64 * info.time_base.as_secs_f64(); | ||
| 214 | + let our_dur = secs(info.duration.unwrap()); | ||
| 215 | + let their_dur = ffprobe_duration(path); | ||
| 216 | + let pre_skip = secs(info.start_time.unwrap()); | ||
| 217 | + assert!( | ||
| 218 | + (our_dur + pre_skip - their_dur).abs() < 1e-6, | ||
| 219 | + "{name}: duration {our_dur} + pre-skip {pre_skip} vs ffprobe {their_dur}" | ||
| 220 | + ); | ||
| 221 | + println!("{name:<28} {ours:>8} {theirs:>8} {our_dur:>10.4} {their_dur:>10.4}"); | ||
| 222 | + | ||
| 223 | + // Timestamps are monotonic where the mapping states them, and Opus | ||
| 224 | + // states one for every packet. | ||
| 225 | + let stamped = packets.iter().filter(|p| p.pts.is_some()).count(); | ||
| 226 | + match expected_codec { | ||
| 227 | + CodecId::Opus => assert_eq!(stamped, packets.len(), "{name}: every Opus pts"), | ||
| 228 | + _ => assert!(stamped > 0, "{name}: at least the page-boundary timestamps"), | ||
| 229 | + } | ||
| 230 | + let mut last = i64::MIN; | ||
| 231 | + for p in packets.iter().filter_map(|p| p.pts) { | ||
| 232 | + assert!(p >= last, "{name}: timestamps must not go backwards"); | ||
| 233 | + last = p; | ||
| 234 | + } | ||
| 235 | + // The last packet ends where the file says the stream ends. | ||
| 236 | + assert_eq!( | ||
| 237 | + granule_of(packets.last().unwrap()), | ||
| 238 | + Some(info.duration.unwrap() + info.start_time.unwrap()), | ||
| 239 | + "{name}: the end-of-stream granule reaches the last packet" | ||
| 240 | + ); | ||
| 241 | + } | ||
| 242 | + assert!( | ||
| 243 | + files.len() >= 9, | ||
| 244 | + "expected the nine Ogg fixtures, saw {}", | ||
| 245 | + files.len() | ||
| 246 | + ); | ||
| 247 | +} | ||
| 248 | + | ||
| 249 | +/// Demux a fixture, write its packets back out, and require ffmpeg to decode | ||
| 250 | +/// the result to the same samples. | ||
| 251 | +fn remux_case(path: &Path, page_target: Option<usize>) { | ||
| 252 | + let name = path.file_name().unwrap().to_string_lossy().to_string(); | ||
| 253 | + let (streams, packets, _) = demux_all(path); | ||
| 254 | + let out_path = workdir("remux").join(format!("remux-{name}")); | ||
| 255 | + | ||
| 256 | + let file = std::fs::File::create(&out_path).unwrap(); | ||
| 257 | + let mut muxer = OggMuxer::new(std::io::BufWriter::new(file)); | ||
| 258 | + muxer.add_stream(streams[0].clone()).unwrap(); | ||
| 259 | + muxer.set_page_target_bytes(page_target); | ||
| 260 | + for packet in &packets { | ||
| 261 | + muxer.write_packet(packet).unwrap(); | ||
| 262 | + } | ||
| 263 | + muxer.finish().unwrap(); | ||
| 264 | + | ||
| 265 | + // Structure: ffprobe reads it without a word of complaint, sees the same | ||
| 266 | + // stream and counts the same packets. | ||
| 267 | + let described = ffprobe_clean(&out_path); | ||
| 268 | + assert!(!described.is_empty(), "{name}: ffprobe described nothing"); | ||
| 269 | + assert_eq!( | ||
| 270 | + ffprobe_packets(&out_path), | ||
| 271 | + packets.len() as u64, | ||
| 272 | + "{name}: remuxed packet count" | ||
| 273 | + ); | ||
| 274 | + assert!( | ||
| 275 | + (ffprobe_duration(&out_path) - ffprobe_duration(path)).abs() < 1e-6, | ||
| 276 | + "{name}: remuxed duration" | ||
| 277 | + ); | ||
| 278 | + | ||
| 279 | + // Content: same samples, byte for byte. | ||
| 280 | + let before = decode_pcm(path); | ||
| 281 | + let after = decode_pcm(&out_path); | ||
| 282 | + assert_eq!( | ||
| 283 | + after.len(), | ||
| 284 | + before.len(), | ||
| 285 | + "{name}: remux decoded to {} bytes, source to {}", | ||
| 286 | + after.len(), | ||
| 287 | + before.len() | ||
| 288 | + ); | ||
| 289 | + assert!( | ||
| 290 | + after == before, | ||
| 291 | + "{name}: remuxed audio differs from the source" | ||
| 292 | + ); | ||
| 293 | + | ||
| 294 | + // And our own demuxer reads back exactly the packets that went in. | ||
| 295 | + let (round, again, _) = demux_all(&out_path); | ||
| 296 | + assert_eq!( | ||
| 297 | + again.len(), | ||
| 298 | + packets.len(), | ||
| 299 | + "{name}: round-trip packet count" | ||
| 300 | + ); | ||
| 301 | + for (a, b) in again.iter().zip(&packets) { | ||
| 302 | + assert_eq!(a.data, b.data, "{name}: payload changed in the round trip"); | ||
| 303 | + } | ||
| 304 | + assert_eq!(round[0].params.codec, streams[0].params.codec); | ||
| 305 | + println!( | ||
| 306 | + "remux {name:<24} {described} ok ({} packets)", | ||
| 307 | + packets.len() | ||
| 308 | + ); | ||
| 309 | +} | ||
| 310 | + | ||
| 311 | +#[test] | ||
| 312 | +fn remuxes_every_fixture_bit_identically() { | ||
| 313 | + let files = ogg_fixtures(); | ||
| 314 | + if files.is_empty() { | ||
| 315 | + eprintln!("fixtures/audio absent (gitignored) — skipping"); | ||
| 316 | + return; | ||
| 317 | + } | ||
| 318 | + for path in &files { | ||
| 319 | + remux_case(path, None); | ||
| 320 | + } | ||
| 321 | +} | ||
| 322 | + | ||
| 323 | +/// The page-size knob must not change what comes out: one packet per page and | ||
| 324 | +/// one page for the lot both have to decode identically. | ||
| 325 | +#[test] | ||
| 326 | +fn page_size_does_not_change_the_audio() { | ||
| 327 | + let files = ogg_fixtures(); | ||
| 328 | + let Some(path) = files | ||
| 329 | + .iter() | ||
| 330 | + .find(|p| p.to_string_lossy().contains("vorbis-ogg-stereo-48000")) | ||
| 331 | + else { | ||
| 332 | + eprintln!("fixtures absent — skipping"); | ||
| 333 | + return; | ||
| 334 | + }; | ||
| 335 | + remux_case(path, Some(1)); | ||
| 336 | + remux_case(path, Some(1 << 20)); | ||
| 337 | +} | ||
| 338 | + | ||
| 339 | +#[test] | ||
| 340 | +fn damage_costs_one_page_and_no_more() { | ||
| 341 | + let files = ogg_fixtures(); | ||
| 342 | + let Some(path) = files | ||
| 343 | + .iter() | ||
| 344 | + .find(|p| p.to_string_lossy().contains("vorbis-ogg-stereo-44100")) | ||
| 345 | + else { | ||
| 346 | + eprintln!("fixtures absent — skipping"); | ||
| 347 | + return; | ||
| 348 | + }; | ||
| 349 | + let (_, clean, _) = demux_all(path); | ||
| 350 | + let bytes = std::fs::read(path).unwrap(); | ||
| 351 | + | ||
| 352 | + // Flip a bit in the middle of the file: that lands inside a page body, so | ||
| 353 | + // the page's checksum fails and its packets are lost — and nothing else is. | ||
| 354 | + let mut damaged = bytes.clone(); | ||
| 355 | + let at = damaged.len() / 2; | ||
| 356 | + damaged[at] ^= 0x40; | ||
| 357 | + let out = workdir("damage").join("flipped.ogg"); | ||
| 358 | + std::fs::write(&out, &damaged).unwrap(); | ||
| 359 | + | ||
| 360 | + let (streams, packets, dropped) = demux_all(&out); | ||
| 361 | + assert_eq!(streams.len(), 1, "the stream is still described"); | ||
| 362 | + assert_eq!(dropped, 1, "exactly one page fails its checksum"); | ||
| 363 | + assert!( | ||
| 364 | + packets.len() < clean.len(), | ||
| 365 | + "the damaged page's packets are gone: {} vs {}", | ||
| 366 | + packets.len(), | ||
| 367 | + clean.len() | ||
| 368 | + ); | ||
| 369 | + // Recovery, not collapse: what is lost is the damaged page and nothing | ||
| 370 | + // else, so every packet after it is still there, byte for byte, in order. | ||
| 371 | + // What survives is a prefix of the clean read plus a suffix of it: the | ||
| 372 | + // packets of the damaged page, and only those, are missing from the middle. | ||
| 373 | + let kept = packets.len(); | ||
| 374 | + let head = packets | ||
| 375 | + .iter() | ||
| 376 | + .zip(&clean) | ||
| 377 | + .take_while(|(a, b)| a.data == b.data) | ||
| 378 | + .count(); | ||
| 379 | + let tail = packets | ||
| 380 | + .iter() | ||
| 381 | + .rev() | ||
| 382 | + .zip(clean.iter().rev()) | ||
| 383 | + .take_while(|(a, b)| a.data == b.data) | ||
| 384 | + .count(); | ||
| 385 | + assert!(head > 0, "nothing before the damage was read"); | ||
| 386 | + assert!(tail > 0, "nothing after the damage was recovered"); | ||
| 387 | + assert_eq!( | ||
| 388 | + head + tail, | ||
| 389 | + kept, | ||
| 390 | + "recovery is a prefix of {head} and a suffix of {tail} out of {kept} packets" | ||
| 391 | + ); | ||
| 392 | + println!( | ||
| 393 | + "damage: {kept} of {} packets survived — {head} before the bad page, {tail} after it", | ||
| 394 | + clean.len() | ||
| 395 | + ); | ||
| 396 | +} | ||
| 397 | + | ||
| 398 | +#[test] | ||
| 399 | +fn seeks_land_at_or_before_the_target() { | ||
| 400 | + let files = ogg_fixtures(); | ||
| 401 | + if files.is_empty() { | ||
| 402 | + eprintln!("fixtures absent — skipping"); | ||
| 403 | + return; | ||
| 404 | + } | ||
| 405 | + for path in files.iter().filter(|p| { | ||
| 406 | + let n = p.to_string_lossy().to_string(); | ||
| 407 | + n.contains("stereo-48000") || n.contains("5.1-44100") | ||
| 408 | + }) { | ||
| 409 | + let name = path.file_name().unwrap().to_string_lossy().to_string(); | ||
| 410 | + let file = std::fs::File::open(path).unwrap(); | ||
| 411 | + let mut demuxer = OggDemuxer::open(file).unwrap(); | ||
| 412 | + let info = demuxer.streams()[0].clone(); | ||
| 413 | + let duration = info.duration.unwrap(); | ||
| 414 | + for fraction in [0, 1, 2, 3, 4] { | ||
| 415 | + let target = duration * fraction / 4; | ||
| 416 | + let to = Timestamp::new(target + info.start_time.unwrap(), info.time_base); | ||
| 417 | + demuxer.seek(0, to, SeekMode::SyncBefore).unwrap(); | ||
| 418 | + let packet = match demuxer.next_packet() { | ||
| 419 | + Ok(p) => p, | ||
| 420 | + // Seeking to the very end can land on the end-of-stream page. | ||
| 421 | + Err(e) if e.is_eof() => continue, | ||
| 422 | + Err(e) => panic!("{name}: {e}"), | ||
| 423 | + }; | ||
| 424 | + if let Some(pts) = packet.pts { | ||
| 425 | + assert!( | ||
| 426 | + pts <= target + info.start_time.unwrap(), | ||
| 427 | + "{name}: seek to {target} landed at {pts}" | ||
| 428 | + ); | ||
| 429 | + } | ||
| 430 | + // Whatever it landed on, the rest of the file still reads. | ||
| 431 | + let mut rest = 1; | ||
| 432 | + while let Ok(_p) = demuxer.next_packet() { | ||
| 433 | + rest += 1; | ||
| 434 | + } | ||
| 435 | + assert!(rest > 0, "{name}: nothing readable after the seek"); | ||
| 436 | + } | ||
| 437 | + // Seeking forwards then back to zero returns the whole stream. | ||
| 438 | + demuxer | ||
| 439 | + .seek(0, Timestamp::new(0, info.time_base), SeekMode::SyncBefore) | ||
| 440 | + .unwrap(); | ||
| 441 | + let mut count = 0; | ||
| 442 | + while demuxer.next_packet().is_ok() { | ||
| 443 | + count += 1; | ||
| 444 | + } | ||
| 445 | + let (_, all, _) = demux_all(path); | ||
| 446 | + assert!( | ||
| 447 | + count >= all.len() - 2, | ||
| 448 | + "{name}: after seeking home {count} of {} packets remained", | ||
| 449 | + all.len() | ||
| 450 | + ); | ||
| 451 | + } | ||
| 452 | +} | ||
| 453 | + | ||
| 454 | +/// Payload sizes Ogg's own lacing has to work for, none of which the fixtures | ||
| 455 | +/// contain: a packet that is exactly a multiple of 255, one that fills more | ||
| 456 | +/// than one page's segment table, and an empty one. | ||
| 457 | +#[test] | ||
| 458 | +fn round_trips_awkward_packet_sizes_through_memory() { | ||
| 459 | + let sizes = [ | ||
| 460 | + 1usize, 254, 255, 256, 509, 510, 511, 64_000, 65_025, 300_000, | ||
| 461 | + ]; | ||
| 462 | + let rate = 48_000; | ||
| 463 | + let time_base = TimeBase::from_rate(rate); | ||
| 464 | + | ||
| 465 | + let mut params = CodecParameters::new(CodecId::Vorbis); | ||
| 466 | + if let MediaParameters::Audio(audio) = &mut params.media { | ||
| 467 | + audio.sample_rate = rate; | ||
| 468 | + } | ||
| 469 | + // A Vorbis triplet is what the mapping requires; the contents only have to | ||
| 470 | + // identify, since nothing decodes them here. | ||
| 471 | + let mut ident = vec![1u8]; | ||
| 472 | + ident.extend_from_slice(b"vorbis"); | ||
| 473 | + ident.extend_from_slice(&0u32.to_le_bytes()); | ||
| 474 | + ident.push(2); | ||
| 475 | + ident.extend_from_slice(&rate.to_le_bytes()); | ||
| 476 | + ident.resize(30, 0); | ||
| 477 | + let comment = vec![3u8; 400]; | ||
| 478 | + let setup = vec![5u8; 9000]; | ||
| 479 | + params.extradata = Some(Buf::from_vec( | ||
| 480 | + ec_ogg::xiph_lace(&[&ident, &comment, &setup]).unwrap(), | ||
| 481 | + )); | ||
| 482 | + let info = StreamInfo::new(0, time_base, params); | ||
| 483 | + | ||
| 484 | + let mut muxer = OggMuxer::new(Cursor::new(Vec::new())); | ||
| 485 | + muxer.add_stream(info).unwrap(); | ||
| 486 | + // One packet per page, so every packet carries the page granule back out. | ||
| 487 | + muxer.set_page_target_bytes(Some(1)); | ||
| 488 | + let mut granule = 0i64; | ||
| 489 | + let mut written = Vec::new(); | ||
| 490 | + for (i, size) in sizes.iter().enumerate() { | ||
| 491 | + let data: Vec<u8> = (0..*size) | ||
| 492 | + .map(|n| (n as u32 % 251) as u8 ^ i as u8) | ||
| 493 | + .collect(); | ||
| 494 | + granule += 1024; | ||
| 495 | + let mut packet = Packet::new(0, time_base, data.clone()); | ||
| 496 | + packet.side_data.push(granule_side_data(granule)); | ||
| 497 | + muxer.write_packet(&packet).unwrap(); | ||
| 498 | + written.push(data); | ||
| 499 | + } | ||
| 500 | + muxer.finish().unwrap(); | ||
| 501 | + let bytes = muxer.into_inner().into_inner(); | ||
| 502 | + | ||
| 503 | + let mut demuxer = OggDemuxer::open(Cursor::new(bytes)).unwrap(); | ||
| 504 | + assert_eq!(demuxer.streams()[0].params.codec, CodecId::Vorbis); | ||
| 505 | + assert_eq!( | ||
| 506 | + demuxer.mapping(0), | ||
| 507 | + Some(Mapping::Vorbis { rate, channels: 2 }) | ||
| 508 | + ); | ||
| 509 | + // Setup data survived the trip laced the way it arrived. | ||
| 510 | + let extradata = demuxer.streams()[0].params.extradata.clone().unwrap(); | ||
| 511 | + let unlaced = ec_ogg::xiph_unlace(&extradata).unwrap(); | ||
| 512 | + assert_eq!(unlaced.len(), 3); | ||
| 513 | + assert_eq!(unlaced[2], &setup[..]); | ||
| 514 | + | ||
| 515 | + let mut read = Vec::new(); | ||
| 516 | + while let Ok(packet) = demuxer.next_packet() { | ||
| 517 | + read.push(packet); | ||
| 518 | + } | ||
| 519 | + assert_eq!(read.len(), written.len(), "one packet in, one packet out"); | ||
| 520 | + for (i, (got, want)) in read.iter().zip(&written).enumerate() { | ||
| 521 | + assert_eq!( | ||
| 522 | + &got.data[..], | ||
| 523 | + &want[..], | ||
| 524 | + "packet {i} of {} bytes", | ||
| 525 | + want.len() | ||
| 526 | + ); | ||
| 527 | + assert_eq!( | ||
| 528 | + granule_of(got), | ||
| 529 | + Some((i as i64 + 1) * 1024), | ||
| 530 | + "packet {i}: granule position" | ||
| 531 | + ); | ||
| 532 | + } | ||
| 533 | +} | ||
| 534 | + | ||
| 535 | +/// Header packets written by the caller replace what extradata would have | ||
| 536 | +/// produced — the path a remux takes to carry the original `OpusTags` through. | ||
| 537 | +#[test] | ||
| 538 | +fn caller_supplied_headers_win_over_extradata() { | ||
| 539 | + let time_base = TimeBase::from_rate(48_000); | ||
| 540 | + let mut head = Vec::from(*b"OpusHead"); | ||
| 541 | + head.extend_from_slice(&[1, 2]); | ||
| 542 | + head.extend_from_slice(&312u16.to_le_bytes()); | ||
| 543 | + head.extend_from_slice(&48_000u32.to_le_bytes()); | ||
| 544 | + head.resize(19, 0); | ||
| 545 | + | ||
| 546 | + let mut params = CodecParameters::new(CodecId::Opus); | ||
| 547 | + params.extradata = Some(Buf::from_vec(head.clone())); | ||
| 548 | + let info = StreamInfo::new(0, time_base, params); | ||
| 549 | + | ||
| 550 | + let mut tags = Vec::from(*b"OpusTags"); | ||
| 551 | + tags.extend_from_slice(&4u32.to_le_bytes()); | ||
| 552 | + tags.extend_from_slice(b"mine"); | ||
| 553 | + tags.extend_from_slice(&0u32.to_le_bytes()); | ||
| 554 | + | ||
| 555 | + let mut muxer = OggMuxer::new(Cursor::new(Vec::new())); | ||
| 556 | + muxer.add_stream(info).unwrap(); | ||
| 557 | + for header in [&head, &tags] { | ||
| 558 | + let mut packet = Packet::new(0, time_base, header.clone()); | ||
| 559 | + packet.flags = PacketFlags { | ||
| 560 | + header: true, | ||
| 561 | + ..PacketFlags::default() | ||
| 562 | + }; | ||
| 563 | + muxer.write_packet(&packet).unwrap(); | ||
| 564 | + } | ||
| 565 | + // One CELT 20 ms packet, so the stream has audio to end on. | ||
| 566 | + let mut audio = Packet::new(0, time_base, vec![(31 << 3) as u8, 0, 0, 0]); | ||
| 567 | + audio.side_data.push(granule_side_data(960)); | ||
| 568 | + muxer.write_packet(&audio).unwrap(); | ||
| 569 | + muxer.finish().unwrap(); | ||
| 570 | + | ||
| 571 | + let bytes = muxer.into_inner().into_inner(); | ||
| 572 | + // The tags packet we supplied is in the file; the synthesized one is not. | ||
| 573 | + let haystack = String::from_utf8_lossy(&bytes).to_string(); | ||
| 574 | + assert!( | ||
| 575 | + haystack.contains("mine"), | ||
| 576 | + "caller's OpusTags must be written" | ||
| 577 | + ); | ||
| 578 | + assert!( | ||
| 579 | + !haystack.contains("ec-ogg"), | ||
| 580 | + "synthesized tags must not appear" | ||
| 581 | + ); | ||
| 582 | + | ||
| 583 | + let mut demuxer = OggDemuxer::open(Cursor::new(bytes)).unwrap(); | ||
| 584 | + assert_eq!(demuxer.streams()[0].params.codec, CodecId::Opus); | ||
| 585 | + assert_eq!( | ||
| 586 | + demuxer.streams()[0].start_time, | ||
| 587 | + Some(312), | ||
| 588 | + "presentation starts at the pre-skip" | ||
| 589 | + ); | ||
| 590 | + let packet = demuxer.next_packet().unwrap(); | ||
| 591 | + assert_eq!(packet.duration, Some(960), "TOC states the packet duration"); | ||
| 592 | + assert_eq!(packet.pts, Some(0)); | ||
| 593 | + assert!(demuxer.next_packet().unwrap_err().is_eof()); | ||
| 594 | +} | ||
shims/oxideav-ogg/Cargo.tomladded+13 -0
| @@ -0,0 +1,13 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "oxideav-ogg" | ||
| 3 | +description = "Compatibility shim: the oxideav-ogg mux surface edith consumes, over ec-ogg." | ||
| 4 | +version = "0.1.8" | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | +publish = false | ||
| 9 | + | ||
| 10 | +[dependencies] | ||
| 11 | +ec-core = { path = "../../crates/ec-core", version = "0.1.0" } | ||
| 12 | +ec-ogg = { path = "../../crates/ec-ogg", version = "0.1.0" } | ||
| 13 | +oxideav-core = { path = "../oxideav-core", version = "0.1.34" } | ||
shims/oxideav-ogg/src/lib.rsadded+28 -0
| @@ -0,0 +1,28 @@ | |||
| 1 | +//! `oxideav-ogg` as edith consumes it, over [`ec_ogg`]. | ||
| 2 | +//! | ||
| 3 | +//! A shim, not a port: it carries the incumbent's package name and version so | ||
| 4 | +//! the swap is a `[patch.crates-io]` line, and it exposes exactly the items the | ||
| 5 | +//! replica names — `mux::xiph_lace`, `mux::open_concrete`, and the concrete | ||
| 6 | +//! muxer's `set_page_target_bytes` beside the `oxideav_core::Muxer` methods | ||
| 7 | +//! (`export.rs:2942,2957,2961`). | ||
| 8 | +//! | ||
| 9 | +//! One semantic difference is owned here rather than at the call site. The | ||
| 10 | +//! replica states a packet's *granule position* — where it ends — in the | ||
| 11 | +//! packet's `pts`, because that is what the incumbent's muxer wrote onto the | ||
| 12 | +//! page; `ec_ogg` keeps `pts` meaning presentation start and carries granule | ||
| 13 | +//! positions in side data ([`ec_ogg::granule_side_data`]). The translation is | ||
| 14 | +//! [`mux::OggMuxer::write_packet`], once, for every caller. | ||
| 15 | + | ||
| 16 | +#![forbid(unsafe_code)] | ||
| 17 | + | ||
| 18 | +use std::io::{Seek, Write}; | ||
| 19 | + | ||
| 20 | +/// A sink an Ogg file can be written to. The incumbent puts this trait in | ||
| 21 | +/// `oxideav-core`; nothing in the replica names it directly (it only ever | ||
| 22 | +/// passes a `Box::new(File::create(..)?)`), so it lives here until the atomic | ||
| 23 | +/// oxideav swap decides where the family keeps it. | ||
| 24 | +pub trait WriteSeek: Write + Seek + Send {} | ||
| 25 | + | ||
| 26 | +impl<T: Write + Seek + Send> WriteSeek for T {} | ||
| 27 | + | ||
| 28 | +pub mod mux; | ||
shims/oxideav-ogg/src/mux.rsadded+90 -0
| @@ -0,0 +1,90 @@ | |||
| 1 | +//! The muxing half — the only half the replica calls. | ||
| 2 | + | ||
| 3 | +use ec_core::Muxer as _; | ||
| 4 | +use ec_ogg::granule_side_data; | ||
| 5 | +use oxideav_core::{Error, Muxer, Packet, Result, StreamInfo}; | ||
| 6 | + | ||
| 7 | +use crate::WriteSeek; | ||
| 8 | + | ||
| 9 | +/// Lace header packets into the `extradata` form Vorbis setup data travels in: | ||
| 10 | +/// [`None`] when they cannot be described that way. | ||
| 11 | +pub fn xiph_lace(packets: &[&[u8]]) -> Option<Vec<u8>> { | ||
| 12 | + ec_ogg::xiph_lace(packets) | ||
| 13 | +} | ||
| 14 | + | ||
| 15 | +/// Open a writer over `output` with `streams` already declared. | ||
| 16 | +pub fn open_concrete(output: Box<dyn WriteSeek>, streams: &[StreamInfo]) -> Result<OggMuxer> { | ||
| 17 | + let mut inner = ec_ogg::OggMuxer::new(output); | ||
| 18 | + for stream in streams { | ||
| 19 | + inner.add_stream(to_ec_stream(stream)?)?; | ||
| 20 | + } | ||
| 21 | + Ok(OggMuxer { inner }) | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +/// The concrete muxer, so callers reach [`OggMuxer::set_page_target_bytes`] | ||
| 25 | +/// without a downcast. | ||
| 26 | +pub struct OggMuxer { | ||
| 27 | + inner: ec_ogg::OggMuxer<Box<dyn WriteSeek>>, | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +impl OggMuxer { | ||
| 31 | + /// Aim for `bytes` of body per page; [`None`] restores the default. | ||
| 32 | + pub fn set_page_target_bytes(&mut self, bytes: Option<usize>) { | ||
| 33 | + self.inner.set_page_target_bytes(bytes); | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +impl Muxer for OggMuxer { | ||
| 38 | + fn format_name(&self) -> &str { | ||
| 39 | + "ogg" | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + fn write_header(&mut self) -> Result<()> { | ||
| 43 | + Ok(self.inner.write_headers()?) | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + /// The caller's `pts` *is* the granule position — where this packet ends — | ||
| 47 | + /// which is the convention the incumbent muxer wrote onto its pages. It is | ||
| 48 | + /// moved into the side data `ec_ogg` reads positions from, and the packet | ||
| 49 | + /// keeps no start timestamp, because Ogg does not carry one. | ||
| 50 | + fn write_packet(&mut self, packet: &Packet) -> Result<()> { | ||
| 51 | + let mut out = packet.clone(); | ||
| 52 | + if let Some(granule) = packet.pts { | ||
| 53 | + out.side_data.push(granule_side_data(granule)); | ||
| 54 | + } | ||
| 55 | + out.pts = None; | ||
| 56 | + out.dts = None; | ||
| 57 | + Ok(self.inner.write_packet(&out)?) | ||
| 58 | + } | ||
| 59 | + | ||
| 60 | + fn write_trailer(&mut self) -> Result<()> { | ||
| 61 | + Ok(self.inner.finish()?) | ||
| 62 | + } | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +/// The replica's stream description, in family terms. | ||
| 66 | +fn to_ec_stream(stream: &StreamInfo) -> Result<ec_core::StreamInfo> { | ||
| 67 | + let params = &stream.params; | ||
| 68 | + let codec = params.codec_id.to_ec().ok_or_else(|| { | ||
| 69 | + Error::Unsupported(format!( | ||
| 70 | + "Ogg mux: codec {} is not one this family carries", | ||
| 71 | + params.codec_id | ||
| 72 | + )) | ||
| 73 | + })?; | ||
| 74 | + let mut out = ec_core::CodecParameters::new(codec); | ||
| 75 | + if let ec_core::MediaParameters::Audio(audio) = &mut out.media { | ||
| 76 | + if let Some(rate) = params.sample_rate { | ||
| 77 | + audio.sample_rate = rate; | ||
| 78 | + } | ||
| 79 | + if let Some(channels) = params.channels { | ||
| 80 | + audio.layout = ec_core::ChannelLayout::from_count(usize::from(channels).max(1)); | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | + if !params.extradata.is_empty() { | ||
| 84 | + out.extradata = Some(ec_core::Buf::copy_from_slice(¶ms.extradata)); | ||
| 85 | + } | ||
| 86 | + let mut info = ec_core::StreamInfo::new(stream.index, stream.time_base, out); | ||
| 87 | + info.duration = stream.duration; | ||
| 88 | + info.start_time = stream.start_time; | ||
| 89 | + Ok(info) | ||
| 90 | +} | ||
shims/oxideav-ogg/tests/edith_surface.rsadded+123 -0
| @@ -0,0 +1,123 @@ | |||
| 1 | +//! The replica's own call sequence, run against the shim. | ||
| 2 | +//! | ||
| 3 | +//! `export.rs:2942-2982` laces three Vorbis headers, describes one stream, | ||
| 4 | +//! opens a concrete muxer, sets the page target, then writes header, packets | ||
| 5 | +//! and trailer — with each packet's *granule* in its `pts`. This drives exactly | ||
| 6 | +//! that, with real Vorbis packets taken out of a fixture, and asks ffmpeg | ||
| 7 | +//! whether the result is the same audio. | ||
| 8 | + | ||
| 9 | +use std::path::{Path, PathBuf}; | ||
| 10 | +use std::process::Command; | ||
| 11 | + | ||
| 12 | +use ec_core::Demuxer as _; | ||
| 13 | +use oxideav_core::{CodecId, CodecParameters, Muxer as _, Packet, StreamInfo, TimeBase}; | ||
| 14 | + | ||
| 15 | +fn fixture() -> PathBuf { | ||
| 16 | + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio/vorbis-ogg-stereo-44100.ogg") | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +fn decode_pcm(path: &Path) -> Vec<u8> { | ||
| 20 | + let out = Command::new("ffmpeg") | ||
| 21 | + .args(["-v", "error", "-i"]) | ||
| 22 | + .arg(path) | ||
| 23 | + .args(["-f", "f32le", "-"]) | ||
| 24 | + .output() | ||
| 25 | + .expect("ffmpeg"); | ||
| 26 | + assert!( | ||
| 27 | + out.status.success(), | ||
| 28 | + "ffmpeg failed on {}: {}", | ||
| 29 | + path.display(), | ||
| 30 | + String::from_utf8_lossy(&out.stderr) | ||
| 31 | + ); | ||
| 32 | + out.stdout | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +#[test] | ||
| 36 | +fn writes_a_vorbis_file_the_way_the_replica_does() { | ||
| 37 | + let source = fixture(); | ||
| 38 | + if !source.exists() { | ||
| 39 | + eprintln!("fixtures/audio absent (gitignored) — skipping"); | ||
| 40 | + return; | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + // Packets and setup data out of a real file, standing in for the encoder | ||
| 44 | + // the replica feeds this from. | ||
| 45 | + let mut demuxer = ec_ogg::OggDemuxer::open(std::fs::File::open(&source).unwrap()).unwrap(); | ||
| 46 | + let info = demuxer.streams()[0].clone(); | ||
| 47 | + let extradata = info.params.extradata.clone().unwrap(); | ||
| 48 | + let headers = ec_ogg::xiph_unlace(&extradata).unwrap(); | ||
| 49 | + let mut packets = Vec::new(); | ||
| 50 | + while let Ok(packet) = demuxer.next_packet() { | ||
| 51 | + packets.push(packet); | ||
| 52 | + } | ||
| 53 | + assert_eq!(headers.len(), 3, "a Vorbis stream is three headers"); | ||
| 54 | + | ||
| 55 | + // From here on, the replica's code, line for line. | ||
| 56 | + let laced = super_xiph_lace(&headers).expect("the three headers would not lace"); | ||
| 57 | + assert_eq!(&laced[..], &extradata[..], "lacing must round-trip"); | ||
| 58 | + | ||
| 59 | + let rate = 44_100u32; | ||
| 60 | + let time_base = TimeBase::new(1, i64::from(rate)); | ||
| 61 | + let mut params = CodecParameters::audio(CodecId::new("vorbis")); | ||
| 62 | + params.sample_rate = Some(rate); | ||
| 63 | + params.channels = Some(2); | ||
| 64 | + params.extradata = laced; | ||
| 65 | + let stream = StreamInfo { | ||
| 66 | + index: 0, | ||
| 67 | + time_base, | ||
| 68 | + duration: info.duration, | ||
| 69 | + start_time: Some(0), | ||
| 70 | + params, | ||
| 71 | + }; | ||
| 72 | + | ||
| 73 | + let out_path = | ||
| 74 | + std::env::temp_dir().join(format!("oxideav-ogg-shim-{}.ogg", std::process::id())); | ||
| 75 | + let file = std::fs::File::create(&out_path).unwrap(); | ||
| 76 | + let mut muxer = oxideav_ogg::mux::open_concrete(Box::new(file), &[stream]).unwrap(); | ||
| 77 | + muxer.set_page_target_bytes(Some(4096)); | ||
| 78 | + muxer.write_header().unwrap(); | ||
| 79 | + for packet in &packets { | ||
| 80 | + // The replica states the granule position in `pts`; the shim is what | ||
| 81 | + // knows that is what it means. | ||
| 82 | + let mut out = Packet::new(0, time_base, packet.data.to_vec()); | ||
| 83 | + out.pts = ec_ogg::granule_of(packet); | ||
| 84 | + out.duration = packet.duration; | ||
| 85 | + muxer.write_packet(&out).unwrap(); | ||
| 86 | + } | ||
| 87 | + muxer.write_trailer().unwrap(); | ||
| 88 | + | ||
| 89 | + // ffprobe reads it without complaint, and it is the same audio. | ||
| 90 | + let probe = Command::new("ffprobe") | ||
| 91 | + .args([ | ||
| 92 | + "-v", | ||
| 93 | + "error", | ||
| 94 | + "-select_streams", | ||
| 95 | + "a:0", | ||
| 96 | + "-count_packets", | ||
| 97 | + "-show_entries", | ||
| 98 | + "stream=codec_name,sample_rate,channels,nb_read_packets", | ||
| 99 | + "-of", | ||
| 100 | + "csv=p=0", | ||
| 101 | + ]) | ||
| 102 | + .arg(&out_path) | ||
| 103 | + .output() | ||
| 104 | + .expect("ffprobe"); | ||
| 105 | + let stderr = String::from_utf8_lossy(&probe.stderr); | ||
| 106 | + assert!(stderr.trim().is_empty(), "ffprobe complained: {stderr}"); | ||
| 107 | + assert_eq!( | ||
| 108 | + String::from_utf8_lossy(&probe.stdout).trim(), | ||
| 109 | + format!("vorbis,{rate},2,{}", packets.len()), | ||
| 110 | + "ffprobe must see the stream the replica described" | ||
| 111 | + ); | ||
| 112 | + assert_eq!( | ||
| 113 | + decode_pcm(&out_path), | ||
| 114 | + decode_pcm(&source), | ||
| 115 | + "the shim's file must decode to the samples that went into it" | ||
| 116 | + ); | ||
| 117 | + let _ = std::fs::remove_file(&out_path); | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// Named apart so the call above reads like the replica's line. | ||
| 121 | +fn super_xiph_lace(headers: &[&[u8]]) -> Option<Vec<u8>> { | ||
| 122 | + oxideav_ogg::mux::xiph_lace(headers) | ||
| 123 | +} | ||