Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

Merge origin/main into #1433; NAL streams keep their chunks (#1440 locates access units inside a PES)

Brandon Thomasfccddb6ea82d
diff --cc crates/mpegts/src/es.rs
index e53bde6ec,0b96e1481..9735d456e
--- a/crates/mpegts/src/es.rs
+++ b/crates/mpegts/src/es.rs
@@@ -406,11 -381,7 +405,12 @@@ impl Splitter
if data.is_empty() {
return;
}
- self.chunks.push_back((pos, self.es_pos));
+ // PES-delimited modes resolve a unit's position from `pos` right here and never look a
- // chunk up again, so remembering chunks there would only grow without bound
- if matches!(self.mode, Mode::MpegVideo | Mode::Audio(_)) {
++ // chunk up again, so remembering chunks there would only grow without bound (NAL streams
++ // keep theirs: an access unit can start inside a PES; `keep_from` prunes them)
++ if matches!(self.mode, Mode::MpegVideo | Mode::Audio(_) | Mode::Nal { .. }) {
+ self.chunks.push_back((pos, self.es_pos));
+ }
if let Some(o) = self.open.as_mut()
&& o.pos == u64::MAX
&& o.start == self.es_pos
@@@ -728,61 -699,4 +728,61 @@@ mod tests
// AC-3 frames are never joined
assert!(!eac3_joins_unit(&[0x0B, 0x77, 0x40, 0, 0, 8 << 3]));
}
+
+ #[test]
+ fn ac3_header_prefix_of_six_bytes_is_not_indexed_out_of_bounds() {
+ // exactly the six bytes frame_len() guarantees: byte 6 (acmod) is missing
+ assert_eq!(frame_info(&Codec::Ac3, &[0x0B, 0x77, 0, 0, 0x1E, 0x40]), None);
+ assert_eq!(frame_info(&Codec::Ac3, &[0x0B, 0x77, 0, 0, 0x1E, 0x40, 0]), None);
+ }
+
+ #[test]
+ fn eac3_reserved_sample_rate_is_refused() {
+ // fscod 3 and fscod2 3: no sample rate
+ let mut f = vec![0x0B, 0x77, 0, 7, 0xF0, 16 << 3];
+ f.resize(16, 0);
+ assert_eq!(frame_info(&Codec::Eac3, &f), None);
+ f[4] = 0xE0; // fscod2 2: 16 kHz
+ assert_eq!(frame_info(&Codec::Eac3, &f).map(|i| i.sample_rate), Some(16_000));
+ }
+
+ #[test]
+ fn four_byte_eac3_frames_make_no_units() {
+ let es: Vec<u8> = [0x0B, 0x77, 0x00, 0x01].repeat(10_000);
+ let mut s = Splitter::new(&Codec::Eac3);
+ s.feed(0, &es);
+ s.finish();
+ assert!(s.units.is_empty(), "{} units from 40000 noise bytes", s.units.len());
+ }
+
+ #[test]
+ fn pes_delimited_modes_do_not_retain_chunks() {
- for codec in [Codec::LpcmBluray, Codec::H264, Codec::Unknown(0x99)] {
++ for codec in [Codec::LpcmBluray, Codec::Unknown(0x99)] {
+ let mut s = Splitter::new(&codec);
+ for k in 0..5000u64 {
+ s.pes_start(Some(k as i64), None);
+ s.feed(k * 188, &[0x11; 184]);
+ }
+ s.finish();
+ assert!(s.chunks.len() <= 2, "{codec:?}: {} chunks retained", s.chunks.len());
+ assert_eq!(s.units.len(), 5000, "{codec:?}");
+ assert!(s.units.iter().enumerate().all(|(k, u)| u.pos == k as u64 * 188 && u.offset == 0), "{codec:?}");
+ }
+ }
+
+ #[test]
+ fn unit_table_is_capped() {
+ let frame = |k: u8| {
+ let mut v = vec![0x0B, 0x77, 0, 7, (3 << 4) | (2 << 1), 16 << 3];
+ v.resize(16, k);
+ v
+ };
+ let mut s = Splitter::new(&Codec::Eac3);
+ s.max_units = 10;
+ let es: Vec<u8> = (0..100).flat_map(frame).collect();
+ s.feed(0, &es);
+ s.finish();
+ assert_eq!(s.units.len(), 10);
+ assert!(s.truncated);
+ }
}
diff --cc crates/mpegts/src/tests.rs
index 9f4c29146,5e34bcf63..5cf89db3a
--- a/crates/mpegts/src/tests.rs
+++ b/crates/mpegts/src/tests.rs
@@@ -287,74 -331,98 +331,170 @@@ fn timestamps_unwrap_across_the_33_bit_
assert_eq!(u.unwrap(4200), (1 << 33) + 4200);
}
+fn adts_frame(k: u8) -> Vec<u8> {
+ let mut v = vec![0xFF, 0xF1, 0x50, 0x80, 0x0C, 0x9F, 0xFC];
+ v.extend([k; 93]);
+ v
+}
+
+#[test]
+fn non_pes_payload_is_dropped_until_the_next_unit_start() {
+ // a unit start whose payload is not a PES header, then continuation packets that happen to
+ // hold ADTS frames: nothing of it may become a unit
+ let mut mux = TsMux::new(false);
+ mux.psi(&[(0x0F, 0x1100)]);
+ mux.packet(0x1100, true, &[0x55; 184]);
+ for k in 0..10 {
+ mux.packet(0x1100, false, &adts_frame(k));
+ }
+ let f = open(&mux.out).unwrap();
+ assert_eq!(f.streams.first().map(|s| s.units.len()), Some(0));
+ // a real PES packet afterwards is indexed again
+ let mut mux2 = TsMux::new(false);
+ mux2.psi(&[(0x0F, 0x1100)]);
+ mux2.packet(0x1100, true, &[0x55; 184]);
+ mux2.packet(0x1100, false, &adts_frame(1));
+ mux2.pes(0x1100, &pes(0xC0, Some(9000), None, &adts_frame(2), true));
+ let f = open(&mux2.out).unwrap();
+ let u = &f.streams[0].units;
+ assert_eq!(u.len(), 1);
+ assert_eq!(u[0].pts, Some(9000));
+}
+
+#[test]
+fn adaptation_field_only_unit_start_keeps_the_pes_in_progress() {
+ let mut mux = TsMux::new(false);
+ mux.psi(&[(0x03, 0x1100)]);
+ let data = pes(0xC0, Some(9000), None, &[mp2_frame(0), mp2_frame(1)].concat(), true);
+ mux.packet(0x1100, true, &data[..184]);
+ // PUSI set, adaptation field only (no payload)
+ let cc = mux.cc.get(&0x1100).copied().unwrap_or(0);
+ let mut af = vec![0x47, 0x40 | 0x11, 0x00, 0x20 | cc, 183, 0x00];
+ af.resize(188, 0xFF);
+ mux.out.extend(af);
+ for chunk in data[184..].chunks(184) {
+ mux.packet(0x1100, false, chunk);
+ }
+ let f = open(&mux.out).unwrap();
+ let s = &f.streams[0];
+ assert_eq!(s.units.len(), 2);
+ assert_eq!(s.units[0].pts, Some(9000));
+ assert_eq!(f.read_unit(&mux.out, 0, 1).unwrap(), mp2_frame(1));
+}
+
+#[test]
+fn oversized_unit_is_refused_without_reserving_it() {
+ let f = File {
+ format: Format::Ts { packet_size: 188, sync_offset: 0 },
+ streams: vec![Stream {
+ id: StreamId::Pid(0x100),
+ stream_type: 0x1B,
+ codec: Codec::H264,
+ language: None,
+ units: vec![Unit { pts: None, dts: None, key: true, disposable: false, size: u32::MAX, pos: 0, offset: 0, picture: None }],
+ lpcm: None,
+ pes_packets: 0,
+ skipped_bytes: 0,
+ }],
+ program: None,
+ pcr_range: None,
+ warnings: Vec::new(),
+ };
+ assert!(matches!(f.read_unit(&Vec::<u8>::new(), 0, 0), Err(Error::Invalid(_))));
+}
++
+ /// A `ByteSource` that counts the bytes requested through `read_at`.
+ struct Counting<'a> {
+ data: &'a [u8],
+ read: std::cell::Cell<u64>,
+ }
+
+ impl ByteSource for Counting<'_> {
+ fn len(&self) -> u64 {
+ self.data.len() as u64
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
+ self.read.set(self.read.get() + buf.len() as u64);
+ self.data.read_at(offset, buf)
+ }
+ }
+
+ #[test]
+ fn bad_adaptation_fields_do_not_amplify_reads() {
+ // aligned packets whose adaptation_field_length (255) overruns the packet: the packet grid is
+ // intact, so this must cost one pass over the file, not one block read per packet
+ let mut data = Vec::new();
+ for _ in 0..3000 {
+ data.extend([0x47, 0x11, 0x00, 0x30]);
+ data.extend(std::iter::repeat_n(0xFF, 184));
+ }
+ let src = Counting { data: &data, read: Default::default() };
+ let f = open(&src).unwrap();
+ assert!(f.warnings.iter().any(|w| w.contains("adaptation field")), "{:?}", f.warnings);
+ assert!(!f.warnings.iter().any(|w| w.contains("lost packet sync")), "{:?}", f.warnings);
+ let read = src.read.get();
+ assert!(read <= 4 * data.len() as u64, "read {read} bytes of a {}-byte file", data.len());
+ }
+
+ #[test]
+ fn garbage_without_sync_does_not_amplify_reads() {
+ // a sync byte every 189 bytes: five-in-a-row never lines up, every 0x47 is a false candidate
+ let mut data = Vec::new();
+ for _ in 0..3000 {
+ data.extend([0x47]);
+ data.extend(std::iter::repeat_n(0x11, 188));
+ }
+ let head: Vec<u8> = (0..188 * 8).map(|i| if i % 188 == 0 { 0x47 } else { 0 }).collect();
+ let mut all = head;
+ all.extend(data);
+ let src = Counting { data: &all, read: Default::default() };
+ let f = open(&src).unwrap();
+ assert!(f.warnings.iter().any(|w| w.contains("lost packet sync")), "{:?}", f.warnings);
+ let read = src.read.get();
+ assert!(read <= 4 * all.len() as u64, "read {read} bytes of a {}-byte file", all.len());
+ }
+
+ #[test]
+ fn transport_stream_resyncs_after_garbage() {
+ const BLOCK_PACKETS: usize = 4096;
+ for m2ts in [false, true] {
+ let ps = if m2ts { 192 } else { 188 };
+ // garbage in front of the stream (shorter than 8 packets) and, at a few places around the
+ // first block boundary, between two frames; lengths that are not a multiple of the packet
+ for (delta, glen) in [(0usize, 100usize), (1, 37), (2, 188), (3, 301), (5, 5), (8, 1000)] {
+ let edge = (BLOCK_PACKETS - delta) * ps;
+ let mut mux = TsMux::new(m2ts);
+ mux.out.extend([0x11, 0x47, 0x22]); // garbage prefix with a lone 0x47
+ mux.psi(&[(0x02, 0x1011)]);
+ let mut expect = Vec::new();
+ let mut placed = false;
+ let mut k = 0usize;
+ while k < 3000 || !placed {
+ if !placed && mux.out.len() >= edge {
+ // garbage between two PES packets, with lone sync bytes inside
+ let mut g: Vec<u8> = (0..glen).map(|i| 0x10 + (i % 7) as u8).collect();
+ if let Some(b) = g.get_mut(3) {
+ *b = 0x47;
+ }
+ mux.out.extend(g);
+ placed = true;
+ }
+ let f = mpeg2_frame(if k == 0 { 1 } else { 2 }, (k % 1000) as u16, false, 40 + k % 300);
+ mux.pes(0x1011, &pes(0xE0, Some(90_000 + 3600 * k as i64), None, &f, false));
+ expect.push(f);
+ k += 1;
+ }
+ assert!(mux.out.len() > (BLOCK_PACKETS + 4) * ps, "stream must cross a block boundary");
+ let data = mux.out;
+ let f = open(&data).unwrap();
+ assert!(f.warnings.iter().any(|w| w.contains("lost packet sync")), "{:?}", f.warnings);
+ let v = f.find(Kind::Video, |_| true).unwrap();
+ let s = &f.streams[v];
+ assert_eq!(s.units.len(), expect.len(), "m2ts {m2ts} delta {delta} glen {glen}");
+ for (i, fr) in expect.iter().enumerate() {
+ assert_eq!(&f.read_unit(&data, v, i).unwrap(), fr, "unit {i} (m2ts {m2ts} delta {delta} glen {glen})");
+ assert_eq!(s.units[i].pts, Some(90_000 + 3600 * i as i64));
+ }
+ }
+ }
+ }