forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ogg.rs831 lines, 28.9 KiBHistoryRawDownload
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
12use std::io::Cursor;
13use std::path::{Path, PathBuf};
14use std::process::Command;
15
16use ec_core::{
17 Buf, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet, PacketFlags, SeekMode,
18 StreamInfo, TimeBase, Timestamp,
19};
20use ec_ogg::{Mapping, OggDemuxer, OggMuxer, granule_of, granule_side_data};
21
22/// The fixture's own name — never the whole path, which carries the checkout
23/// directory and has matched fixture keywords by accident.
24fn name_of(p: &std::path::Path) -> String {
25 p.file_name()
26 .unwrap_or_default()
27 .to_string_lossy()
28 .to_string()
29}
30
31fn fixtures() -> PathBuf {
32 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
33}
34
35/// Working directory keyed by test name: these tests are threads of one
36/// process, so a shared temp directory would have them deleting each other's
37/// files.
38fn workdir(test: &str) -> PathBuf {
39 let dir = std::env::temp_dir().join(format!("ec-ogg-{}-{test}", std::process::id()));
40 std::fs::create_dir_all(&dir).expect("create work dir");
41 dir
42}
43
44/// Every Ogg fixture on disk, sorted so the table reads the same every run.
45fn ogg_fixtures() -> Vec<PathBuf> {
46 let Ok(entries) = std::fs::read_dir(fixtures()) else {
47 return Vec::new();
48 };
49 let mut out: Vec<PathBuf> = entries
50 .flatten()
51 .map(|e| e.path())
52 .filter(|p| {
53 matches!(
54 p.extension().and_then(|s| s.to_str()),
55 Some("ogg") | Some("opus")
56 )
57 })
58 .collect();
59 out.sort();
60 out
61}
62
63/// Audio packets ffprobe counts in a file — header packets excluded, which is
64/// also what this demuxer hands out.
65fn ffprobe_packets(path: &Path) -> u64 {
66 let out = Command::new("ffprobe")
67 .args([
68 "-v",
69 "error",
70 "-select_streams",
71 "a:0",
72 "-count_packets",
73 "-show_entries",
74 "stream=nb_read_packets",
75 "-of",
76 "csv=p=0",
77 ])
78 .arg(path)
79 .output()
80 .expect("ffprobe must be installed: it is the oracle for this crate");
81 String::from_utf8_lossy(&out.stdout)
82 .trim()
83 .parse()
84 .unwrap_or_else(|e| panic!("ffprobe packet count for {}: {e}", path.display()))
85}
86
87/// ffprobe's own duration for the file, in seconds.
88fn ffprobe_duration(path: &Path) -> f64 {
89 let out = Command::new("ffprobe")
90 .args([
91 "-v",
92 "error",
93 "-show_entries",
94 "format=duration",
95 "-of",
96 "csv=p=0",
97 ])
98 .arg(path)
99 .output()
100 .expect("ffprobe");
101 String::from_utf8_lossy(&out.stdout).trim().parse().unwrap()
102}
103
104/// Decode a file to raw 32-bit float samples with ffmpeg. Errors are fatal: an
105/// unreadable file is the failure being tested for.
106fn decode_pcm(path: &Path) -> Vec<u8> {
107 let out = Command::new("ffmpeg")
108 .args(["-v", "error", "-i"])
109 .arg(path)
110 .args(["-f", "f32le", "-"])
111 .output()
112 .expect("ffmpeg");
113 assert!(
114 out.status.success(),
115 "ffmpeg failed to decode {}: {}",
116 path.display(),
117 String::from_utf8_lossy(&out.stderr)
118 );
119 out.stdout
120}
121
122/// ffprobe with errors escalated: the structural verdict on a file we wrote.
123fn ffprobe_clean(path: &Path) -> String {
124 let out = Command::new("ffprobe")
125 .args([
126 "-v",
127 "error",
128 "-show_entries",
129 "stream=codec_name,sample_rate,channels",
130 "-of",
131 "csv=p=0",
132 ])
133 .arg(path)
134 .output()
135 .expect("ffprobe");
136 let stderr = String::from_utf8_lossy(&out.stderr);
137 assert!(
138 stderr.trim().is_empty(),
139 "ffprobe complained about {}: {stderr}",
140 path.display()
141 );
142 String::from_utf8_lossy(&out.stdout).trim().to_string()
143}
144
145/// Read every packet of a file through our demuxer.
146fn demux_all(path: &Path) -> (Vec<StreamInfo>, Vec<Packet>, u64) {
147 let file = std::fs::File::open(path).unwrap();
148 let mut demuxer = OggDemuxer::open(file).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
149 let streams = demuxer.streams().to_vec();
150 let mut packets = Vec::new();
151 loop {
152 match demuxer.next_packet() {
153 Ok(p) => packets.push(p),
154 Err(e) if e.is_eof() => break,
155 Err(e) => panic!("{}: {e}", path.display()),
156 }
157 }
158 (streams, packets, demuxer.damaged_pages())
159}
160
161#[test]
162fn demuxes_every_fixture_to_eof() {
163 let files = ogg_fixtures();
164 if files.is_empty() {
165 eprintln!("fixtures/audio absent (gitignored) — skipping");
166 return;
167 }
168 println!(
169 "{:<28} {:>8} {:>8} {:>10} {:>10}",
170 "file", "ours", "ffprobe", "dur", "ffprobe"
171 );
172 for path in &files {
173 let name = path.file_name().unwrap().to_string_lossy().to_string();
174 let (streams, packets, damaged) = demux_all(path);
175 assert_eq!(damaged, 0, "{name}: an intact fixture has no damaged pages");
176 assert_eq!(streams.len(), 1, "{name}: one logical stream expected");
177 let info = &streams[0];
178 let expected_codec = match name.starts_with("opus") {
179 true => CodecId::Opus,
180 false => CodecId::Vorbis,
181 };
182 assert_eq!(info.params.codec, expected_codec, "{name}");
183 assert!(
184 info.params
185 .extradata
186 .as_ref()
187 .is_some_and(|e| !e.is_empty()),
188 "{name}: setup data must reach the decoder"
189 );
190
191 // The generator names rate and layout in the file name.
192 let MediaParameters::Audio(audio) = &info.params.media else {
193 panic!("{name}: audio parameters expected");
194 };
195 let expect_rate: u32 = name
196 .rsplit('-')
197 .next()
198 .unwrap()
199 .split('.')
200 .next()
201 .unwrap()
202 .parse()
203 .unwrap();
204 let expect_channels = match true {
205 _ if name.contains("mono") => 1,
206 _ if name.contains("stereo") => 2,
207 _ => 6,
208 };
209 assert_eq!(audio.layout.channel_count(), expect_channels, "{name}");
210 match expected_codec {
211 // Opus always decodes at 48 kHz whatever it was fed.
212 CodecId::Opus => assert_eq!(audio.sample_rate, 48_000, "{name}"),
213 _ => assert_eq!(audio.sample_rate, expect_rate, "{name}"),
214 }
215
216 let ours = packets.len() as u64;
217 let theirs = ffprobe_packets(path);
218 assert_eq!(ours, theirs, "{name}: packet count");
219
220 // Duration: ours is the playable length, so Opus differs from ffprobe's
221 // by exactly the pre-skip it reports as part of the granule count.
222 let secs = |ticks: i64| ticks as f64 * info.time_base.as_secs_f64();
223 let our_dur = secs(info.duration.unwrap());
224 let their_dur = ffprobe_duration(path);
225 let pre_skip = secs(info.start_time.unwrap());
226 assert!(
227 (our_dur + pre_skip - their_dur).abs() < 1e-6,
228 "{name}: duration {our_dur} + pre-skip {pre_skip} vs ffprobe {their_dur}"
229 );
230 println!("{name:<28} {ours:>8} {theirs:>8} {our_dur:>10.4} {their_dur:>10.4}");
231
232 // Timestamps are monotonic where the mapping states them, and Opus
233 // states one for every packet.
234 let stamped = packets.iter().filter(|p| p.pts.is_some()).count();
235 match expected_codec {
236 CodecId::Opus => assert_eq!(stamped, packets.len(), "{name}: every Opus pts"),
237 _ => assert!(stamped > 0, "{name}: at least the page-boundary timestamps"),
238 }
239 let mut last = i64::MIN;
240 for p in packets.iter().filter_map(|p| p.pts) {
241 assert!(p >= last, "{name}: timestamps must not go backwards");
242 last = p;
243 }
244 // The last packet ends where the file says the stream ends.
245 assert_eq!(
246 granule_of(packets.last().unwrap()),
247 Some(info.duration.unwrap() + info.start_time.unwrap()),
248 "{name}: the end-of-stream granule reaches the last packet"
249 );
250 }
251 assert!(
252 files.len() >= 9,
253 "expected the nine Ogg fixtures, saw {}",
254 files.len()
255 );
256}
257
258/// Demux a fixture, write its packets back out, and require ffmpeg to decode
259/// the result to the same samples.
260fn remux_case(path: &Path, page_target: Option<usize>) {
261 let name = path.file_name().unwrap().to_string_lossy().to_string();
262 let (streams, packets, _) = demux_all(path);
263 let out_path = workdir("remux").join(format!("remux-{name}"));
264
265 let file = std::fs::File::create(&out_path).unwrap();
266 let mut muxer = OggMuxer::new(std::io::BufWriter::new(file));
267 muxer.add_stream(streams[0].clone()).unwrap();
268 muxer.set_page_target_bytes(page_target);
269 for packet in &packets {
270 muxer.write_packet(packet).unwrap();
271 }
272 muxer.finish().unwrap();
273
274 // Structure: ffprobe reads it without a word of complaint, sees the same
275 // stream and counts the same packets.
276 let described = ffprobe_clean(&out_path);
277 assert!(!described.is_empty(), "{name}: ffprobe described nothing");
278 assert_eq!(
279 ffprobe_packets(&out_path),
280 packets.len() as u64,
281 "{name}: remuxed packet count"
282 );
283 assert!(
284 (ffprobe_duration(&out_path) - ffprobe_duration(path)).abs() < 1e-6,
285 "{name}: remuxed duration"
286 );
287
288 // Content: same samples, byte for byte.
289 let before = decode_pcm(path);
290 let after = decode_pcm(&out_path);
291 assert_eq!(
292 after.len(),
293 before.len(),
294 "{name}: remux decoded to {} bytes, source to {}",
295 after.len(),
296 before.len()
297 );
298 assert!(
299 after == before,
300 "{name}: remuxed audio differs from the source"
301 );
302
303 // And our own demuxer reads back exactly the packets that went in.
304 let (round, again, _) = demux_all(&out_path);
305 assert_eq!(
306 again.len(),
307 packets.len(),
308 "{name}: round-trip packet count"
309 );
310 for (a, b) in again.iter().zip(&packets) {
311 assert_eq!(a.data, b.data, "{name}: payload changed in the round trip");
312 }
313 assert_eq!(round[0].params.codec, streams[0].params.codec);
314 println!(
315 "remux {name:<24} {described} ok ({} packets)",
316 packets.len()
317 );
318}
319
320#[test]
321fn remuxes_every_fixture_bit_identically() {
322 let files = ogg_fixtures();
323 if files.is_empty() {
324 eprintln!("fixtures/audio absent (gitignored) — skipping");
325 return;
326 }
327 for path in &files {
328 remux_case(path, None);
329 }
330}
331
332/// The page-size knob must not change what comes out: one packet per page and
333/// one page for the lot both have to decode identically.
334#[test]
335fn page_size_does_not_change_the_audio() {
336 let files = ogg_fixtures();
337 let Some(path) = files
338 .iter()
339 .find(|p| name_of(p).contains("vorbis-ogg-stereo-48000"))
340 else {
341 eprintln!("fixtures absent — skipping");
342 return;
343 };
344 remux_case(path, Some(1));
345 remux_case(path, Some(1 << 20));
346}
347
348#[test]
349fn damage_costs_one_page_and_no_more() {
350 let files = ogg_fixtures();
351 let Some(path) = files
352 .iter()
353 .find(|p| name_of(p).contains("vorbis-ogg-stereo-44100"))
354 else {
355 eprintln!("fixtures absent — skipping");
356 return;
357 };
358 let (_, clean, _) = demux_all(path);
359 let bytes = std::fs::read(path).unwrap();
360
361 // Flip a bit in the middle of the file: that lands inside a page body, so
362 // the page's checksum fails and its packets are lost — and nothing else is.
363 let mut damaged = bytes.clone();
364 let at = damaged.len() / 2;
365 damaged[at] ^= 0x40;
366 let out = workdir("damage").join("flipped.ogg");
367 std::fs::write(&out, &damaged).unwrap();
368
369 let (streams, packets, dropped) = demux_all(&out);
370 assert_eq!(streams.len(), 1, "the stream is still described");
371 assert_eq!(dropped, 1, "exactly one page fails its checksum");
372 assert!(
373 packets.len() < clean.len(),
374 "the damaged page's packets are gone: {} vs {}",
375 packets.len(),
376 clean.len()
377 );
378 // Recovery, not collapse: what is lost is the damaged page and nothing
379 // else, so every packet after it is still there, byte for byte, in order.
380 // What survives is a prefix of the clean read plus a suffix of it: the
381 // packets of the damaged page, and only those, are missing from the middle.
382 let kept = packets.len();
383 let head = packets
384 .iter()
385 .zip(&clean)
386 .take_while(|(a, b)| a.data == b.data)
387 .count();
388 let tail = packets
389 .iter()
390 .rev()
391 .zip(clean.iter().rev())
392 .take_while(|(a, b)| a.data == b.data)
393 .count();
394 assert!(head > 0, "nothing before the damage was read");
395 assert!(tail > 0, "nothing after the damage was recovered");
396 assert_eq!(
397 head + tail,
398 kept,
399 "recovery is a prefix of {head} and a suffix of {tail} out of {kept} packets"
400 );
401 println!(
402 "damage: {kept} of {} packets survived — {head} before the bad page, {tail} after it",
403 clean.len()
404 );
405}
406
407#[test]
408fn seeks_land_at_or_before_the_target() {
409 let files = ogg_fixtures();
410 if files.is_empty() {
411 eprintln!("fixtures absent — skipping");
412 return;
413 }
414 for path in files.iter().filter(|p| {
415 let n = p.to_string_lossy().to_string();
416 n.contains("stereo-48000") || n.contains("5.1-44100")
417 }) {
418 let name = path.file_name().unwrap().to_string_lossy().to_string();
419 let file = std::fs::File::open(path).unwrap();
420 let mut demuxer = OggDemuxer::open(file).unwrap();
421 let info = demuxer.streams()[0].clone();
422 let duration = info.duration.unwrap();
423 for fraction in [0, 1, 2, 3, 4] {
424 let target = duration * fraction / 4;
425 let to = Timestamp::new(target + info.start_time.unwrap(), info.time_base);
426 demuxer.seek(0, to, SeekMode::SyncBefore).unwrap();
427 let packet = match demuxer.next_packet() {
428 Ok(p) => p,
429 // Seeking to the very end can land on the end-of-stream page.
430 Err(e) if e.is_eof() => continue,
431 Err(e) => panic!("{name}: {e}"),
432 };
433 if let Some(pts) = packet.pts {
434 assert!(
435 pts <= target + info.start_time.unwrap(),
436 "{name}: seek to {target} landed at {pts}"
437 );
438 }
439 // Whatever it landed on, the rest of the file still reads.
440 let mut rest = 1;
441 while let Ok(_p) = demuxer.next_packet() {
442 rest += 1;
443 }
444 assert!(rest > 0, "{name}: nothing readable after the seek");
445 }
446 // Seeking forwards then back to zero returns the whole stream.
447 demuxer
448 .seek(0, Timestamp::new(0, info.time_base), SeekMode::SyncBefore)
449 .unwrap();
450 let mut count = 0;
451 while demuxer.next_packet().is_ok() {
452 count += 1;
453 }
454 let (_, all, _) = demux_all(path);
455 assert!(
456 count >= all.len() - 2,
457 "{name}: after seeking home {count} of {} packets remained",
458 all.len()
459 );
460 }
461}
462
463/// FLAC-in-Ogg: recognised, described and read to the end. No fixture ships in
464/// this mapping, so ffmpeg makes one from a fixture that does.
465#[test]
466fn reads_flac_in_ogg() {
467 let files = ogg_fixtures();
468 let Some(source) = files
469 .iter()
470 .find(|p| name_of(p).contains("vorbis-ogg-stereo-44100"))
471 else {
472 eprintln!("fixtures absent — skipping");
473 return;
474 };
475 let path = workdir("flac").join("flac-in.ogg");
476 let made = Command::new("ffmpeg")
477 .args(["-v", "error", "-y", "-i"])
478 .arg(source)
479 .args(["-c:a", "flac", "-f", "ogg"])
480 .arg(&path)
481 .status()
482 .expect("ffmpeg");
483 assert!(made.success(), "ffmpeg could not write FLAC-in-Ogg");
484
485 let (streams, packets, damaged) = demux_all(&path);
486 assert_eq!(damaged, 0);
487 assert_eq!(streams[0].params.codec, CodecId::Flac);
488 assert_eq!(
489 demuxer_mapping_rate(&streams[0]),
490 44_100,
491 "the rate comes out of STREAMINFO, not the file name"
492 );
493 assert_eq!(packets.len() as u64, ffprobe_packets(&path));
494 println!("flac-in-ogg: {} packets", packets.len());
495}
496
497/// The sample rate a stream description states.
498fn demuxer_mapping_rate(info: &StreamInfo) -> u32 {
499 match &info.params.media {
500 MediaParameters::Audio(audio) => audio.sample_rate,
501 _ => 0,
502 }
503}
504
505/// Payload sizes Ogg's own lacing has to work for, none of which the fixtures
506/// contain: a packet that is exactly a multiple of 255, one that fills more
507/// than one page's segment table, and an empty one.
508#[test]
509fn round_trips_awkward_packet_sizes_through_memory() {
510 let sizes = [
511 1usize, 254, 255, 256, 509, 510, 511, 64_000, 65_025, 300_000,
512 ];
513 let rate = 48_000;
514 let time_base = TimeBase::from_rate(rate);
515
516 let mut params = CodecParameters::new(CodecId::Vorbis);
517 if let MediaParameters::Audio(audio) = &mut params.media {
518 audio.sample_rate = rate;
519 }
520 // A Vorbis triplet is what the mapping requires; the contents only have to
521 // identify, since nothing decodes them here.
522 let mut ident = vec![1u8];
523 ident.extend_from_slice(b"vorbis");
524 ident.extend_from_slice(&0u32.to_le_bytes());
525 ident.push(2);
526 ident.extend_from_slice(&rate.to_le_bytes());
527 ident.resize(30, 0);
528 let comment = vec![3u8; 400];
529 let setup = vec![5u8; 9000];
530 params.extradata = Some(Buf::from_vec(
531 ec_ogg::xiph_lace(&[&ident, &comment, &setup]).unwrap(),
532 ));
533 let info = StreamInfo::new(0, time_base, params);
534
535 let mut muxer = OggMuxer::new(Cursor::new(Vec::new()));
536 muxer.add_stream(info).unwrap();
537 // One packet per page, so every packet carries the page granule back out.
538 muxer.set_page_target_bytes(Some(1));
539 let mut granule = 0i64;
540 let mut written = Vec::new();
541 for (i, size) in sizes.iter().enumerate() {
542 let data: Vec<u8> = (0..*size)
543 .map(|n| (n as u32 % 251) as u8 ^ i as u8)
544 .collect();
545 granule += 1024;
546 let mut packet = Packet::new(0, time_base, data.clone());
547 packet.side_data.push(granule_side_data(granule));
548 muxer.write_packet(&packet).unwrap();
549 written.push(data);
550 }
551 muxer.finish().unwrap();
552 let bytes = muxer.into_inner().into_inner();
553
554 let mut demuxer = OggDemuxer::open(Cursor::new(bytes)).unwrap();
555 assert_eq!(demuxer.streams()[0].params.codec, CodecId::Vorbis);
556 assert_eq!(
557 demuxer.mapping(0),
558 Some(Mapping::Vorbis { rate, channels: 2 })
559 );
560 // Setup data survived the trip laced the way it arrived.
561 let extradata = demuxer.streams()[0].params.extradata.clone().unwrap();
562 let unlaced = ec_ogg::xiph_unlace(&extradata).unwrap();
563 assert_eq!(unlaced.len(), 3);
564 assert_eq!(unlaced[2], &setup[..]);
565
566 let mut read = Vec::new();
567 while let Ok(packet) = demuxer.next_packet() {
568 read.push(packet);
569 }
570 assert_eq!(read.len(), written.len(), "one packet in, one packet out");
571 for (i, (got, want)) in read.iter().zip(&written).enumerate() {
572 assert_eq!(
573 &got.data[..],
574 &want[..],
575 "packet {i} of {} bytes",
576 want.len()
577 );
578 assert_eq!(
579 granule_of(got),
580 Some((i as i64 + 1) * 1024),
581 "packet {i}: granule position"
582 );
583 }
584}
585
586/// Header packets written by the caller replace what extradata would have
587/// produced — the path a remux takes to carry the original `OpusTags` through.
588#[test]
589fn caller_supplied_headers_win_over_extradata() {
590 let time_base = TimeBase::from_rate(48_000);
591 let mut head = Vec::from(*b"OpusHead");
592 head.extend_from_slice(&[1, 2]);
593 head.extend_from_slice(&312u16.to_le_bytes());
594 head.extend_from_slice(&48_000u32.to_le_bytes());
595 head.resize(19, 0);
596
597 let mut params = CodecParameters::new(CodecId::Opus);
598 params.extradata = Some(Buf::from_vec(head.clone()));
599 let info = StreamInfo::new(0, time_base, params);
600
601 let mut tags = Vec::from(*b"OpusTags");
602 tags.extend_from_slice(&4u32.to_le_bytes());
603 tags.extend_from_slice(b"mine");
604 tags.extend_from_slice(&0u32.to_le_bytes());
605
606 let mut muxer = OggMuxer::new(Cursor::new(Vec::new()));
607 muxer.add_stream(info).unwrap();
608 for header in [&head, &tags] {
609 let mut packet = Packet::new(0, time_base, header.clone());
610 packet.flags = PacketFlags {
611 header: true,
612 ..PacketFlags::default()
613 };
614 muxer.write_packet(&packet).unwrap();
615 }
616 // One CELT 20 ms packet, so the stream has audio to end on.
617 let mut audio = Packet::new(0, time_base, vec![(31 << 3) as u8, 0, 0, 0]);
618 audio.side_data.push(granule_side_data(960));
619 muxer.write_packet(&audio).unwrap();
620 muxer.finish().unwrap();
621
622 let bytes = muxer.into_inner().into_inner();
623 // The tags packet we supplied is in the file; the synthesized one is not.
624 let haystack = String::from_utf8_lossy(&bytes).to_string();
625 assert!(
626 haystack.contains("mine"),
627 "caller's OpusTags must be written"
628 );
629 assert!(
630 !haystack.contains("ec-ogg"),
631 "synthesized tags must not appear"
632 );
633
634 let mut demuxer = OggDemuxer::open(Cursor::new(bytes)).unwrap();
635 assert_eq!(demuxer.streams()[0].params.codec, CodecId::Opus);
636 assert_eq!(
637 demuxer.streams()[0].start_time,
638 Some(312),
639 "presentation starts at the pre-skip"
640 );
641 let packet = demuxer.next_packet().unwrap();
642 assert_eq!(packet.duration, Some(960), "TOC states the packet duration");
643 assert_eq!(packet.pts, Some(0));
644 assert!(demuxer.next_packet().unwrap_err().is_eof());
645}
646
647fn vorbis_params(rate: u32) -> CodecParameters {
648 let mut ident = vec![1u8];
649 ident.extend_from_slice(b"vorbis");
650 ident.extend_from_slice(&0u32.to_le_bytes());
651 ident.push(2);
652 ident.extend_from_slice(&rate.to_le_bytes());
653 ident.resize(30, 0);
654 let mut params = CodecParameters::new(CodecId::Vorbis);
655 params.extradata = Some(Buf::from_vec(
656 ec_ogg::xiph_lace(&[&ident, &[3u8], &[5u8]]).unwrap(),
657 ));
658 params
659}
660
661fn opus_params(pre_skip: u16) -> CodecParameters {
662 let mut head = Vec::from(*b"OpusHead");
663 head.extend_from_slice(&[1, 2]);
664 head.extend_from_slice(&pre_skip.to_le_bytes());
665 head.extend_from_slice(&48_000u32.to_le_bytes());
666 head.resize(19, 0);
667 let mut params = CodecParameters::new(CodecId::Opus);
668 params.extradata = Some(Buf::from_vec(head));
669 params
670}
671
672fn flac_headers(rate: u32) -> [Vec<u8>; 2] {
673 let mut head = vec![0u8; 51];
674 head[0] = 0x7f;
675 head[1..5].copy_from_slice(b"FLAC");
676 head[7..9].copy_from_slice(&1u16.to_be_bytes());
677 head[9..13].copy_from_slice(b"fLaC");
678 let si = &mut head[17..51];
679 si[10] = (rate >> 12) as u8;
680 si[11] = (rate >> 4) as u8;
681 si[12] = ((rate & 0x0f) as u8) << 4 | (1 << 1);
682 [head, vec![0x84, 0, 0, 0]]
683}
684
685fn mux_seek_case(
686 codec: CodecId,
687 time_base: TimeBase,
688 headers: &[Vec<u8>],
689 granules: &[i64],
690 packets: &[Vec<u8>],
691) -> Vec<u8> {
692 let mut muxer = OggMuxer::new(Cursor::new(Vec::new()));
693 let mut params = CodecParameters::new(codec);
694 if headers.is_empty() {
695 params = match codec {
696 CodecId::Vorbis => vorbis_params(time_base.den() as u32),
697 CodecId::Opus => opus_params(granules[0] as u16),
698 _ => params,
699 };
700 }
701 muxer
702 .add_stream(StreamInfo::new(0, time_base, params))
703 .unwrap();
704 for header in headers {
705 let mut packet = Packet::new(0, time_base, header.clone());
706 packet.flags = PacketFlags {
707 header: true,
708 ..PacketFlags::default()
709 };
710 muxer.write_packet(&packet).unwrap();
711 }
712 for (packet, granule) in packets.iter().zip(granules) {
713 let mut packet = Packet::new(0, time_base, packet.clone());
714 packet.side_data.push(granule_side_data(*granule));
715 muxer.write_packet(&packet).unwrap();
716 }
717 muxer.finish().unwrap();
718 muxer.into_inner().into_inner()
719}
720
721#[test]
722fn seek_to_first_data_granule_replays_the_first_packet() {
723 let cases = [
724 (
725 CodecId::Vorbis,
726 TimeBase::from_rate(48_000),
727 Vec::new(),
728 vec![0, 1024],
729 vec![b"first-vorbis".to_vec(), b"second-vorbis".to_vec()],
730 ),
731 (
732 CodecId::Opus,
733 TimeBase::from_rate(48_000),
734 Vec::new(),
735 vec![312, 1272],
736 vec![
737 vec![(31 << 3) as u8, 0, 0, 0],
738 vec![(31 << 3) as u8, 1, 2, 3],
739 ],
740 ),
741 (
742 CodecId::Flac,
743 TimeBase::from_rate(48_000),
744 flac_headers(48_000).to_vec(),
745 vec![1024, 2048],
746 vec![b"first-flac".to_vec(), b"second-flac".to_vec()],
747 ),
748 ];
749
750 for (codec, time_base, headers, granules, packets) in cases {
751 let bytes = mux_seek_case(codec, time_base, &headers, &granules, &packets);
752 let mut fresh = OggDemuxer::open(Cursor::new(bytes.clone())).unwrap();
753 let first = fresh.next_packet().unwrap();
754
755 let mut seeked = OggDemuxer::open(Cursor::new(bytes)).unwrap();
756 seeked
757 .seek(
758 0,
759 Timestamp::new(granules[0], time_base),
760 SeekMode::SyncBefore,
761 )
762 .unwrap();
763 let after_seek = seeked.next_packet().unwrap();
764
765 assert_eq!(after_seek.data, first.data, "{codec:?}: first packet data");
766 assert_eq!(
767 granule_of(&after_seek),
768 granule_of(&first),
769 "{codec:?}: first packet granule"
770 );
771 assert_eq!(after_seek.pts, first.pts, "{codec:?}: first packet pts");
772 }
773}
774
775/// Fuzzing regression: a granule position at the bottom of `i64` on the last page of an Opus
776/// stream made `granule - pre_skip` overflow when the demuxer measured the duration.
777#[test]
778fn granule_at_i64_floor_does_not_overflow_the_duration() {
779 let time_base = TimeBase::from_rate(48_000);
780 let mut head = Vec::from(*b"OpusHead");
781 head.extend_from_slice(&[1, 2]);
782 head.extend_from_slice(&312u16.to_le_bytes()); // pre-skip, so start_time is non-zero
783 head.extend_from_slice(&48_000u32.to_le_bytes());
784 head.resize(19, 0);
785 let mut params = CodecParameters::new(CodecId::Opus);
786 params.extradata = Some(Buf::from_vec(head));
787
788 let mut muxer = OggMuxer::new(Cursor::new(Vec::new()));
789 muxer.add_stream(StreamInfo::new(0, time_base, params)).unwrap();
790 let mut packet = Packet::new(0, time_base, vec![0xf8, 0, 0]); // config 31, one frame
791 packet.side_data.push(granule_side_data(i64::MIN));
792 muxer.write_packet(&packet).unwrap();
793 muxer.finish().unwrap();
794 let bytes = muxer.into_inner().into_inner();
795
796 let demuxer = OggDemuxer::open(Cursor::new(bytes)).unwrap();
797 assert_eq!(demuxer.streams()[0].duration, None, "no duration can be stated");
798}
799
800/// Fuzzing regression: a page whose granule sits near `i64::MAX` made the running packet
801/// position overflow when the next packet (which has no granule of its own) advanced it.
802#[test]
803fn packet_position_near_i64_max_saturates_instead_of_overflowing() {
804 let time_base = TimeBase::from_rate(48_000);
805 let mut head = Vec::from(*b"OpusHead");
806 head.extend_from_slice(&[1, 2]);
807 head.extend_from_slice(&0u16.to_le_bytes());
808 head.extend_from_slice(&48_000u32.to_le_bytes());
809 head.resize(19, 0);
810 let mut params = CodecParameters::new(CodecId::Opus);
811 params.extradata = Some(Buf::from_vec(head));
812
813 let mut muxer = OggMuxer::new(Cursor::new(Vec::new()));
814 muxer.add_stream(StreamInfo::new(0, time_base, params)).unwrap();
815 // One packet per page, so the second packet sits on a page with no granule of its own.
816 muxer.set_page_target_bytes(Some(1));
817 let mut first = Packet::new(0, time_base, vec![0xf8, 0, 0]);
818 first.side_data.push(granule_side_data(i64::MAX - 100));
819 muxer.write_packet(&first).unwrap();
820 muxer.write_packet(&Packet::new(0, time_base, vec![0xf8, 1, 1])).unwrap();
821 muxer.finish().unwrap();
822 let bytes = muxer.into_inner().into_inner();
823
824 let mut demuxer = OggDemuxer::open(Cursor::new(bytes)).unwrap();
825 let mut read = Vec::new();
826 while let Ok(packet) = demuxer.next_packet() {
827 read.push(packet);
828 }
829 assert_eq!(read.len(), 2, "both packets are still delivered");
830 assert_eq!(read[1].pts, Some(i64::MAX - 100), "the packet that overflowed keeps its start");
831}