forge
Explore
Log in

Don't you dare go Hollow

U18: ec-mpegts drop the Stats counters and the with_walk_limit hook (no caller in edith or yumush; the full-walk path is FULL_WALK), and trim synthetic.rs to the round trip

Browse files at this commit

5b7f1f5a9620e711a8ccc8e262666ff9f5a7b408Ahmet Kaan GümüşParent: 5e2a73b
crates/ec-mpegts/src/demux.rsmodified+1 -43
@@ -60,27 +60,6 @@ pub struct TrackInfo {
60 pub language: Option<String>,60 pub language: Option<String>,
61 }61 }
62 62
63-/// Counters of what the demuxer had to put up with.
64-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
65-pub struct Stats {
66- /// Times the sync byte was lost and found again.
67- pub resyncs: u64,
68- /// Continuity-counter gaps on tracked PIDs.
69- pub cc_errors: u64,
70- /// Duplicate packets dropped.
71- pub duplicates: u64,
72- /// PSI sections with a bad CRC.
73- pub crc_errors: u64,
74- /// Packets with the transport error indicator set.
75- pub tei: u64,
76- /// `discontinuity_indicator` seen.
77- pub discontinuities: u64,
78- /// PMT changes after the first (of the selected program).
79- pub pmt_changes: u64,
80- /// PES packets dropped (bad start code, oversize).
81- pub bad_pes: u64,
82-}
83-
84 enum Cc {63 enum Cc {
85 Ok,64 Ok,
86 Dup,65 Dup,
@@ -181,7 +160,6 @@ pub struct TsDemuxer<R> {
181 streams: Vec<StreamInfo>,160 streams: Vec<StreamInfo>,
182 queue: VecDeque<Queued>,161 queue: VecDeque<Queued>,
183 eof: bool,162 eof: bool,
184- stats: Stats,
185 framing: VideoFraming,163 framing: VideoFraming,
186 last_off: u64,164 last_off: u64,
187 duration: Option<i64>,165 duration: Option<i64>,
@@ -226,7 +204,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
226 streams: Vec::new(),204 streams: Vec::new(),
227 queue: VecDeque::new(),205 queue: VecDeque::new(),
228 eof: false,206 eof: false,
229- stats: Stats::default(),
230 framing: VideoFraming::AnnexB,207 framing: VideoFraming::AnnexB,
231 last_off: first_off,208 last_off: first_off,
232 duration: None,209 duration: None,
@@ -300,11 +277,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
300 self.duration.map(|d| d as f64 / TICKS as f64)277 self.duration.map(|d| d as f64 / TICKS as f64)
301 }278 }
302 279
303- /// Counters of what the demuxer repaired or skipped so far.
304- pub fn stats(&self) -> Stats {
305- self.stats
306- }
307-
308 /// First PCR (27 MHz) seen on the program's PCR PID.280 /// First PCR (27 MHz) seen on the program's PCR PID.
309 pub fn first_pcr(&self) -> Option<u64> {281 pub fn first_pcr(&self) -> Option<u64> {
310 self.first_pcr282 self.first_pcr
@@ -405,7 +377,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
405 }377 }
406 };378 };
407 if !ok {379 if !ok {
408- self.stats.resyncs += 1;
409 self.mark_bad();380 self.mark_bad();
410 self.cc.clear();381 self.cc.clear();
411 for s in self.sections.values_mut() {382 for s in self.sections.values_mut() {
@@ -430,7 +401,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
430 return Ok(true);401 return Ok(true);
431 }402 }
432 if h.tei {403 if h.tei {
433- self.stats.tei += 1;
434 if let Some(&ti) = self.pid_map.get(&h.pid) {404 if let Some(&ti) = self.pid_map.get(&h.pid) {
435 self.tracks[ti].pes_bad = true;405 self.tracks[ti].pes_bad = true;
436 }406 }
@@ -442,7 +412,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
442 self.first_pcr.get_or_insert(pcr);412 self.first_pcr.get_or_insert(pcr);
443 }413 }
444 if h.discontinuity {414 if h.discontinuity {
445- self.stats.discontinuities += 1;
446 }415 }
447 let is_psi = h.pid == 0 || self.programs.iter().any(|p| p.pmt_pid == h.pid);416 let is_psi = h.pid == 0 || self.programs.iter().any(|p| p.pmt_pid == h.pid);
448 let tracked = self.pid_map.get(&h.pid).copied();417 let tracked = self.pid_map.get(&h.pid).copied();
@@ -452,11 +421,9 @@ impl<R: Read + Seek> TsDemuxer<R> {
452 let cc = self.cc_check(&h, &pkt);421 let cc = self.cc_check(&h, &pkt);
453 match cc {422 match cc {
454 Cc::Dup => {423 Cc::Dup => {
455- self.stats.duplicates += 1;
456 return Ok(true);424 return Ok(true);
457 }425 }
458 Cc::Gap => {426 Cc::Gap => {
459- self.stats.cc_errors += 1;
460 if let Some(ti) = tracked {427 if let Some(ti) = tracked {
461 self.tracks[ti].pes_bad = true;428 self.tracks[ti].pes_bad = true;
462 }429 }
@@ -472,12 +439,10 @@ impl<R: Read + Seek> TsDemuxer<R> {
472 let payload = &pkt[h.payload.0..h.payload.1];439 let payload = &pkt[h.payload.0..h.payload.1];
473 if is_psi {440 if is_psi {
474 let mut out = Vec::new();441 let mut out = Vec::new();
475- let bad = self442+ self.sections
476- .sections
477 .entry(h.pid)443 .entry(h.pid)
478 .or_default()444 .or_default()
479 .push(h.pusi, payload, &mut out);445 .push(h.pusi, payload, &mut out);
480- self.stats.crc_errors += u64::from(bad);
481 for s in out {446 for s in out {
482 self.on_section(h.pid, &s);447 self.on_section(h.pid, &s);
483 }448 }
@@ -504,7 +469,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
504 t.pes_expect = None;469 t.pes_expect = None;
505 if payload.len() >= 3 && payload[..3] != [0, 0, 1] {470 if payload.len() >= 3 && payload[..3] != [0, 0, 1] {
506 t.pes_on = false;471 t.pes_on = false;
507- self.stats.bad_pes += 1;
508 return;472 return;
509 }473 }
510 } else if !self.tracks[ti].pes_on {474 } else if !self.tracks[ti].pes_on {
@@ -521,7 +485,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
521 if t.pes.len() > MAX_PES {485 if t.pes.len() > MAX_PES {
522 t.pes_on = false;486 t.pes_on = false;
523 t.pes.clear();487 t.pes.clear();
524- self.stats.bad_pes += 1;
525 return;488 return;
526 }489 }
527 if let Some(n) = t.pes_expect490 if let Some(n) = t.pes_expect
@@ -540,7 +503,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
540 t.pes_on = false;503 t.pes_on = false;
541 let buf = std::mem::take(&mut t.pes);504 let buf = std::mem::take(&mut t.pes);
542 let Some(head) = parse_pes(&buf) else {505 let Some(head) = parse_pes(&buf) else {
543- self.stats.bad_pes += 1;
544 t.pes = buf;506 t.pes = buf;
545 t.pes.clear();507 t.pes.clear();
546 return;508 return;
@@ -650,7 +612,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
650 return;612 return;
651 }613 }
652 if self.pmt_seen {614 if self.pmt_seen {
653- self.stats.pmt_changes += 1;
654 }615 }
655 self.pmt_seen = true;616 self.pmt_seen = true;
656 for ti in 0..self.tracks.len() {617 for ti in 0..self.tracks.len() {
@@ -747,7 +708,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
747 self.frozen = false;708 self.frozen = false;
748 tail?;709 tail?;
749 self.reset_at(self.first_off, None);710 self.reset_at(self.first_off, None);
750- self.stats = Stats::default();
751 Ok(())711 Ok(())
752 }712 }
753 713
@@ -957,11 +917,9 @@ impl<R: Read + Seek + Send> Demuxer for TsDemuxer<R> {
957 }917 }
958 918
959 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {919 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
960- let saved = self.stats;
961 self.frozen = true;920 self.frozen = true;
962 let r = self.seek_scan(stream, to, mode);921 let r = self.seek_scan(stream, to, mode);
963 self.frozen = false;922 self.frozen = false;
964- self.stats = saved;
965 // The landing re-read starts with the PSI of the stream again.923 // The landing re-read starts with the PSI of the stream again.
966 r924 r
967 }925 }
crates/ec-mpegts/src/lib.rsmodified+1 -1
@@ -69,7 +69,7 @@ pub use codec::{
69 LpcmHeader, NalIter, StreamKind, annexb_to_length_prefixed, audio_specific_config, build_avcc,69 LpcmHeader, NalIter, StreamKind, annexb_to_length_prefixed, audio_specific_config, build_avcc,
70 build_hvcc, nal_units, parse_lpcm_header,70 build_hvcc, nal_units, parse_lpcm_header,
71 };71 };
72-pub use demux::{ProgramInfo, Stats, TrackInfo, TsDemuxer, VideoFraming};72+pub use demux::{ProgramInfo, TrackInfo, TsDemuxer, VideoFraming};
73 pub use ps::{PsDemuxer, PsKind, is_mpeg_video_es, is_mpegps};73 pub use ps::{PsDemuxer, PsKind, is_mpeg_video_es, is_mpegps};
74 pub use psi::{EsEntry, Pmt};74 pub use psi::{EsEntry, Pmt};
75 75
crates/ec-mpegts/src/ps.rsmodified+4 -28
@@ -21,7 +21,7 @@ use ec_core::registry::{Demuxer, SeekMode, StreamInfo};
21 use ec_core::{Error, Packet, PacketFlags, Result, Rounding, TimeBase, Timestamp};21 use ec_core::{Error, Packet, PacketFlags, Result, Rounding, TimeBase, Timestamp};
22 22
23 use crate::codec::{StreamKind, annexb_to_length_prefixed};23 use crate::codec::{StreamKind, annexb_to_length_prefixed};
24-use crate::demux::{Stats, TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33};24+use crate::demux::{TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33};
25 use crate::psi::{EsEntry, descriptors};25 use crate::psi::{EsEntry, descriptors};
26 use crate::track::{PesIn, Queued, TICKS, Track};26 use crate::track::{PesIn, Queued, TICKS, Track};
27 use crate::window::Window;27 use crate::window::Window;
@@ -250,7 +250,6 @@ pub struct PsDemuxer<R> {
250 streams: Vec<StreamInfo>,250 streams: Vec<StreamInfo>,
251 queue: VecDeque<Queued>,251 queue: VecDeque<Queued>,
252 eof: bool,252 eof: bool,
253- stats: Stats,
254 framing: VideoFraming,253 framing: VideoFraming,
255 last_off: u64,254 last_off: u64,
256 duration: Option<i64>,255 duration: Option<i64>,
@@ -268,23 +267,15 @@ pub struct PsDemuxer<R> {
268 /// After a seek that started reading earlier (see [`PsDemuxer::land`]): drop every267 /// After a seek that started reading earlier (see [`PsDemuxer::land`]): drop every
269 /// packet that starts before this offset.268 /// packet that starts before this offset.
270 pre_drop: Option<u64>,269 pre_drop: Option<u64>,
271- walk_limit: u64,
272 }270 }
273 271
274 impl<R: Read + Seek> PsDemuxer<R> {272 impl<R: Read + Seek> PsDemuxer<R> {
275 /// Opens `reader` as a program stream, a system stream or a raw video stream.273 /// Opens `reader` as a program stream, a system stream or a raw video stream.
276 pub fn new(reader: R) -> Result<PsDemuxer<R>> {274 pub fn new(reader: R) -> Result<PsDemuxer<R>> {
277- Self::open(reader, FULL_WALK)275+ Self::open(reader)
278 }276 }
279 277
280- /// As [`PsDemuxer::new`], with files larger than `walk_limit` bytes checked for SCR278+ fn open(reader: R) -> Result<PsDemuxer<R>> {
281- /// resets by sampling instead of a full walk (tests exercise that path on small files).
282- #[doc(hidden)]
283- pub fn with_walk_limit(reader: R, walk_limit: u64) -> Result<PsDemuxer<R>> {
284- Self::open(reader, walk_limit)
285- }
286-
287- fn open(reader: R, walk_limit: u64) -> Result<PsDemuxer<R>> {
288 let mut win = Window::new(reader);279 let mut win = Window::new(reader);
289 let file_len = win.len()?;280 let file_len = win.len()?;
290 let head = win.get(0, 64 * 1024)?;281 let head = win.get(0, 64 * 1024)?;
@@ -315,7 +306,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
315 streams: Vec::new(),306 streams: Vec::new(),
316 queue: VecDeque::new(),307 queue: VecDeque::new(),
317 eof: false,308 eof: false,
318- stats: Stats::default(),
319 framing: VideoFraming::AnnexB,309 framing: VideoFraming::AnnexB,
320 last_off: first_off,310 last_off: first_off,
321 duration: None,311 duration: None,
@@ -332,7 +322,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
332 bad_next: false,322 bad_next: false,
333 skip: None,323 skip: None,
334 pre_drop: None,324 pre_drop: None,
335- walk_limit,
336 };325 };
337 if kind == PsKind::VideoElementary {326 if kind == PsKind::VideoElementary {
338 d.open_es()?;327 d.open_es()?;
@@ -390,12 +379,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
390 self.duration.map(|d| d as f64 / TICKS as f64)379 self.duration.map(|d| d as f64 / TICKS as f64)
391 }380 }
392 381
393- /// Counters of what was repaired or skipped (`resyncs`, `discontinuities` = SCR
394- /// resets, `bad_pes`); the transport-only counters stay 0.
395- pub fn stats(&self) -> Stats {
396- self.stats
397- }
398-
399 /// SCR resets found in the file (concatenated VOBs, cell boundaries): timestamps382 /// SCR resets found in the file (concatenated VOBs, cell boundaries): timestamps
400 /// after each are shifted to continue the timeline.383 /// after each are shifted to continue the timeline.
401 pub fn epoch_count(&self) -> usize {384 pub fn epoch_count(&self) -> usize {
@@ -502,7 +485,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
502 Ok(false)485 Ok(false)
503 }486 }
504 El::Bad => {487 El::Bad => {
505- self.stats.resyncs += 1;
506 self.mark_bad();488 self.mark_bad();
507 match self.next_pack(pos + 1)? {489 match self.next_pack(pos + 1)? {
508 Some(p) => {490 Some(p) => {
@@ -552,7 +534,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
552 self.first_scr = Some(scr as i64);534 self.first_scr = Some(scr as i64);
553 }535 }
554 if self.clock.feed(scr) {536 if self.clock.feed(scr) {
555- self.stats.discontinuities += 1;
556 // The table made at open knows this join with its aligned shift.537 // The table made at open knows this join with its aligned shift.
557 if let Some(e) = self.epochs.iter().find(|e| e.off == at) {538 if let Some(e) = self.epochs.iter().find(|e| e.off == at) {
558 self.clock.shift = e.shift;539 self.clock.shift = e.shift;
@@ -619,7 +600,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
619 match parse_pes(b) {600 match parse_pes(b) {
620 Some(h) => (h.pts, h.dts, h.payload),601 Some(h) => (h.pts, h.dts, h.payload),
621 None => {602 None => {
622- self.stats.bad_pes += 1;
623 return;603 return;
624 }604 }
625 }605 }
@@ -627,7 +607,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
627 match parse_pes1(b) {607 match parse_pes1(b) {
628 Some(h) => h,608 Some(h) => h,
629 None => {609 None => {
630- self.stats.bad_pes += 1;
631 return;610 return;
632 }611 }
633 }612 }
@@ -805,7 +784,7 @@ impl<R: Read + Seek> PsDemuxer<R> {
805 /// Finds SCR resets: the whole file when it is small, otherwise a sample of pack784 /// Finds SCR resets: the whole file when it is small, otherwise a sample of pack
806 /// headers decides whether a full walk is needed.785 /// headers decides whether a full walk is needed.
807 fn build_epochs(&mut self) -> Result<()> {786 fn build_epochs(&mut self) -> Result<()> {
808- let full = if self.file_len <= self.walk_limit {787+ let full = if self.file_len <= FULL_WALK {
809 true788 true
810 } else {789 } else {
811 let mut last: Option<u64> = None;790 let mut last: Option<u64> = None;
@@ -986,7 +965,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
986 self.frozen = false;965 self.frozen = false;
987 tail?;966 tail?;
988 self.reset_at(self.first_off);967 self.reset_at(self.first_off);
989- self.stats = Stats::default();
990 Ok(())968 Ok(())
991 }969 }
992 970
@@ -1562,11 +1540,9 @@ impl<R: Read + Seek + Send> Demuxer for PsDemuxer<R> {
1562 }1540 }
1563 1541
1564 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {1542 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
1565- let saved = self.stats;
1566 self.frozen = true;1543 self.frozen = true;
1567 let r = self.seek_scan(stream, to, mode);1544 let r = self.seek_scan(stream, to, mode);
1568 self.frozen = false;1545 self.frozen = false;
1569- self.stats = saved;
1570 r1546 r
1571 }1547 }
1572 }1548 }
crates/ec-mpegts/tests/it/ffmpeg_parity.rsmodified+1 -8
@@ -505,13 +505,6 @@ fn corrupted_and_truncated() {
505 "{name}: only {n} of {} packets",505 "{name}: only {n} of {} packets",
506 want.len()506 want.len()
507 );507 );
508- let st = d.stats();508+ eprintln!("{name}: {n} packets, {flagged} flagged");
509- if name == "overwritten" || name == "bytes removed" {
510- assert!(
511- st.resyncs > 0 || st.cc_errors > 0,
512- "{name}: damage unnoticed {st:?}"
513- );
514- }
515- eprintln!("{name}: {n} packets, {flagged} flagged, {st:?}");
516 }509 }
517 }510 }
crates/ec-mpegts/tests/it/ps.rsmodified+6 -15
@@ -554,16 +554,10 @@ fn per_stream(p: &[Pkt]) -> Vec<Vec<&Pkt>> {
554 }554 }
555 555
556 /// `copies` of a file back to back: the SCR (and the PTS) restart in each.556 /// `copies` of a file back to back: the SCR (and the PTS) restart in each.
557-fn check_concat(bytes: &[u8], copies: usize, walk_limit: Option<u64>) {557+fn check_concat(bytes: &[u8], copies: usize) {
558 let cat: Vec<u8> = (0..copies).flat_map(|_| bytes.iter().copied()).collect();558 let cat: Vec<u8> = (0..copies).flat_map(|_| bytes.iter().copied()).collect();
559 let path = tmpfile("concat.vob", &cat);559 let path = tmpfile("concat.vob", &cat);
560- let open = |p: &Path| {560+ let open = |p: &Path| PsDemuxer::new(BufReader::new(File::open(p).unwrap())).unwrap();
561- let f = BufReader::new(File::open(p).unwrap());
562- match walk_limit {
563- Some(l) => PsDemuxer::with_walk_limit(f, l).unwrap(),
564- None => PsDemuxer::new(f).unwrap(),
565- }
566- };
567 let single = {561 let single = {
568 let mut d = open_bytes(bytes.to_vec()).unwrap();562 let mut d = open_bytes(bytes.to_vec()).unwrap();
569 let mut v = Vec::new();563 let mut v = Vec::new();
@@ -575,7 +569,6 @@ fn check_concat(bytes: &[u8], copies: usize, walk_limit: Option<u64>) {
575 let mut d = open(&path);569 let mut d = open(&path);
576 assert_eq!(d.epoch_count(), copies, "SCR resets found at open");570 assert_eq!(d.epoch_count(), copies, "SCR resets found at open");
577 let all = read_ps(&mut d);571 let all = read_ps(&mut d);
578- assert_eq!(d.stats().discontinuities, copies as u64 - 1);
579 assert_eq!(all.len(), single.len() * copies);572 assert_eq!(all.len(), single.len() * copies);
580 let ps = per_stream(&all);573 let ps = per_stream(&all);
581 let mut shift = None;574 let mut shift = None;
@@ -622,10 +615,8 @@ fn check_concat(bytes: &[u8], copies: usize, walk_limit: Option<u64>) {
622 #[test]615 #[test]
623 fn concatenated_vobs_keep_time_monotonic() {616 fn concatenated_vobs_keep_time_monotonic() {
624 let b = committed("ps_mpeg2_ac3.vob");617 let b = committed("ps_mpeg2_ac3.vob");
625- check_concat(&b, 3, None);618+ check_concat(&b, 3);
626- // The same through the sampling check used for big files.619+ check_concat(&committed("ps_mpeg1_mp2.mpg"), 2);
627- check_concat(&b, 3, Some(1));
628- check_concat(&committed("ps_mpeg1_mp2.mpg"), 2, None);
629 }620 }
630 621
631 #[test]622 #[test]
@@ -647,7 +638,7 @@ fn concatenated_dvd_files_with_nav_packets() {
647 &["-c:a", "ac3", "-ar", "48000"],638 &["-c:a", "ac3", "-ar", "48000"],
648 &["-f", "dvd"],639 &["-f", "dvd"],
649 );640 );
650- check_concat(&std::fs::read(p).unwrap(), 2, None);641+ check_concat(&std::fs::read(p).unwrap(), 2);
651 }642 }
652 643
653 #[test]644 #[test]
@@ -796,7 +787,7 @@ fn exercise(bytes: Vec<u8>) {
796 let Ok(mut d) = open_bytes(bytes) else {787 let Ok(mut d) = open_bytes(bytes) else {
797 return;788 return;
798 };789 };
799- let _ = (d.tracks(), d.duration_secs(), d.stats(), d.epoch_count());790+ let _ = (d.tracks(), d.duration_secs(), d.epoch_count());
800 for round in 0..2 {791 for round in 0..2 {
801 if round == 1 {792 if round == 1 {
802 d.set_video_framing(ec_mpegts::VideoFraming::LengthPrefixed);793 d.set_video_framing(ec_mpegts::VideoFraming::LengthPrefixed);
crates/ec-mpegts/tests/it/robust.rsmodified+1 -1
@@ -13,7 +13,7 @@ fn exercise(bytes: Vec<u8>) {
13 let Ok(mut d) = TsDemuxer::new(Cursor::new(bytes)) else {13 let Ok(mut d) = TsDemuxer::new(Cursor::new(bytes)) else {
14 return;14 return;
15 };15 };
16- let _ = (d.tracks(), d.programs().len(), d.duration_secs(), d.stats());16+ let _ = (d.tracks(), d.programs().len(), d.duration_secs());
17 for round in 0..2 {17 for round in 0..2 {
18 if round == 1 {18 if round == 1 {
19 d.set_video_framing(VideoFraming::LengthPrefixed);19 d.set_video_framing(VideoFraming::LengthPrefixed);
crates/ec-mpegts/tests/it/synthetic.rsmodified+3 -246
@@ -1,16 +1,12 @@
1-//! Hand-built transport streams for the corners ffmpeg's muxer never produces: a PCR1+//! Hand-built transport stream round trip.
2-//! on its own PID, several access units in one PES, 204-byte packets, duplicate
3-//! packets, PMT changes, damaged PSI, refused stream types, PGS.
4 2
5 use std::collections::HashMap;3 use std::collections::HashMap;
6-use std::fs::File;4+use std::io::Cursor;
7-use std::io::{BufReader, Cursor};
8 use std::path::PathBuf;5 use std::path::PathBuf;
9 6
10 use crate::common::crc32;7 use crate::common::crc32;
11-use ec_core::CodecId;
12 use ec_core::registry::Demuxer;8 use ec_core::registry::Demuxer;
13-use ec_mpegts::{StreamKind, TsDemuxer};9+use ec_mpegts::TsDemuxer;
14 10
15 fn tiny(name: &str) -> Vec<u8> {11 fn tiny(name: &str) -> Vec<u8> {
16 std::fs::read(12 std::fs::read(
@@ -329,243 +325,4 @@ fn rebuilt_stream_equals_the_original() {
329 assert_eq!(by_stream(&got, s), by_stream(&want, s), "stream {s}");325 assert_eq!(by_stream(&got, s), by_stream(&want, s), "stream {s}");
330 }326 }
331 assert_eq!(d.packet_size(), 188);327 assert_eq!(d.packet_size(), 188);
332- assert_eq!(d.stats().cc_errors, 0);
333-}
334-
335-#[test]
336-fn pcr_on_its_own_pid() {
337- let (got, d) = packets(build(188, 0x1FF0, false));
338- assert_eq!(d.pcr_pid(), Some(0x1FF0));
339- assert!(d.first_pcr().is_some());
340- assert_eq!(d.tracks().len(), 2);
341- assert_eq!(by_stream(&got, 0), by_stream(&reference(), 0));
342-}
343-
344-#[test]
345-fn packet_sizes_192_and_204() {
346- for size in [192, 204] {
347- let (got, d) = packets(build(size, VPID, false));
348- assert_eq!(d.packet_size(), size);
349- assert_eq!(d.is_bdav(), size == 192);
350- assert_eq!(
351- by_stream(&got, 1),
352- by_stream(&reference(), 1),
353- "size {size}"
354- );
355- assert_eq!(
356- by_stream(&got, 0),
357- by_stream(&reference(), 0),
358- "size {size}"
359- );
360- }
361-}
362-
363-#[test]
364-fn two_access_units_in_one_pes_are_split_on_the_delimiter() {
365- let (got, _) = packets(build(188, VPID, true));
366- let want = reference();
367- let (g, w) = (by_stream(&got, 0), by_stream(&want, 0));
368- assert_eq!(g.len(), w.len());
369- for (a, b) in g.iter().zip(&w) {
370- assert_eq!(a.3, b.3);
371- assert_eq!(a.2, b.2, "keyframe flag");
372- }
373- // The second unit of a pair has no timestamp of its own.
374- assert!(g.iter().filter(|p| p.1.is_none()).count() >= 5);
375-}
376-
377-#[test]
378-fn duplicate_packets_are_dropped() {
379- let clean = build(188, VPID, false);
380- let mut dup = Vec::new();
381- for (i, p) in clean.chunks(188).enumerate() {
382- dup.extend_from_slice(p);
383- if i % 7 == 3 && p[1] & 0x1f == 1 {
384- dup.extend_from_slice(p);
385- }
386- }
387- let (got, d) = packets(dup);
388- assert!(d.stats().duplicates > 0);
389- assert_eq!(by_stream(&got, 0), by_stream(&packets(clean).0, 0));
390-}
391-
392-#[test]
393-fn damaged_psi_is_ignored() {
394- let mut bytes = build(188, VPID, false);
395- // The first PMT's CRC byte: second packet, last section byte.
396- let mut broken = bytes.clone();
397- let pmt = &mut broken[188..376];
398- let st = 5 + usize::from(pmt[4]); // past the adaptation field and the pointer
399- let end = st + 3 + (usize::from(pmt[st + 2] & 0xf) << 8 | usize::from(pmt[st + 3]));
400- pmt[end] ^= 0xFF;
401- // Later copies of the PMT are intact, so the file still opens; the damage is counted.
402- let (_, d) = packets(broken);
403- assert!(d.stats().crc_errors >= 1, "{:?}", d.stats());
404- // Garbage everywhere in the PAT leaves nothing to open.
405- for b in &mut bytes[..188] {
406- *b = 0x47;
407- }
408- for (i, p) in bytes.chunks_mut(188).enumerate() {
409- if p[1] == 0x40 && p[2] == 0 && i % 4 == 0 {
410- p[10] ^= 0x55;
411- }
412- }
413- let _ = TsDemuxer::new(Cursor::new(bytes));
414-}
415-
416-#[test]
417-fn refusals_name_the_codec_and_pgs_is_exposed() {
418- let es = vec![
419- Es {
420- pid: 0x100,
421- stream_type: 0x02,
422- descriptors: vec![],
423- },
424- Es {
425- pid: 0x101,
426- stream_type: 0x11,
427- descriptors: vec![],
428- },
429- Es {
430- pid: 0x102,
431- stream_type: 0x90,
432- descriptors: vec![],
433- },
434- Es {
435- pid: 0x103,
436- stream_type: 0x06,
437- descriptors: vec![0x6A, 1, 0],
438- },
439- Es {
440- pid: 0x104,
441- stream_type: 0x06,
442- descriptors: vec![0x59, 0],
443- },
444- Es {
445- pid: 0x105,
446- stream_type: 0x83,
447- descriptors: vec![],
448- },
449- ];
450- let mut m = Mux::new(192);
451- m.tables(0x1000, 0x100, &es, 0);
452- for i in 0..40u64 {
453- m.pes(
454- 0x102,
455- 0xBD,
456- Some(90_000 + i * 1000),
457- None,
458- &[0x16, 0, 3, 1, 2, 3],
459- true,
460- false,
461- );
462- m.pes(
463- 0x100,
464- 0xE0,
465- Some(90_000 + i * 3600),
466- None,
467- &[0, 0, 1, 0xB3, 1, 2, 3, 4],
468- false,
469- false,
470- );
471- if i % 5 == 0 {
472- m.tables(0x1000, 0x100, &es, 0);
473- }
474- }
475- let mut d = TsDemuxer::new(Cursor::new(m.out)).unwrap();
476- let tracks = d.tracks();
477- assert_eq!(tracks.len(), 6);
478- assert_eq!(tracks[0].kind, StreamKind::Mpeg2Video);
479- assert!(
480- tracks[0].refusal.is_none(),
481- "MPEG-2 video is exposed, not refused"
482- );
483- assert_eq!(tracks[0].stream, None, "no parseable sequence header yet");
484- assert!(tracks[1].refusal.as_ref().unwrap().contains("aac_latm"));
485- assert_eq!(tracks[2].stream, Some(0));
486- assert_eq!(tracks[3].kind, StreamKind::Ac3);
487- assert_eq!(
488- tracks[3].stream, None,
489- "no AC-3 frames were seen, so it cannot be described yet"
490- );
491- assert_eq!(tracks[4].kind, StreamKind::DvbSub);
492- assert!(tracks[4].refusal.is_none(), "DVB subtitles are exposed");
493- assert_eq!(tracks[5].kind, StreamKind::TrueHd);
494- assert!(
495- tracks[5].refusal.is_none(),
496- "TrueHD is exposed, not refused"
497- );
498- assert_eq!(tracks[5].stream, None, "no TrueHD access unit was seen yet");
499- assert_eq!(d.streams().len(), 2);
500- assert_eq!(d.streams()[0].params.codec, CodecId::Pgs);
501- assert_eq!(d.streams()[1].params.codec, CodecId::DvbSub);
502- let mut n = 0;
503- while let Ok(p) = d.next_packet() {
504- if p.stream != 0 {
505- continue;
506- }
507- assert_eq!(&p.data[..], &[0x16, 0, 3, 1, 2, 3]);
508- assert!(p.flags.keyframe);
509- n += 1;
510- }
511- assert_eq!(n, 40);
512-}
513-
514-#[test]
515-fn pmt_change_appends_streams_and_keeps_indices() {
516- let a = tiny("tiny_h264_aac.ts");
517- let b = tiny("tiny_h264_eac3.ts");
518- let mut both = a.clone();
519- both.extend_from_slice(&b);
520- let mut d = TsDemuxer::new(Cursor::new(both)).unwrap();
521- assert_eq!(d.streams().len(), 2);
522- let mut counts = HashMap::new();
523- while let Ok(p) = d.next_packet() {
524- *counts.entry(p.stream).or_insert(0) += 1;
525- }
526- assert_eq!(d.stats().pmt_changes, 1);
527- assert_eq!(d.streams().len(), 3);
528- assert_eq!(d.streams()[2].params.codec, CodecId::EAc3);
529- assert_eq!(d.streams()[1].params.codec, CodecId::Aac);
530- let alone = |bytes: Vec<u8>| {
531- let mut d = TsDemuxer::new(Cursor::new(bytes)).unwrap();
532- let mut c = [0usize; 2];
533- while let Ok(p) = d.next_packet() {
534- c[p.stream as usize] += 1;
535- }
536- c
537- };
538- let (ca, cb) = (alone(a), alone(b));
539- assert_eq!(counts[&0], ca[0] + cb[0]);
540- assert_eq!(counts[&1], ca[1]);
541- assert_eq!(counts[&2], cb[1]);
542- let tracks = d.tracks();
543- assert_eq!(tracks.iter().filter(|t| t.stream.is_some()).count(), 3);
544- assert!(tracks[1].pid == tracks[2].pid);
545-}
546-
547-#[test]
548-fn length_prefixed_video_and_config_records() {
549- let mut d = TsDemuxer::new(Cursor::new(tiny("tiny_h264_aac.ts"))).unwrap();
550- d.set_video_framing(ec_mpegts::VideoFraming::LengthPrefixed);
551- let avcc = d.streams()[0].params.extradata.clone().unwrap();
552- assert_eq!(avcc[0], 1);
553- assert_eq!(avcc[4] & 3, 3, "4-byte lengths");
554- let p = d.next_packet().unwrap();
555- let n = u32::from_be_bytes(p.data[..4].try_into().unwrap()) as usize;
556- assert!(n + 4 <= p.data.len());
557- // The same access unit, re-framed from the Annex-B one, round-trips.
558- let mut d2 = TsDemuxer::new(Cursor::new(tiny("tiny_h264_aac.ts"))).unwrap();
559- let q = d2.next_packet().unwrap();
560- assert_eq!(
561- ec_mpegts::annexb_to_length_prefixed(&q.data, 4),
562- p.data.to_vec()
563- );
564- // The hvcC of the HEVC fixture.
565- let h = TsDemuxer::new(Cursor::new(tiny("tiny_hevc_aac.ts"))).unwrap();
566- let hvcc = h.streams()[0].params.extradata.clone().unwrap();
567- assert_eq!(hvcc[0], 1);
568- assert_eq!(hvcc[21] & 3, 3);
569- assert!(hvcc[22] >= 3, "VPS, SPS and PPS arrays");
570- let _ = BufReader::new(File::open("/dev/null").unwrap());
571 }328 }