diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 929aa9a24..612c3e035 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-media" -description = "Bit-level I/O, clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) and MXF demuxers and muxers, and Ogg, AVI and MPEG-TS/PS demuxers." +description = "Bit-level I/O, clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) and MXF demuxers and muxers, an MPEG-TS/PS demuxer and MPEG-TS muxer, and Ogg and AVI demuxers." version.workspace = true edition.workspace = true license.workspace = true @@ -22,7 +22,8 @@ matroska = [] avi = [] # MXF demuxer and writer (`craft_media::mxf`); the writer formats dates with chrono. mxf = ["dep:chrono"] -# MPEG-2 Systems demuxer: transport streams and program streams (`craft_media::mpegts`). +# MPEG-2 Systems demuxer: transport streams and program streams (`craft_media::mpegts`), and the +# transport stream writer (`craft_media::mpegts::mux`). mpegts = [] # Sierra VMD (Video and Music Data) demuxer (`craft_media::vmd`). vmd = [] @@ -69,6 +70,14 @@ required-features = ["matroska"] name = "oracle_mpegts" required-features = ["mpegts"] +[[test]] +name = "mpegts_mux_fuzz" +required-features = ["mpegts"] + +[[test]] +name = "mpegts_mux_readback" +required-features = ["mpegts"] + [[test]] name = "oracle_mux" required-features = ["isobmff"] diff --git a/crates/media/README.md b/crates/media/README.md index 16ad74434..a90b55993 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -1,8 +1,9 @@ # craft-media Media containers and bit-level I/O for the Craft apps: an MSB-first bit reader and writer, -clean-room ISO BMFF (MP4), QuickTime (MOV), Matroska (MKV, WebM), MXF and AVI demuxers and muxers, and -Ogg, MPEG-2 Systems (transport and program stream) and Sierra VMD demuxers, written from the public specifications. No `unsafe`, no panics on malformed +clean-room ISO BMFF (MP4), QuickTime (MOV), Matroska (MKV, WebM), MXF and AVI demuxers and muxers, +an MPEG-2 Systems (transport and program stream) demuxer and transport stream muxer, and Ogg and +Sierra VMD demuxers, written from the public specifications. No `unsafe`, no panics on malformed input, builds for `wasm32-unknown-unknown`. Dependencies: `thiserror` (for `isobmff`), `chrono` (for `mxf`), `serde` (optional). @@ -549,7 +550,8 @@ FourCC, size, frame rate, packet count, audio format and duration. A clean-room MPEG-2 Systems demuxer from FilmCraft's `filmcraft-mpegts` (storytold/filmcraft@4bec22b): transport streams (188-byte, 192-byte BDAV / M2TS, 204-byte) and program streams (MPEG-1/2 PS, VOB, MOD). No GPL/LGPL code (FFmpeg, libavformat) was consulted; -FFmpeg is a fixture generator and test oracle only. No muxer, no decoding. +FFmpeg is a fixture generator and test oracle only. No decoding. The transport stream writer is +`mpegts::mux` ([below](#transport-stream-writer)). ```rust use craft_media::mpegts::{Kind, open}; @@ -637,6 +639,116 @@ helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares ten ffmpeg-made fi and HEVC video; MP2, ADTS and LATM AAC, AC-3, E-AC-3, Blu-ray and DVD LPCM; TS, M2TS, VOB and MPEG-1 system streams) with ffprobe's packets: unit counts, sizes, timestamps and key flags. +### Transport stream writer + +`mpegts::mux::Muxer` writes one program to any `std::io::Write` as frames arrive, so the same code +writes `.ts` files, HLS segments and SRT payloads. Its `Codec`, `Stream` and `Error` types are its +own, separate from the demuxer's. + +```rust +use craft_media::mpegts::mux::{Codec, Config, Frame, Muxer, Stream}; + +let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)]; +let mut ts = Muxer::new(Vec::new(), Config::default(), &streams)?; +let idr = [0, 0, 0, 1, 0x65, 0x88, 0x84]; +ts.write_frame(0, &Frame { data: &idr, pts: 90_000, dts: None, key: true })?; +let bytes = ts.finish()?; +assert_eq!(bytes.len() % 188, 0); +``` + +- A program association section and a program map section, each ending with its CRC-32. They are + written at the start, every `Config::psi_interval`, before every video keyframe when + `Config::psi_before_keyframes` is set, and before the first frame after `Muxer::replace_writer` + or `Muxer::discontinuity`. +- One PES packet per frame, with PTS and, when it differs from the PTS, DTS: + + | `Codec` | stream_type | stream_id | Frames passed in | + |---|---|---|---| + | `H264` | 0x1B | 0xE0 | Annex B access units; an access unit delimiter is added when missing | + | `Hevc` | 0x24 | 0xE0 | Annex B access units; an access unit delimiter is added when missing | + | `Mpeg2Video` | 0x02 | 0xE0 | MPEG-2 pictures from their first start code | + | `Mpeg1Video` | 0x01 | 0xE0 | MPEG-1 pictures from their first start code | + | `Mpeg4Part2` | 0x10 | 0xE0 | MPEG-4 Part 2 visual frames from their first start code | + | `Av1(Av1Config)` | 0x06 | 0xBD | temporal units in the low overhead format (every OBU has `obu_size`) | + | `AacAdts` | 0x0F | 0xC0 | ADTS frames; their `frame_length` fields must tile the frame | + | `Aac { .. }` | 0x0F | 0xC0 | raw AAC frames; the writer adds the ADTS header | + | `Opus { channels }` | 0x06 | 0xBD | Opus access units, 1 to 8 channels; the writer adds the Opus control header | + | `OpusMapped(OpusMapping)` | 0x06 | 0xBD | Opus multistream access units with an explicit channel mapping | + | `Ac3` | 0x81 | 0xBD | AC-3 sync frames | + | `Eac3` | 0x87 | 0xBD | E-AC-3 sync frames (bsid 11 to 16) | + | `MpegAudio { low_sample_rate }` | 0x03 or 0x04 | 0xC0 | MPEG audio frames, layers I to III, whose version matches the stream type | + + `Codec::aac_from_asc` turns an AudioSpecificConfig into the `Aac` fields, and refuses one that + an ADTS header cannot carry (frameLengthFlag 1, for one). An `Opus { channels }` access unit is + one Opus packet for 1 or 2 channels. For 3 to 8 channels it holds the streams of mapping family 1 + in the order that table 4-3 of the Opus transport draft gives, and every stream but the last uses + the self-delimited framing of RFC 6716 Appendix B. `OpusMapped` takes any other layout. +- Descriptors in the program map section: a registration descriptor `AC-3` or `EAC3` on AC-3 and + E-AC-3 streams; a registration descriptor `Opus` and an extension descriptor (tag 0x7F, + extension tag 0x80) on Opus streams, whose channel_config_code is the channel count for + `Opus { channels }` and 0x81 with the mapping family, stream counts and channel mapping for + `OpusMapped`; a registration descriptor `AV01` and the AV1 video descriptor (tag 0x80) built + from `Av1Config` (`Av1Config::from_av1c` reads an AV1CodecConfigurationRecord); and an + ISO 639 language descriptor on any stream that has a language. +- For AV1, each OBU follows the start code 0x000001 with emulation prevention bytes, temporal + delimiters and padding OBUs that end with a zero byte are left out, and each PES packet holds + one temporal unit. A keyframe must carry a + sequence header, and tile list OBUs are refused. +- For Opus, `Muxer::write_frame_with_trim` writes the control header's start and end trims (each + at most 8 191 samples, `MAX_OPUS_TRIM`). A start trim is allowed only while every earlier frame + of the stream was trimmed whole, 65 535 samples in all. +- The PCR on `Config::pcr_pid`: one of the streams' PIDs, or a PID that carries only PCRs. PCRs + are never more than `Config::pcr_interval` apart (at most 100 ms, H.222.0 §2.7.2). The PCR is + the largest DTS so far minus `Config::pcr_delay`, 1 to 90 000 ticks (`MAX_PCR_DELAY`, the + one-second limit of §2.4.2.6). A live output calls `Muxer::advance` while no frames arrive; its + time is on the DTS scale, so the PCR it writes is that time minus `pcr_delay`. +- A continuity counter per PID, the random access indicator on keyframes, adaptation field + stuffing, and timestamps written modulo 2^33. `Muxer::discontinuity` starts a new time base: + the next packet of every stream PID and of the PCR PID sets the discontinuity_indicator + (§2.4.3.5), and timestamps may then go back. + +Packets go to the output in batches of `Config::batch_packets` (7 by default, 1 316 bytes, one UDP +datagram), each in one `write` call, and the rest of a batch at the end of every `write_frame` and +`advance` unless `Config::hold_packets` is set. The batch is allocated once, in `Muxer::new`. After +an `Error::Io` the output may hold part of a packet; `Stats::packets` counts only whole packets. +`Muxer::replace_writer` returns the old output in a `Segment` (packet and frame counts, first and +last PTS, whether it starts with a keyframe, any error from its last packets), and the new output +starts with the PAT, the PMT and a PCR. `Muxer::replace_writer_continuing` swaps the output +without adding them. + +Frames are checked before anything is written. A stream's DTS must not go back, a video stream's +DTS must increase, a DTS may not be after its PTS, and a frame may be at most `pcr_delay` behind +the largest DTS written so far (`Error::Timestamp`). Audio frames must fit in one PES packet, and +video frames are at most `MAX_VIDEO_FRAME` (`MAX_UNIT_BYTES`, counting the start codes and escape +bytes the writer adds; `Error::FrameTooLarge`). A program has 1 to 32 streams on PIDs 0x0010 to +0x1FFE (`Error::BadPid`, `Error::DuplicatePid`), and its program map section is at most 1 021 bytes +(`Error::PsiTooLarge`). A gap in the timeline longer than `MAX_PCR_FILL` PCR intervals gets one PCR +at its end and is counted in `Stats::pcr_gaps`. + +`Config::default()`: program 1 with its PMT on PID 0x1000, the PCR on the first video stream (or +the first stream) every 40 ms and 700 ms behind the DTS, the PAT and PMT every 100 ms and before +keyframes, and writes of 7 packets. + +Gaps: one program per stream; no null packets (no constant bit rate); not written: LPCM (H.222.0 +defines no LPCM stream type for transport streams), AAC in LATM, DTS, subtitles and teletext. The +demuxer reads Opus and AV1 streams as `Unknown(6)` and MPEG-4 Part 2 as `Unknown(0x10)`, one unit +per PES packet. + +Specifications: the ones above, and Opus Interactive Audio Codec Transport Multiplexing Standard, +draft TS V0.1.3 (2015-10), for the Opus control header and descriptors; RFC 6716 for Opus packet +durations and self-delimited framing; Carriage of AV1 in MPEG-2 TS (Alliance for Open Media +working draft) and the AV1 Bitstream & Decoding Process Specification for AV1; ISO/IEC 14496-3 +for the AudioSpecificConfig; ATSC A/52 for the AC-3 and E-AC-3 stream types and registration +descriptors. + +Tests: `tests/mpegts_mux_readback.rs` reads the output back with the demuxer: streams, codecs, +languages, every frame's bytes, PTS and DTS, keyframes and the PCR range, with no continuity or +CRC warnings, including AV1 units, Opus with an explicit mapping and a start trim, both sides of a +discontinuity, and the output that follows an I/O error. `tests/mpegts_mux_fuzz.rs` muxes random +programs and timelines with idle gaps and output swaps and reads them back, and feeds random bytes +to every codec. Unit tests check every PES header's fixed bits, the sections' CRC, and that every +refused frame writes nothing. + ## `mxf` A clean-room MXF demuxer and writer from FilmCraft's `filmcraft-mxf` (storytold/filmcraft@4bec22b): diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 0c0d18211..a0e2d0c06 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -11,7 +11,7 @@ //! - `avi` (feature `avi`): a clean-room AVI (RIFF) and OpenDML demuxer. //! - `mxf` (feature `mxf`, enables `chrono`): a clean-room MXF demuxer and writer (OP1a, OP-Atom). //! - `mpegts` (feature `mpegts`): a clean-room MPEG-2 Systems demuxer (transport streams and -//! program streams). +//! program streams) and transport stream writer. //! - `vmd` (feature `vmd`): a clean-room Sierra VMD (Video and Music Data) demuxer. //! - [`Container`] and [`CodecId`] (no feature): the identifiers the codec crates report a file's //! container and codec with. diff --git a/crates/media/src/mpegts/mod.rs b/crates/media/src/mpegts/mod.rs index a0a62efa5..32356be02 100644 --- a/crates/media/src/mpegts/mod.rs +++ b/crates/media/src/mpegts/mod.rs @@ -15,6 +15,7 @@ //! reference and field structure. That index is the seeking table. //! - Units are read back on demand by re-reading the file from the unit's first packet, so the //! index costs a few dozen bytes per access unit. +//! - [`mux`] writes one program as a transport stream to any `io::Write`, frame by frame. //! //! The module does no decoding. No dependencies beyond `std`, no `unsafe`, builds for //! `wasm32-unknown-unknown`. @@ -26,6 +27,7 @@ mod es; pub use es::{FrameInfo, frame_bytes, frame_info, sei_has_recovery_point}; +pub mod mux; mod pes; mod ps; mod ts; diff --git a/crates/media/src/mpegts/mux/av1.rs b/crates/media/src/mpegts/mux/av1.rs new file mode 100644 index 000000000..22d0d7cd5 --- /dev/null +++ b/crates/media/src/mpegts/mux/av1.rs @@ -0,0 +1,232 @@ +//! AV1 in a transport stream (Carriage of AV1 in MPEG-2 TS, §3): each OBU after the start code +//! 0x000001, with emulation prevention so that 0x000000, 0x000001, 0x000002 and 0x000003 never +//! appear inside it. Temporal delimiters are left out, and so are padding OBUs that end with a +//! zero byte (an empty one included), which decoders ignore. + +use super::Error; + +const OBU_SEQUENCE_HEADER: u8 = 1; +const OBU_TEMPORAL_DELIMITER: u8 = 2; +const OBU_TILE_LIST: u8 = 8; +const OBU_PADDING: u8 = 15; + +struct Obu { + /// Bytes from the OBU header to the end of its payload. + len: usize, + kind: u8, +} + +/// The OBU at the start of `d`. +fn obu(d: &[u8]) -> Result { + let &h = d.first().ok_or(Error::BadFrame("an AV1 frame ends inside an OBU header"))?; + if h & 0x80 != 0 { + return Err(Error::BadFrame("an AV1 OBU has its forbidden bit set")); + } + if h & 0x02 == 0 { + return Err(Error::BadFrame("AV1 OBUs must carry obu_size (the low overhead bitstream format)")); + } + let mut at = 1 + usize::from(h & 0x04 != 0); + let mut size: u64 = 0; + for i in 0..8 { + let &b = d.get(at).ok_or(Error::BadFrame("an AV1 frame ends inside an OBU header"))?; + at += 1; + size |= u64::from(b & 0x7F) << (7 * i); + if b & 0x80 == 0 { + break; + } + if i == 7 { + return Err(Error::BadFrame("an AV1 obu_size is longer than eight bytes")); + } + } + let len = usize::try_from(size).ok().filter(|&s| s <= u32::MAX as usize).and_then(|s| at.checked_add(s)).filter(|&l| l <= d.len()); + let len = len.ok_or(Error::BadFrame("an AV1 OBU runs past the end of the frame"))?; + Ok(Obu { len, kind: (h >> 3) & 0x0F }) +} + +/// The OBU `bytes` (as `obu` found it) is not written: a temporal delimiter, or a padding OBU +/// that ends with a zero byte. +fn left_out(o: &Obu, bytes: &[u8]) -> bool { + o.kind == OBU_TEMPORAL_DELIMITER || (o.kind == OBU_PADDING && bytes.last() == Some(&0)) +} + +/// Emulation prevention bytes `bytes` needs after a start code. +fn escapes(bytes: &[u8]) -> usize { + let (mut n, mut zeros) = (0, 0u8); + for &b in bytes { + if zeros >= 2 && b <= 3 { + n += 1; + zeros = 0; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + } + n +} + +/// Checks a temporal unit and returns the bytes it takes in the PES packet: start codes, OBUs +/// and emulation prevention bytes. +pub(crate) fn check(data: &[u8], key: bool) -> Result { + let (mut at, mut body, mut seq, mut any) = (0, 0usize, false, false); + while at < data.len() { + let o = obu(&data[at..])?; + let bytes = &data[at..at + o.len]; + at += o.len; + if left_out(&o, bytes) { + continue; + } + match o.kind { + OBU_TILE_LIST => return Err(Error::BadFrame("tile list OBUs are not carried in a transport stream")), + OBU_SEQUENCE_HEADER => seq = true, + _ => {} + } + if bytes.last() == Some(&0) { + return Err(Error::BadFrame("an AV1 OBU ends with a zero byte, which the next start code would turn into a forbidden sequence")); + } + body = body.saturating_add(3 + bytes.len() + escapes(bytes)); + any = true; + } + if !any { + return Err(Error::BadFrame("the AV1 frame holds only temporal delimiters and padding")); + } + if key && !seq { + return Err(Error::BadFrame("an AV1 keyframe must carry a sequence header")); + } + Ok(body) +} + +/// Writes a checked temporal unit in start code form, a packet at a time. +pub(crate) struct Escaper<'a> { + data: &'a [u8], + at: usize, + /// End of the OBU being written. + end: usize, + /// Start code bytes still to write. + start_code: u8, + zeros: u8, +} + +impl<'a> Escaper<'a> { + pub(crate) fn new(data: &'a [u8]) -> Self { + Self { data, at: 0, end: 0, start_code: 0, zeros: 0 } + } + + /// Fills `out` as far as the temporal unit goes; returns the bytes written. + pub(crate) fn fill(&mut self, out: &mut [u8]) -> usize { + let mut n = 0; + while n < out.len() { + if self.start_code > 0 { + out[n] = u8::from(self.start_code == 1); + self.start_code -= 1; + n += 1; + } else if self.at < self.end { + let b = self.data[self.at]; + if self.zeros >= 2 && b <= 3 { + out[n] = 3; + self.zeros = 0; + } else { + out[n] = b; + self.at += 1; + self.zeros = if b == 0 { self.zeros + 1 } else { 0 }; + } + n += 1; + } else { + let rest = self.data.get(self.at..).unwrap_or(&[]); + let Ok(o) = obu(rest) else { break }; + if left_out(&o, &rest[..o.len]) { + self.at += o.len; + continue; + } + self.end = self.at + o.len; + self.start_code = 3; + self.zeros = 0; + } + } + n + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Removes start codes and emulation prevention bytes: the OBUs back. + fn unescape(es: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut zeros = 0; + let mut i = 0; + while i < es.len() { + if es[i..].starts_with(&[0, 0, 1]) { + i += 3; + zeros = 0; + continue; + } + let b = es[i]; + i += 1; + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + out.push(b); + } + out + } + + fn write(data: &[u8], chunk: usize) -> Vec { + let mut e = Escaper::new(data); + let mut out = Vec::new(); + loop { + let mut b = vec![0u8; chunk]; + let n = e.fill(&mut b); + out.extend_from_slice(&b[..n]); + if n < chunk { + return out; + } + } + } + + #[test] + fn obus_get_start_codes_and_escapes() { + // a temporal delimiter, a sequence header, a frame OBU whose payload holds every + // sequence that needs an escape + let tu = [0x12, 0x00, 0x0A, 0x03, 0x00, 0x00, 0x01, 0x32, 0x0A, 0, 0, 0, 0, 0, 1, 0, 0, 3, 0x7F]; + let body = check(&tu, true).unwrap(); + for chunk in [1, 2, 5, 184] { + let es = write(&tu, chunk); + assert_eq!(es.len(), body, "chunk {chunk}"); + assert!(es.starts_with(&[0, 0, 1, 0x0A, 0x03, 0x00, 0x00, 0x03, 0x01, 0, 0, 1, 0x32])); + for w in es[3..].windows(3) { + assert!(!(w[0] == 0 && w[1] == 0 && w[2] <= 2) || w == [0, 0, 1], "{es:02X?}"); + } + assert_eq!(unescape(&es), tu[2..].to_vec()); + } + } + + #[test] + fn padding_that_ends_with_a_zero_byte_is_left_out() { + // a sequence header, an empty padding OBU, a frame OBU, a padding OBU ending in 0x00, + // and a padding OBU that is written + let tu = [0x0A, 0x01, 0x05, 0x7A, 0x00, 0x32, 0x01, 0x07, 0x7A, 0x02, 0x09, 0x00, 0x7A, 0x01, 0x09]; + let body = check(&tu, true).unwrap(); + for chunk in [1, 2, 5, 184] { + let es = write(&tu, chunk); + assert_eq!(es.len(), body, "chunk {chunk}"); + assert_eq!(es, [0, 0, 1, 0x0A, 0x01, 0x05, 0, 0, 1, 0x32, 0x01, 0x07, 0, 0, 1, 0x7A, 0x01, 0x09], "chunk {chunk}"); + } + } + + #[test] + fn bad_temporal_units_are_refused() { + assert!(check(&[0x12, 0x00], false).is_err(), "only a temporal delimiter"); + assert!(check(&[0x32, 0x01, 0x05], true).is_err(), "a keyframe without a sequence header"); + assert!(check(&[0x32, 0x01, 0x05], false).is_ok()); + assert!(check(&[0x30, 0x05], false).is_err(), "no obu_size"); + assert!(check(&[0xB2, 0x01, 0x05], false).is_err(), "forbidden bit"); + assert!(check(&[0x32, 0x05, 0x05], false).is_err(), "past the end"); + assert!(check(&[0x32, 0x01, 0x00], false).is_err(), "ends with a zero byte"); + assert!(check(&[0x42, 0x01, 0x05], false).is_err(), "tile list"); + assert!(check(&[0x7A, 0x00], false).is_err(), "only empty padding"); + assert!(check(&[0x7A, 0x02, 0x05, 0x00], false).is_err(), "only padding that ends with a zero byte"); + assert!(check(&[0x32, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01], false).is_err(), "a nine-byte size"); + assert!(check(&[0x32, 0x80, 0x80, 0x80, 0x80, 0x10], false).is_err(), "over 2^32 - 1"); + } +} diff --git a/crates/media/src/mpegts/mux/mod.rs b/crates/media/src/mpegts/mux/mod.rs new file mode 100644 index 000000000..2bf808e17 --- /dev/null +++ b/crates/media/src/mpegts/mux/mod.rs @@ -0,0 +1,1192 @@ +//! MPEG-2 transport stream writer (ITU-T H.222.0 | ISO/IEC 13818-1). +//! +//! [`Muxer`] writes one program to any [`Write`] as frames arrive: +//! +//! - a program association section and a program map section, each ending with its CRC-32, at the +//! start, every [`Config::psi_interval`], before every video keyframe (optional), after +//! [`Muxer::replace_writer`] and after [`Muxer::discontinuity`]; +//! - one PES packet per frame for H.264, HEVC, MPEG-1, MPEG-2 and MPEG-4 Part 2 video, AV1, AAC in +//! ADTS frames (passed in, or built from raw AAC frames), Opus, AC-3, E-AC-3 and MPEG audio +//! (layers I to III), with PTS and, when it differs, DTS; +//! - the program clock reference on [`Config::pcr_pid`], in the adaptation field of the PCR +//! stream's frames or in packets of its own, never more than [`Config::pcr_interval`] apart +//! (at most 100 ms, §2.7.2); +//! - a continuity counter per PID, the random access indicator on keyframes, the discontinuity +//! indicator after [`Muxer::discontinuity`], and adaptation field stuffing in each frame's last +//! packet. +//! +//! Timestamps are 90 kHz ticks. They are written modulo 2^33, so a stream may run past the +//! wrap. The PCR follows the largest DTS so far minus [`Config::pcr_delay`]. +//! +//! # Arrival order +//! +//! Frames of different streams may arrive in any order, as long as each frame's DTS is no more +//! than [`Config::pcr_delay`] behind the largest DTS written so far (or the largest time given to +//! [`Muxer::advance`]). Within one stream the DTS never goes back, and for video it goes forward +//! with every frame. A caller whose encoders drift further apart than `pcr_delay` (at most +//! [`MAX_PCR_DELAY`], one second) queues frames and writes them in DTS order. +//! +//! # Output and failures +//! +//! Packets are built in a 188-byte buffer and collected in a batch of [`Config::batch_packets`] +//! packets, allocated once. A full batch is handed to the output in one `write` call, repeated +//! only when the output takes part of it; the default of 7 packets (1316 bytes) is one SRT or UDP +//! payload. Unless [`Config::hold_packets`] is set, the +//! rest of the batch is written at the end of every [`Muxer::write_frame`] and [`Muxer::advance`] +//! call, so a live output never waits for the next frame. A file output can set `hold_packets` +//! and a larger batch (for example 348 packets, 65 424 bytes) and then needs no `BufWriter`. +//! +//! The output must block until it has taken each write: an [`io::ErrorKind::WouldBlock`] error +//! is an I/O error like any other. After an I/O error the rest of that batch is dropped, the +//! output may hold part of a packet, and the continuity counters have moved on. +//! [`Stats::packets`] and [`Segment::packets`] count only the whole packets the output took. To +//! recover, give the muxer a new output with +//! [`Muxer::replace_writer`]: the new output starts at a packet boundary with the PAT, the PMT and +//! a PCR, and reads on its own. +//! +//! The names here ([`Codec`], [`Stream`], [`Error`]) are the writer's own and differ from the +//! demuxer's in [`crate::mpegts`]. + +mod av1; +mod pes; +mod psi; + +use std::fmt; +use std::io::{self, Write}; + +/// Bytes in a transport stream packet. +pub const PACKET_SIZE: usize = 188; +/// Timestamp ticks per second. +pub const TICKS_PER_SECOND: u32 = 90_000; +/// Largest PCR interval, 100 ms in 90 kHz ticks (H.222.0 §2.7.2). +pub const MAX_PCR_INTERVAL: u32 = 9_000; +/// Largest [`Config::pcr_delay`], one second in 90 kHz ticks: data may spend at most one second +/// in the decoder's buffers (H.222.0 §2.4.2.6). +pub const MAX_PCR_DELAY: u32 = 90_000; +/// Most elementary streams in one program. +pub const MAX_STREAMS: usize = 32; +/// Largest number of PCR-only packets, and of PAT and PMT repeats, written to fill one gap in the +/// timeline. A gap that needs more PCRs gets one PCR at its end and is counted in +/// [`Stats::pcr_gaps`]. +pub const MAX_PCR_FILL: u32 = 1024; +/// Largest video frame, [`super::MAX_UNIT_BYTES`] (128 MiB): the largest unit the demuxer +/// returns. +pub const MAX_VIDEO_FRAME: usize = super::MAX_UNIT_BYTES as usize; +/// Largest [`Config::batch_packets`]. +pub const MAX_BATCH_PACKETS: u16 = 1024; +/// Largest Opus start or end trim, in samples at 48 kHz (a 13-bit field). +pub const MAX_OPUS_TRIM: u16 = 8191; + +/// Errors from writing a transport stream. +#[non_exhaustive] +#[derive(Debug)] +pub enum Error { + /// Writing the output failed. + Io(io::Error), + /// The configuration or the stream list is not valid. + Config(String), + /// This PID is outside 0x0010 to 0x1FFE. + BadPid(u16), + /// This PID is used for two things. + DuplicatePid(u16), + /// The program map section would be longer than 1021 bytes. + PsiTooLarge { + /// The section_length it would have. + length: usize, + }, + /// [`Config::pcr_delay`] is outside 1 to [`MAX_PCR_DELAY`]. + PcrDelay(u32), + /// There is no stream with this index. + NoSuchStream(usize), + /// The frame has no bytes. + EmptyFrame, + /// The frame is not in the form its codec needs. + BadFrame(&'static str), + /// The frame is larger than its codec allows. + FrameTooLarge { + /// Bytes in the frame. + size: usize, + /// Most bytes the frame may have. + limit: usize, + }, + /// The frame's timestamps are not valid. + Timestamp(&'static str), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Io(e) => write!(f, "I/O: {e}"), + Error::Config(s) => write!(f, "transport stream settings: {s}"), + Error::BadPid(pid) => write!(f, "PID 0x{pid:04X} is outside 0x0010 to 0x1FFE"), + Error::DuplicatePid(pid) => write!(f, "PID 0x{pid:04X} is used twice"), + Error::PsiTooLarge { length } => write!(f, "the program map section would be {length} bytes long; the limit is 1021"), + Error::PcrDelay(d) => write!(f, "a PCR delay of {d} ticks is outside 1 to {MAX_PCR_DELAY}"), + Error::NoSuchStream(i) => write!(f, "no stream {i}"), + Error::EmptyFrame => write!(f, "the frame is empty"), + Error::BadFrame(s) => write!(f, "{s}"), + Error::FrameTooLarge { size, limit } => write!(f, "the frame is {size} bytes; the limit is {limit}"), + Error::Timestamp(s) => write!(f, "{s}"), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Io(e) => Some(e), + _ => None, + } + } +} + +impl From for Error { + fn from(e: io::Error) -> Self { + Error::Io(e) + } +} + +/// Result alias for the writer. +pub type Result = std::result::Result; + +/// The fields of the AV1 video descriptor (Carriage of AV1 in MPEG-2 TS, §2.2), taken from the +/// stream's sequence header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Av1Config { + /// seq_profile, 0 to 2. + pub seq_profile: u8, + /// seq_level_idx[0], 0 to 31. + pub seq_level_idx_0: u8, + /// seq_tier[0]. + pub seq_tier_0: bool, + /// high_bitdepth. + pub high_bitdepth: bool, + /// twelve_bit. + pub twelve_bit: bool, + /// mono_chrome. + pub monochrome: bool, + /// subsampling_x. + pub chroma_subsampling_x: bool, + /// subsampling_y. + pub chroma_subsampling_y: bool, + /// chroma_sample_position, 0 to 3. + pub chroma_sample_position: u8, + /// 0 SDR, 1 wide color gamut, 2 HDR and wide color gamut, 3 no indication. + pub hdr_wcg_idc: u8, +} + +impl Av1Config { + /// The fields from the first four bytes of an ISOBMFF `av1C` record (marker and version 1), + /// with `hdr_wcg_idc` 3 (no indication). + pub fn from_av1c(record: &[u8]) -> Result { + let &[b0, b1, b2, _, ..] = record else { return Err(Error::Config("an av1C record has at least four bytes".into())) }; + if b0 != 0x81 { + return Err(Error::Config("an av1C record has at least four bytes and starts with marker 1 and version 1".into())); + } + let c = Self { + seq_profile: b1 >> 5, + seq_level_idx_0: b1 & 0x1F, + seq_tier_0: b2 & 0x80 != 0, + high_bitdepth: b2 & 0x40 != 0, + twelve_bit: b2 & 0x20 != 0, + monochrome: b2 & 0x10 != 0, + chroma_subsampling_x: b2 & 0x08 != 0, + chroma_subsampling_y: b2 & 0x04 != 0, + chroma_sample_position: b2 & 3, + hdr_wcg_idc: 3, + }; + c.check().map_err(Error::Config)?; + Ok(c) + } + + fn check(&self) -> std::result::Result<(), String> { + if self.seq_profile > 2 { + return Err(format!("AV1 seq_profile {} is not 0 to 2", self.seq_profile)); + } + if self.seq_level_idx_0 > 31 || self.chroma_sample_position > 3 || self.hdr_wcg_idc > 3 { + return Err("an AV1 descriptor field is out of range".into()); + } + Ok(()) + } +} + +/// An Opus channel configuration coded in full (channel_config_code 0x81 of the Opus transport +/// draft): the channel mapping family, the stream counts and the channel mapping. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OpusMapping { + /// Output channels, 1 to 8. + pub channels: u8, + /// Channel mapping family (RFC 7845 §5.1.1): 0 for one mono or stereo stream, 1 for the + /// standard surround orders, 255 for an application-defined order. Other families are + /// refused. + pub family: u8, + /// Opus streams in each access unit, 1 to `channels` (1 for family 0). + pub streams: u8, + /// Streams that decode to two channels, at most `streams` (`channels - 1` for family 0). + pub coupled: u8, + /// For each output channel, the coded channel it is taken from (below `streams + coupled`), + /// or 255 for silence. Entries past `channels` are ignored. Family 0 carries no mapping in + /// the descriptor, so its entries must be 0 and 1. + pub mapping: [u8; 8], +} + +impl OpusMapping { + fn check(&self) -> std::result::Result<(), String> { + let ch = usize::from(self.channels); + if !(1..=8).contains(&ch) { + return Err(format!("{ch} Opus channels; 1 to 8 are supported")); + } + if self.family == 0 { + if ch > 2 || self.streams != 1 || u16::from(self.coupled) + 1 != u16::from(self.channels) { + return Err("Opus mapping family 0 is one stream of 1 or 2 channels".into()); + } + // the descriptor carries no mapping for family 0: the channels are in coded order + if self.mapping[..ch].iter().enumerate().any(|(i, &m)| usize::from(m) != i) { + return Err("Opus mapping family 0 keeps the channels in coded order (mapping 0, 1)".into()); + } + return Ok(()); + } + if !matches!(self.family, 1 | 255) { + return Err(format!("Opus mapping family {}; 0, 1 and 255 are supported", self.family)); + } + if self.streams == 0 || self.streams > self.channels || self.coupled > self.streams { + return Err("Opus streams are 1 to the channel count, and coupled streams at most the stream count".into()); + } + let coded = self.streams + self.coupled; + if self.mapping[..ch].iter().any(|&m| m >= coded && m != 255) { + return Err("an Opus channel mapping entry names a coded channel that does not exist".into()); + } + Ok(()) + } +} + +/// What an elementary stream carries, and the form its frames take. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Codec { + /// H.264 access units in Annex B form, with the parameter sets on keyframes. An access unit + /// delimiter is added when a frame does not start with one. + H264, + /// HEVC access units in Annex B form, with the parameter sets on keyframes. An access unit + /// delimiter is added when a frame does not start with one. + Hevc, + /// MPEG-1 video pictures (ISO/IEC 11172-2), from their first start code. + Mpeg1Video, + /// MPEG-2 video pictures, from their first start code. + Mpeg2Video, + /// MPEG-4 Part 2 visual frames (ISO/IEC 14496-2), from their first start code. + Mpeg4Part2, + /// AV1 temporal units in the low overhead bitstream format (every OBU with its size field), + /// with a sequence header on keyframes. Each OBU is written after a start code with emulation + /// prevention. Temporal delimiters, and padding OBUs that end with a zero byte, are left out + /// (Carriage of AV1 in MPEG-2 TS). + Av1(Av1Config), + /// AAC frames that already carry their ADTS headers; one call may pass several frames. + AacAdts, + /// Raw AAC frames; each one gets an ADTS header built from these fields. + Aac { + /// Audio object type, 1 to 4 (2 is AAC LC). + object_type: u8, + /// Sampling frequency index, 0 to 12 (3 is 48 kHz). + sample_rate_index: u8, + /// Channel configuration, 1 to 7. + channels: u8, + }, + /// Opus access units, one per frame; each gets an Opus control header. For 1 or 2 channels + /// the access unit is one Opus packet. For 3 to 8 channels it holds the streams of mapping + /// family 1 in the order the Opus transport draft's table 4-3 gives, all but the last + /// self-delimited; use [`Codec::OpusMapped`] for any other layout. + Opus { + /// Channel count, 1 to 8. + channels: u8, + }, + /// Opus access units with a channel configuration given in full. + OpusMapped(OpusMapping), + /// AC-3 sync frames. + Ac3, + /// E-AC-3 sync frames (bsid 11 to 16). + Eac3, + /// MPEG-1 or MPEG-2 audio frames, layers I to III (MP2, MP3). + MpegAudio { + /// The stream uses the MPEG-2 low sampling frequencies (16, 22.05 and 24 kHz) or the + /// lower MPEG 2.5 rates. Each frame's version bits must agree. + low_sample_rate: bool, + }, +} + +impl Codec { + /// The PMT stream_type. + pub fn stream_type(self) -> u8 { + match self { + Codec::H264 => 0x1B, + Codec::Hevc => 0x24, + Codec::Mpeg1Video => 0x01, + Codec::Mpeg2Video => 0x02, + Codec::Mpeg4Part2 => 0x10, + Codec::AacAdts | Codec::Aac { .. } => 0x0F, + Codec::Av1(_) | Codec::Opus { .. } | Codec::OpusMapped(_) => 0x06, + Codec::Ac3 => 0x81, + Codec::Eac3 => 0x87, + Codec::MpegAudio { low_sample_rate: false } => 0x03, + Codec::MpegAudio { low_sample_rate: true } => 0x04, + } + } + + /// The PES stream_id. + pub fn stream_id(self) -> u8 { + match self { + Codec::H264 | Codec::Hevc | Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::Mpeg4Part2 => 0xE0, + Codec::AacAdts | Codec::Aac { .. } | Codec::MpegAudio { .. } => 0xC0, + Codec::Av1(_) | Codec::Opus { .. } | Codec::OpusMapped(_) | Codec::Ac3 | Codec::Eac3 => 0xBD, + } + } + + /// The stream carries pictures. + pub fn is_video(self) -> bool { + matches!(self, Codec::H264 | Codec::Hevc | Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::Mpeg4Part2 | Codec::Av1(_)) + } + + fn is_opus(self) -> bool { + matches!(self, Codec::Opus { .. } | Codec::OpusMapped(_)) + } + + /// Raw AAC described by an AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1). Configurations + /// that an ADTS header cannot carry are refused: an object type outside 1 to 4 (SBR and PS + /// signaled explicitly included), an explicit sampling frequency, channel configuration 0, + /// and frameLengthFlag 1 (960-sample frames). + pub fn aac_from_asc(asc: &[u8]) -> Result { + let &[a, b, ..] = asc else { return Err(Error::Config("an AudioSpecificConfig has at least two bytes".into())) }; + let object_type = a >> 3; + let sample_rate_index = (a & 7) << 1 | b >> 7; + let channels = (b >> 3) & 0x0F; + let codec = Codec::Aac { object_type, sample_rate_index, channels }; + codec.check().map_err(Error::Config)?; + // GASpecificConfig's frameLengthFlag follows the channel configuration (ISO/IEC 14496-3 §4.4.1). + if b & 0x04 != 0 { + return Err(Error::Config("AAC frameLengthFlag 1 (960-sample frames) cannot be carried by an ADTS header".into())); + } + Ok(codec) + } + + fn check(self) -> std::result::Result<(), String> { + match self { + Codec::Aac { object_type, sample_rate_index, channels } => { + if !(1..=4).contains(&object_type) { + return Err(format!("AAC object type {object_type} is not 1 to 4")); + } + if sample_rate_index > 12 { + return Err(format!("AAC sampling frequency index {sample_rate_index} is not 0 to 12")); + } + if !(1..=7).contains(&channels) { + return Err(format!("AAC channel configuration {channels} is not 1 to 7")); + } + Ok(()) + } + Codec::Opus { channels } if !(1..=8).contains(&channels) => Err(format!("{channels} Opus channels; 1 to 8 are supported")), + Codec::OpusMapped(m) => m.check(), + Codec::Av1(c) => c.check(), + _ => Ok(()), + } + } +} + +/// One elementary stream of the program. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Stream { + /// The PID its packets carry, 0x0010 to 0x1FFE. + pub pid: u16, + /// What it carries. + pub codec: Codec, + /// ISO 639-2 language code (three lowercase letters), written as a language descriptor. + pub language: Option<[u8; 3]>, +} + +impl Stream { + /// A stream on `pid` without a language. + pub fn new(pid: u16, codec: Codec) -> Self { + Self { pid, codec, language: None } + } + + /// The same stream with a language code. + pub fn with_language(mut self, language: [u8; 3]) -> Self { + self.language = Some(language); + self + } +} + +/// Program, timing and output settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Config { + /// transport_stream_id in the program association section. + pub transport_stream_id: u16, + /// program_number, not 0. + pub program_number: u16, + /// The PID of the program map section, 0x0010 to 0x1FFE. + pub pmt_pid: u16, + /// The PID that carries the PCR: one of the streams' PIDs, or a PID of its own. + /// `None` uses the first video stream, or the first stream when there is no video. + pub pcr_pid: Option, + /// Largest gap between PCRs, 90 kHz ticks, 1 to [`MAX_PCR_INTERVAL`]. + pub pcr_interval: u32, + /// How far the PCR runs behind the largest DTS so far, 90 kHz ticks, 1 to + /// [`MAX_PCR_DELAY`]. It is also the largest skew between streams (see the crate docs). + pub pcr_delay: u32, + /// How often the PAT and PMT are repeated, 90 kHz ticks, at least 1. + pub psi_interval: u32, + /// Repeat the PAT and PMT before every video keyframe, so each keyframe starts a segment that + /// decodes on its own. + pub psi_before_keyframes: bool, + /// Packets collected before one write to the output, 1 to [`MAX_BATCH_PACKETS`]. + pub batch_packets: u16, + /// Keep a partly filled batch between calls instead of writing it at the end of each + /// [`Muxer::write_frame`] and [`Muxer::advance`]. For file outputs; [`Muxer::flush`], + /// [`Muxer::replace_writer`] and [`Muxer::finish`] still write it. + pub hold_packets: bool, +} + +impl Default for Config { + /// Program 1 with its PMT on PID 0x1000; the PCR at most 40 ms apart and 700 ms behind the + /// DTS; the PAT and PMT every 100 ms and before keyframes; writes of 7 packets, and the rest + /// at the end of every call. + fn default() -> Self { + Self { + transport_stream_id: 1, + program_number: 1, + pmt_pid: 0x1000, + pcr_pid: None, + pcr_interval: 3_600, + pcr_delay: 63_000, + psi_interval: 9_000, + psi_before_keyframes: true, + batch_packets: 7, + hold_packets: false, + } + } +} + +/// One frame to write. +#[derive(Clone, Copy, Debug)] +pub struct Frame<'a> { + /// The coded frame. + pub data: &'a [u8], + /// Presentation time, 90 kHz ticks. + pub pts: i64, + /// Decoding time, 90 kHz ticks; `None` when it equals `pts`. Never after `pts`, never before + /// the stream's previous DTS (for video, always after it), and never behind the clock: the + /// largest DTS so far, or the largest time given to [`Muxer::advance`], minus + /// [`Config::pcr_delay`]. + pub dts: Option, + /// Decoding can start at this frame (an IDR or other random access picture; any audio frame). + pub key: bool, +} + +/// Samples to discard from an Opus access unit, at 48 kHz (the Opus control header's start_trim +/// and end_trim). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OpusTrim { + /// Samples discarded from the start: the encoder's pre-skip, on the first access units of a + /// stream only, 65 535 in all. + pub start: u16, + /// Samples discarded from the end, on the last access unit. + pub end: u16, +} + +/// Counts of what has been written. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Stats { + /// Transport stream packets the outputs took whole. Packets still in the batch, and packets + /// dropped after an I/O error, are not counted. + pub packets: u64, + /// Frames. + pub frames: u64, + /// Times the PAT and PMT were written. + pub psi: u64, + /// PCRs, in frames' packets and in packets of their own. + pub pcrs: u64, + /// Gaps in the timeline longer than [`MAX_PCR_FILL`] PCR intervals. + pub pcr_gaps: u64, +} + +impl Stats { + /// Bytes written. + pub fn bytes(&self) -> u64 { + self.packets.saturating_mul(PACKET_SIZE as u64) + } +} + +/// What one output received, returned when [`Muxer::replace_writer`] or +/// [`Muxer::replace_writer_continuing`] closes it. An HLS packager reads the segment's duration +/// and independence from it. +#[derive(Debug)] +pub struct Segment { + /// The output. + pub writer: W, + /// Transport stream packets it took whole. After an error it may also hold part of a packet. + pub packets: u64, + /// Frames written to it. + pub frames: u64, + /// PTS of its first frame. + pub first_pts: Option, + /// Largest PTS of its frames. + pub last_pts: Option, + /// Its first video frame is a keyframe (with no video stream: it holds a frame), so it + /// decodes on its own when it also starts with the tables. + pub starts_with_keyframe: bool, + /// Writing the last packets to it, or flushing it, failed; those packets are lost. + pub error: Option, +} + +struct State { + pid: u16, + codec: Codec, + /// The counter the next packet with a payload carries. + cc: u8, + last_dts: Option, + /// The next packet carries the discontinuity indicator. + disc: bool, + /// Every Opus access unit so far was discarded whole by its start trim. + opus_lead_in: bool, + /// Opus samples discarded by start trims so far. + opus_start_trimmed: u32, +} + +impl State { + /// The counter an adaptation-field-only packet carries: the one before the next payload + /// packet's (§2.4.3.3), so the counter goes up by one at the next payload packet. + fn held_cc(&self) -> u8 { + self.cc.wrapping_sub(1) & 0x0F + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum PcrOn { + Stream(usize), + Own(u16), +} + +/// The output and the batch of packets waiting for it. +struct Sink { + out: W, + batch: Vec, + cap: usize, + /// Whole packets the output has taken. + packets: u64, + /// A mark that moves with every packet built and every batch dropped after an error, so + /// the muxer can tell whether given packets are still the last ones the output gets. + pushed: u64, +} + +impl Sink { + fn push(&mut self, p: &[u8; PACKET_SIZE]) -> io::Result<()> { + self.pushed += 1; + self.batch.extend_from_slice(p); + if self.batch.len() >= self.cap { self.drain() } else { Ok(()) } + } + + /// Writes the batch, counting the whole packets the output takes. On an error the rest of the + /// batch is dropped. + fn drain(&mut self) -> io::Result<()> { + let mut done = 0; + let mut r = Ok(()); + while done < self.batch.len() { + match self.out.write(&self.batch[done..]) { + Ok(0) => { + r = Err(io::Error::from(io::ErrorKind::WriteZero)); + break; + } + Ok(n) => done += n, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => { + r = Err(e); + break; + } + } + } + self.packets += (done / PACKET_SIZE) as u64; + if r.is_err() && done < self.batch.len() { + self.pushed += 1; + } + self.batch.clear(); + r + } +} + +/// What the current output has received. +#[derive(Default)] +struct SegState { + start_packets: u64, + frames: u64, + first_pts: Option, + last_pts: Option, + first_video_key: Option, +} + +/// The bytes of a frame after its PES header and prefix. +enum Payload<'a> { + Plain(&'a [u8]), + Av1(av1::Escaper<'a>), +} + +impl Payload<'_> { + /// Fills `out` as far as the payload goes; returns the bytes written. + fn fill(&mut self, out: &mut [u8]) -> usize { + match self { + Payload::Plain(d) => { + let n = d.len().min(out.len()); + out[..n].copy_from_slice(&d[..n]); + *d = &d[n..]; + n + } + Payload::Av1(e) => e.fill(out), + } + } +} + +/// Writes one program as a transport stream. +pub struct Muxer { + sink: Sink, + cfg: Config, + streams: Vec, + has_video: bool, + pat: Vec, + pmt: Vec, + pat_cc: u8, + pmt_cc: u8, + pcr_on: PcrOn, + /// The next PCR on a PID of its own carries the discontinuity indicator. + own_pcr_disc: bool, + /// The 27 MHz clock: the largest DTS so far minus the PCR delay. + clock: Option, + last_pcr: Option, + last_psi: Option, + /// [`Sink::pushed`] right after the last PAT and PMT; `None` once something else may follow + /// them. + psi_end: Option, + psi_forced: bool, + /// The next frame or advance writes a PCR whatever the interval (a new writer). + pcr_forced: bool, + stats: Stats, + seg: SegState, +} + +fn check_pid(pid: u16) -> Result<()> { + if (0x0010..=0x1FFE).contains(&pid) { Ok(()) } else { Err(Error::BadPid(pid)) } +} + +impl Muxer { + /// A muxer for `streams` writing to `out`. Nothing is written until the first frame or + /// [`Muxer::advance`]. + pub fn new(out: W, cfg: Config, streams: &[Stream]) -> Result { + if streams.is_empty() || streams.len() > MAX_STREAMS { + return Err(Error::Config(format!("{} streams; 1 to {MAX_STREAMS} are supported", streams.len()))); + } + if cfg.program_number == 0 { + return Err(Error::Config("program number 0 is reserved for the network PID".into())); + } + check_pid(cfg.pmt_pid)?; + if !(1..=MAX_PCR_INTERVAL).contains(&cfg.pcr_interval) { + return Err(Error::Config(format!("a PCR interval of {} ticks is outside 1 to {MAX_PCR_INTERVAL}", cfg.pcr_interval))); + } + if !(1..=MAX_PCR_DELAY).contains(&cfg.pcr_delay) { + return Err(Error::PcrDelay(cfg.pcr_delay)); + } + if cfg.psi_interval == 0 { + return Err(Error::Config("the PAT and PMT interval must be at least 1 tick".into())); + } + if !(1..=MAX_BATCH_PACKETS).contains(&cfg.batch_packets) { + return Err(Error::Config(format!("a batch of {} packets is outside 1 to {MAX_BATCH_PACKETS}", cfg.batch_packets))); + } + for (i, s) in streams.iter().enumerate() { + check_pid(s.pid)?; + if s.pid == cfg.pmt_pid || streams[..i].iter().any(|t| t.pid == s.pid) { + return Err(Error::DuplicatePid(s.pid)); + } + s.codec.check().map_err(Error::Config)?; + if let Some(l) = s.language + && !l.iter().all(u8::is_ascii_lowercase) + { + return Err(Error::Config("a language code is three lowercase letters".into())); + } + } + let pcr_on = match cfg.pcr_pid { + Some(pid) => { + check_pid(pid)?; + if pid == cfg.pmt_pid { + return Err(Error::DuplicatePid(pid)); + } + streams.iter().position(|s| s.pid == pid).map_or(PcrOn::Own(pid), PcrOn::Stream) + } + None => PcrOn::Stream(streams.iter().position(|s| s.codec.is_video()).unwrap_or(0)), + }; + let pcr_pid = match pcr_on { + PcrOn::Stream(i) => streams.get(i).map_or(0x1FFF, |s| s.pid), + PcrOn::Own(pid) => pid, + }; + let cap = usize::from(cfg.batch_packets) * PACKET_SIZE; + Ok(Self { + sink: Sink { out, batch: Vec::with_capacity(cap), cap, packets: 0, pushed: 0 }, + cfg, + streams: streams + .iter() + .map(|s| State { pid: s.pid, codec: s.codec, cc: 0, last_dts: None, disc: false, opus_lead_in: true, opus_start_trimmed: 0 }) + .collect(), + has_video: streams.iter().any(|s| s.codec.is_video()), + pat: psi::pat(cfg.transport_stream_id, cfg.program_number, cfg.pmt_pid)?, + pmt: psi::pmt(cfg.program_number, pcr_pid, streams)?, + pat_cc: 0, + pmt_cc: 0, + pcr_on, + own_pcr_disc: false, + clock: None, + last_pcr: None, + last_psi: None, + psi_end: None, + psi_forced: false, + pcr_forced: false, + stats: Stats::default(), + seg: SegState::default(), + }) + } + + /// The PID that carries the PCR. + pub fn pcr_pid(&self) -> u16 { + match self.pcr_on { + PcrOn::Stream(i) => self.streams.get(i).map_or(0x1FFF, |s| s.pid), + PcrOn::Own(pid) => pid, + } + } + + /// What has been written so far. + pub fn stats(&self) -> Stats { + Stats { packets: self.sink.packets, ..self.stats } + } + + /// The output. + pub fn get_ref(&self) -> &W { + &self.sink.out + } + + /// The output, for writing between packets. With [`Config::hold_packets`] set, call + /// [`Muxer::flush`] first so no held packet follows what is written here. + pub fn get_mut(&mut self) -> &mut W { + // what the caller writes may separate the last tables from the next keyframe + self.psi_end = None; + &mut self.sink.out + } + + /// Writes the held packets and flushes the output. + pub fn flush(&mut self) -> Result<()> { + self.sink.drain()?; + self.sink.out.flush()?; + Ok(()) + } + + /// Closes the current output for a new segment and sends the following packets to `out`. + /// The held packets go to the old output first, and it is flushed. The new output starts with + /// the PAT and PMT, and the next frame (or [`Muxer::advance`]) writes a PCR; continuity + /// counters and the clock carry on. To start every segment with a keyframe, call this right + /// before writing a video keyframe. + pub fn replace_writer(&mut self, out: W) -> Segment { + self.swap(out, true) + } + + /// Like [`Muxer::replace_writer`], but the packet flow is unchanged: no tables or PCR are + /// added, so the outputs joined end to end hold the same bytes as one output would. For the + /// parts of a low-latency HLS segment. + pub fn replace_writer_continuing(&mut self, out: W) -> Segment { + self.swap(out, false) + } + + fn swap(&mut self, out: W, restart: bool) -> Segment { + let error = self.sink.drain().err().or_else(|| self.sink.out.flush().err()); + if restart { + self.psi_forced = true; + self.pcr_forced = true; + } + let writer = std::mem::replace(&mut self.sink.out, out); + let seg = std::mem::replace(&mut self.seg, SegState { start_packets: self.sink.packets, ..SegState::default() }); + let starts_with_keyframe = if self.has_video { seg.first_video_key.unwrap_or(false) } else { seg.frames > 0 }; + Segment { + writer, + packets: self.sink.packets - seg.start_packets, + frames: seg.frames, + first_pts: seg.first_pts, + last_pts: seg.last_pts, + starts_with_keyframe, + error, + } + } + + /// Writes the PAT and PMT before the next frame. + pub fn repeat_psi(&mut self) { + self.psi_forced = true; + } + + /// Starts a new time base, for an encoder or source that restarts with timestamps that do not + /// follow the old ones. The clock and every stream's previous DTS are forgotten, the next + /// packet of every stream PID and of the PCR PID carries the discontinuity indicator + /// (§2.4.3.5), and the next frame or [`Muxer::advance`] writes the PAT, the PMT and a PCR of + /// the new time base first. Continuity counters carry on. An Opus stream may carry a start + /// trim again, as at its start. + pub fn discontinuity(&mut self) { + self.clock = None; + self.last_pcr = None; + self.last_psi = None; + self.psi_forced = true; + self.pcr_forced = true; + self.own_pcr_disc = matches!(self.pcr_on, PcrOn::Own(_)); + for s in &mut self.streams { + s.last_dts = None; + s.disc = true; + // a restarted Opus encoder starts with its own pre-skip + s.opus_lead_in = true; + s.opus_start_trimmed = 0; + } + } + + /// Writes the held packets, flushes and returns the output. A transport stream has no + /// trailer. + pub fn finish(mut self) -> Result { + self.flush()?; + Ok(self.sink.out) + } + + /// The 27 MHz clock value for a DTS. + fn time(&self, dts: i64) -> Result { + dts.checked_sub(i64::from(self.cfg.pcr_delay)).and_then(|v| v.checked_mul(300)).ok_or(Error::Timestamp("the timestamp is out of range")) + } + + /// Writes the batch unless the configuration holds packets between calls. + fn end_call(&mut self) -> Result<()> { + if !self.cfg.hold_packets { + self.sink.drain()?; + } + Ok(()) + } + + /// Moves the clock without a frame, writing the PCRs and the PAT and PMT that fall due. A + /// live output calls this while no frames arrive, so the PCR stays within its interval. + /// + /// `time` is on the DTS scale (90 kHz): the PCR sent is `time - pcr_delay`, the clock a + /// frame with DTS `time` would set. After `advance(t)`, frames whose DTS is below + /// `t - pcr_delay` are refused. A time behind the clock has no effect. + pub fn advance(&mut self, time: i64) -> Result<()> { + let r = self.advance_inner(time); + let end = self.end_call(); + r.and(end) + } + + fn advance_inner(&mut self, time: i64) -> Result<()> { + let t = self.time(time)?; + let clock = self.clock.map_or(t, |c| c.max(t)); + self.clock = Some(clock); + self.fill_pcr(clock)?; + self.psi_if_due(clock, false)?; + if self.pcr_due(clock) { + self.pcr_packet(clock)?; + } + Ok(()) + } + + /// A PCR packet is due: none yet, a new writer, or the interval has passed. + fn pcr_due(&self, clock: i64) -> bool { + self.pcr_forced || self.last_pcr.is_none_or(|l| clock.saturating_sub(l) >= self.limit()) + } + + /// Writes one frame of stream `index` (an index into the list given to [`Muxer::new`]). + /// The frame is checked before anything is written. + pub fn write_frame(&mut self, index: usize, frame: &Frame<'_>) -> Result<()> { + self.write_frame_with_trim(index, frame, OpusTrim::default()) + } + + /// Writes one Opus frame whose control header carries `trim`. A start trim is allowed only + /// while every earlier access unit of the stream (since the start or the last + /// [`Muxer::discontinuity`]) was discarded whole, and the trims of one + /// access unit cannot exceed its duration. A zero trim writes a plain frame, for any codec. + pub fn write_frame_with_trim(&mut self, index: usize, frame: &Frame<'_>, trim: OpusTrim) -> Result<()> { + let r = self.write_inner(index, frame, trim); + let end = self.end_call(); + r.and(end) + } + + fn write_inner(&mut self, index: usize, frame: &Frame<'_>, trim: OpusTrim) -> Result<()> { + let st = self.streams.get(index).ok_or(Error::NoSuchStream(index))?; + if frame.data.is_empty() { + return Err(Error::EmptyFrame); + } + let codec = st.codec; + let dts = frame.dts.unwrap_or(frame.pts); + if dts > frame.pts { + return Err(Error::Timestamp("the decoding time is after the presentation time")); + } + if let Some(l) = st.last_dts { + if dts < l { + return Err(Error::Timestamp("the decoding time is before the stream's previous one")); + } + if dts == l && codec.is_video() { + return Err(Error::Timestamp("a video frame's decoding time must be after the stream's previous one")); + } + } + let trimmed = trim != OpusTrim::default(); + let mut duration = 0; + if trimmed { + if !codec.is_opus() { + return Err(Error::BadFrame("only Opus frames carry trims")); + } + if trim.start > MAX_OPUS_TRIM || trim.end > MAX_OPUS_TRIM { + return Err(Error::BadFrame("an Opus trim is at most 8191 samples")); + } + if trim.start > 0 && (!st.opus_lead_in || st.opus_start_trimmed + u32::from(trim.start) > 0xFFFF) { + return Err(Error::BadFrame("a start trim is allowed only at the start of an Opus stream, 65 535 samples in all")); + } + duration = pes::opus_samples(frame.data).ok_or(Error::BadFrame("the Opus packet's table of contents is incomplete"))?; + if u32::from(trim.start) + u32::from(trim.end) > duration { + return Err(Error::BadFrame("the trim is longer than the Opus access unit")); + } + } + let with_dts = dts != frame.pts; + let header_len = if with_dts { 19 } else { 14 }; + let trim_bytes = if trim.start > 0 { 2 } else { 0 } + if trim.end > 0 { 2 } else { 0 }; + let limit = pes::data_limit(codec, header_len - 6, trim_bytes); + if frame.data.len() > limit { + return Err(Error::FrameTooLarge { size: frame.data.len(), limit }); + } + let mut prefix = [0u8; pes::PREFIX_MAX]; + let prep = pes::prepare(codec, frame.data, frame.key, trim, &mut prefix)?; + // start codes, escapes and delimiters count toward the reader's limit too + let encoded = prep.prefix_len.saturating_add(prep.body_len); + if codec.is_video() && encoded > MAX_VIDEO_FRAME { + return Err(Error::FrameTooLarge { size: encoded, limit: MAX_VIDEO_FRAME }); + } + // bytes after PES_packet_length + let body = (header_len - 6) + prep.prefix_len + prep.body_len; + let length = match u16::try_from(body) { + Ok(n) => n, + Err(_) if codec.is_video() => 0, + Err(_) => return Err(Error::FrameTooLarge { size: frame.data.len(), limit }), + }; + let t = self.time(dts)?; + // the frame must arrive no later than it decodes: its DTS may not be behind the clock + // that PCRs already sent (the largest DTS so far minus the PCR delay, or an advance) + if dts.checked_mul(300).is_none_or(|d| self.clock.is_some_and(|c| d < c)) { + return Err(Error::Timestamp("the decoding time is behind the transport stream clock")); + } + let mut header = [0u8; pes::HEADER_MAX]; + pes::header(&mut header, codec.stream_id(), length, frame.pts, with_dts.then_some(dts)); + + let clock = self.clock.map_or(t, |c| c.max(t)); + self.clock = Some(clock); + self.fill_pcr(clock)?; + // a keyframe needs the tables right in front of it: not again when they are the last + // packets written, but again when PCRs filling a gap came after them + let tables_last = self.psi_end == Some(self.sink.pushed); + self.psi_if_due(clock, frame.key && codec.is_video() && !tables_last)?; + let mut pcr = None; + if self.pcr_on == PcrOn::Stream(index) { + if self.pcr_forced || self.last_pcr.is_none_or(|l| clock > l) { + pcr = Some(clock); + self.last_pcr = Some(clock); + self.pcr_forced = false; + self.stats.pcrs += 1; + } + } else if self.pcr_due(clock) { + self.pcr_packet(clock)?; + } + let payload = match codec { + Codec::Av1(_) => Payload::Av1(av1::Escaper::new(frame.data)), + _ => Payload::Plain(frame.data), + }; + self.pes_packets(index, &header[..header_len], &prefix[..prep.prefix_len], payload, prep.body_len, pcr, frame.key)?; + if let Some(st) = self.streams.get_mut(index) { + st.last_dts = Some(dts); + if codec.is_opus() { + st.opus_start_trimmed += u32::from(trim.start); + if !trimmed || u32::from(trim.start) < duration { + st.opus_lead_in = false; + } + } + } + self.stats.frames += 1; + let seg = &mut self.seg; + seg.frames += 1; + seg.first_pts.get_or_insert(frame.pts); + seg.last_pts = Some(seg.last_pts.map_or(frame.pts, |p| p.max(frame.pts))); + if codec.is_video() { + seg.first_video_key.get_or_insert(frame.key); + } + Ok(()) + } + + /// The PCR interval at 27 MHz. + fn limit(&self) -> i64 { + i64::from(self.cfg.pcr_interval) * 300 + } + + fn psi_if_due(&mut self, clock: i64, keyframe: bool) -> Result<()> { + let due = self.psi_forced + || self.last_psi.is_none_or(|l| clock.saturating_sub(l) >= i64::from(self.cfg.psi_interval) * 300) + || (keyframe && self.cfg.psi_before_keyframes); + if due { + section_packets(&mut self.sink, 0, &mut self.pat_cc, &self.pat)?; + section_packets(&mut self.sink, self.cfg.pmt_pid, &mut self.pmt_cc, &self.pmt)?; + self.last_psi = Some(clock); + self.psi_end = Some(self.sink.pushed); + self.psi_forced = false; + self.stats.psi += 1; + } + Ok(()) + } + + /// Fills the gap up to `clock`: PCR-only packets until the gap to `clock` is within the PCR + /// interval, and the PAT and PMT wherever they fall due before `clock`, in time order. A new + /// writer gets the PAT and PMT before anything else. + fn fill_pcr(&mut self, clock: i64) -> Result<()> { + let Some(last_pcr) = self.last_pcr else { return Ok(()) }; + if self.psi_forced { + self.psi_if_due(last_pcr, false)?; + } + let limit = self.limit(); + let psi = i64::from(self.cfg.psi_interval) * 300; + // each kind of packet is capped on its own, so a short PAT and PMT interval cannot use + // up the PCRs' share + let (mut pcrs, mut tables) = (0, 0); + loop { + let mut pcr_at = self.last_pcr.map(|l| l.saturating_add(limit)).filter(|&t| t < clock); + if pcrs >= MAX_PCR_FILL && pcr_at.is_some() { + if pcrs == MAX_PCR_FILL { + // counted once: the PCR at `clock` that follows closes the gap + self.stats.pcr_gaps += 1; + pcrs += 1; + } + pcr_at = None; + } + let psi_at = self.last_psi.map(|l| l.saturating_add(psi)).filter(|&t| t < clock && tables < MAX_PCR_FILL); + match (psi_at, pcr_at) { + (Some(s), Some(p)) if s <= p => { + self.psi_if_due(s, false)?; + tables += 1; + } + (Some(s), None) => { + self.psi_if_due(s, false)?; + tables += 1; + } + (_, Some(p)) => { + self.pcr_packet(p)?; + pcrs += 1; + } + (None, None) => return Ok(()), + } + } + } + + /// A packet on the PCR PID with only an adaptation field holding the PCR. + fn pcr_packet(&mut self, pcr: i64) -> Result<()> { + let (pid, cc, disc) = match self.pcr_on { + PcrOn::Stream(i) => match self.streams.get_mut(i) { + Some(s) => (s.pid, s.held_cc(), std::mem::take(&mut s.disc)), + None => (0x1FFF, 0, false), + }, + PcrOn::Own(pid) => (pid, 0, std::mem::take(&mut self.own_pcr_disc)), + }; + let mut b = [0xFF; PACKET_SIZE]; + b[..6].copy_from_slice(&[0x47, (pid >> 8) as u8 & 0x1F, pid as u8, 0x20 | cc, 183, 0x10 | if disc { 0x80 } else { 0 }]); + b[6..12].copy_from_slice(&pes::pcr(pcr)); + self.sink.push(&b)?; + self.stats.pcrs += 1; + self.last_pcr = Some(pcr); + self.pcr_forced = false; + Ok(()) + } + + /// Splits one PES packet (`header`, `prefix`, then `body_len` bytes of `payload`) into + /// transport packets. + #[allow(clippy::too_many_arguments)] + fn pes_packets( + &mut self, + index: usize, + header: &[u8], + prefix: &[u8], + mut payload: Payload<'_>, + body_len: usize, + pcr: Option, + key: bool, + ) -> Result<()> { + let Some(st) = self.streams.get_mut(index) else { return Err(Error::NoSuchStream(index)) }; + let pid = st.pid; + let mut parts = [header, prefix]; + let mut left = header.len() + prefix.len() + body_len; + let mut first = true; + while left > 0 { + let pcr_here = if first { pcr } else { None }; + let rai = first && key; + let disc = first && st.disc; + let fixed = if pcr_here.is_some() || rai || disc { 2 + if pcr_here.is_some() { 6 } else { 0 } } else { 0 }; + let take = left.min(184 - fixed); + // the adaptation field, its length byte included + let af = 184 - take; + let mut b = [0u8; PACKET_SIZE]; + b[0] = 0x47; + b[1] = if first { 0x40 } else { 0 } | (pid >> 8) as u8 & 0x1F; + b[2] = pid as u8; + b[3] = if af > 0 { 0x30 } else { 0x10 } | st.cc; + st.cc = (st.cc + 1) & 0x0F; + if af > 0 { + b[4] = (af - 1) as u8; + if af > 1 { + b[5] = if disc { 0x80 } else { 0 } | if rai { 0x40 } else { 0 } | if pcr_here.is_some() { 0x10 } else { 0 }; + let mut p = 6; + if let Some(v) = pcr_here { + b[6..12].copy_from_slice(&pes::pcr(v)); + p = 12; + } + b[p..4 + af].fill(0xFF); + } + } + if disc { + st.disc = false; + } + let mut at = 4 + af; + for part in &mut parts { + let n = part.len().min(PACKET_SIZE - at); + b[at..at + n].copy_from_slice(&part[..n]); + *part = &part[n..]; + at += n; + } + if at < PACKET_SIZE { + payload.fill(&mut b[at..]); + } + self.sink.push(&b)?; + left -= take; + first = false; + } + Ok(()) + } +} + +/// Writes a PSI section on `pid`: a pointer field of 0, the section, and 0xFF stuffing. +fn section_packets(sink: &mut Sink, pid: u16, cc: &mut u8, section: &[u8]) -> Result<()> { + let mut rest = section; + let mut first = true; + while first || !rest.is_empty() { + let mut b = [0xFF; PACKET_SIZE]; + b[0] = 0x47; + b[1] = if first { 0x40 } else { 0 } | (pid >> 8) as u8 & 0x1F; + b[2] = pid as u8; + b[3] = 0x10 | *cc; + *cc = (*cc + 1) & 0x0F; + let mut at = 4; + if first { + b[4] = 0; + at = 5; + } + let n = rest.len().min(PACKET_SIZE - at); + b[at..at + n].copy_from_slice(&rest[..n]); + rest = &rest[n..]; + sink.push(&b)?; + first = false; + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/media/src/mpegts/mux/pes.rs b/crates/media/src/mpegts/mux/pes.rs new file mode 100644 index 000000000..89127c627 --- /dev/null +++ b/crates/media/src/mpegts/mux/pes.rs @@ -0,0 +1,389 @@ +//! PES packet headers (H.222.0 §2.4.3.6), the adaptation field's PCR (§2.4.3.4), and the bytes +//! written ahead of a frame: access unit delimiters, ADTS headers and Opus control headers. + +use super::{Codec, Error, MAX_VIDEO_FRAME, OpusTrim, av1}; + +/// 2^33: PTS, DTS and the PCR base are 33-bit counters. +pub(crate) const WRAP_90K: i64 = 1 << 33; + +/// Largest PES header this writer produces: 9 bytes, PTS and DTS. +pub(crate) const HEADER_MAX: usize = 19; + +/// Largest prefix: an Opus control header for a 65 535-byte packet (2 bytes, 257 size bytes, a +/// start and an end trim). +pub(crate) const PREFIX_MAX: usize = 2 + 0xFFFF / 255 + 1 + 4; + +/// What [`prepare`] found: the prefix it wrote, and the bytes the frame takes after it. +pub(crate) struct Prepared { + pub(crate) prefix_len: usize, + pub(crate) body_len: usize, +} + +/// Most frame bytes `codec` allows when the PES header has `header` bytes after +/// PES_packet_length and an Opus control header carries `trim` trim bytes. +pub(crate) fn data_limit(codec: Codec, header: usize, trim: usize) -> usize { + let room = 0xFFFF - header; + match codec { + c if c.is_video() => MAX_VIDEO_FRAME, + // ADTS frame_length is 13 bits + Codec::Aac { .. } => (0x1FFF - 7).min(room - 7), + Codec::Opus { .. } | Codec::OpusMapped(_) => { + // the control header takes 3 bytes, a size byte per 255 bytes, and the trims + let budget = room - 3 - trim; + let mut l = budget * 255 / 256; + while l + 1 + (l + 1) / 255 <= budget { + l += 1; + } + while l + l / 255 > budget { + l -= 1; + } + l + } + _ => room, + } +} + +/// Samples per channel at 48 kHz in an Opus packet, from its table of contents (RFC 6716 §3.1). +pub(crate) fn opus_samples(data: &[u8]) -> Option { + let toc = *data.first()?; + let config = usize::from(toc >> 3); + let frame = match config { + 0..=11 => [480, 960, 1920, 2880][config % 4], + 12..=15 => [480, 960][config % 2], + _ => [120, 240, 480, 960][config % 4], + }; + let count = match toc & 3 { + 0 => 1, + 1 | 2 => 2, + _ => u32::from(*data.get(1)? & 0x3F), + }; + Some(frame * count) +} + +/// Checks that an ADTS frame or a run of them fills `data` exactly. +fn check_adts(data: &[u8]) -> Result<(), Error> { + let mut at = 0; + while at < data.len() { + let f = &data[at..]; + let &[0xFF, b1, _, b3, b4, b5, _, ..] = f else { return Err(Error::BadFrame("an AAC frame must start with an ADTS header")) }; + if b1 & 0xF6 != 0xF0 { + return Err(Error::BadFrame("an AAC frame must start with an ADTS header")); + } + let header = if b1 & 1 == 0 { 9 } else { 7 }; + let len = usize::from(b3 & 3) << 11 | usize::from(b4) << 3 | usize::from(b5 >> 5); + if len < header || len > f.len() { + return Err(Error::BadFrame("an ADTS frame_length does not match the frame")); + } + at += len; + } + Ok(()) +} + +/// A 33-bit timestamp with its 4-bit prefix and marker bits (§2.4.3.7). +fn timestamp(prefix: u8, v: i64) -> [u8; 5] { + let v = v.rem_euclid(WRAP_90K); + [prefix << 4 | ((v >> 29) & 0x0E) as u8 | 1, (v >> 22) as u8, ((v >> 14) & 0xFE) as u8 | 1, (v >> 7) as u8, ((v << 1) & 0xFE) as u8 | 1] +} + +/// Writes a PES header into `out` and returns its length. `length` is the PES_packet_length field +/// (0 for an unbounded video packet). +pub(crate) fn header(out: &mut [u8; HEADER_MAX], stream_id: u8, length: u16, pts: i64, dts: Option) -> usize { + let [hi, lo] = length.to_be_bytes(); + // '10', not scrambled, no priority, data_alignment_indicator set, not copyrighted, a copy + out[..7].copy_from_slice(&[0, 0, 1, stream_id, hi, lo, 0x84]); + match dts { + Some(dts) => { + out[7] = 0xC0; + out[8] = 10; + out[9..14].copy_from_slice(×tamp(3, pts)); + out[14..19].copy_from_slice(×tamp(1, dts)); + 19 + } + None => { + out[7] = 0x80; + out[8] = 5; + out[9..14].copy_from_slice(×tamp(2, pts)); + 14 + } + } +} + +/// The six program_clock_reference bytes for a 27 MHz clock value: the 33-bit base (clock / 300), +/// six reserved bits, and the 9-bit extension (clock % 300). +pub(crate) fn pcr(clock: i64) -> [u8; 6] { + let v = clock.rem_euclid(WRAP_90K * 300); + let (base, ext) = (v / 300, v % 300); + [(base >> 25) as u8, (base >> 17) as u8, (base >> 9) as u8, (base >> 1) as u8, ((base & 1) << 7) as u8 | 0x7E | (ext >> 8) as u8, ext as u8] +} + +/// The first NAL unit's first header byte, when `data` starts with an Annex B start code. +fn first_nal(data: &[u8]) -> Option { + let at = if data.starts_with(&[0, 0, 1]) { + 3 + } else if data.starts_with(&[0, 0, 0, 1]) { + 4 + } else { + return None; + }; + data.get(at).copied() +} + +/// Checks that `data` is a frame of `codec`, writes what goes in front of it into `out`, and +/// returns the prefix length and the bytes the frame itself takes. +pub(crate) fn prepare(codec: Codec, data: &[u8], key: bool, trim: OpusTrim, out: &mut [u8; PREFIX_MAX]) -> Result { + if let Codec::Av1(_) = codec { + return Ok(Prepared { prefix_len: 0, body_len: av1::check(data, key)? }); + } + let prefix_len = prefix(codec, data, trim, out)?; + Ok(Prepared { prefix_len, body_len: data.len() }) +} + +/// Checks a frame of a codec carried as it is and writes its prefix. Returns the prefix length. +fn prefix(codec: Codec, data: &[u8], trim: OpusTrim, out: &mut [u8; PREFIX_MAX]) -> Result { + match codec { + Codec::H264 => { + let nal = first_nal(data).ok_or(Error::BadFrame("an H.264 frame must start with an Annex B start code"))?; + if nal & 0x1F == 9 { + return Ok(0); + } + // access unit delimiter, primary_pic_type 7 (any slice type) (H.222.0 §2.14) + out[..6].copy_from_slice(&[0, 0, 0, 1, 0x09, 0xF0]); + Ok(6) + } + Codec::Hevc => { + let nal = first_nal(data).ok_or(Error::BadFrame("an HEVC frame must start with an Annex B start code"))?; + if (nal >> 1) & 0x3F == 35 { + return Ok(0); + } + // access unit delimiter (nal_unit_type 35), pic_type 2 (any slice type) (H.222.0 §2.17) + out[..7].copy_from_slice(&[0, 0, 0, 1, 0x46, 0x01, 0x50]); + Ok(7) + } + Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::Mpeg4Part2 => { + first_nal(data).ok_or(Error::BadFrame("an MPEG video frame must start with a start code"))?; + Ok(0) + } + Codec::AacAdts => { + check_adts(data)?; + Ok(0) + } + Codec::Aac { object_type, sample_rate_index, channels } => { + let len = data.len() + 7; + if len > 0x1FFF { + return Err(Error::FrameTooLarge { size: data.len(), limit: 0x1FFF - 7 }); + } + // ADTS fixed and variable header (ISO/IEC 13818-7 §6.2): MPEG-4, no CRC, buffer + // fullness 0x7FF (variable rate), one raw data block + out[..7].copy_from_slice(&[ + 0xFF, + 0xF1, + (object_type - 1) << 6 | sample_rate_index << 2 | channels >> 2, + (channels & 3) << 6 | (len >> 11) as u8, + (len >> 3) as u8, + ((len & 7) as u8) << 5 | 0x1F, + 0xFC, + ]); + Ok(7) + } + Codec::Opus { .. } | Codec::OpusMapped(_) => { + // opus_control_header: the 11-bit prefix 0x3FF, the trim flags, no extension, the + // payload size as 0xFF bytes and a last byte, then the trims (3 reserved bits and + // 13 bits each) + let n = data.len() / 255; + let trims = if trim.start > 0 { 2 } else { 0 } + if trim.end > 0 { 2 } else { 0 }; + if 3 + n + trims > PREFIX_MAX { + return Err(Error::FrameTooLarge { size: data.len(), limit: data_limit(codec, 8, trims) }); + } + out[0] = 0x7F; + out[1] = 0xE0 | if trim.start > 0 { 0x10 } else { 0 } | if trim.end > 0 { 0x08 } else { 0 }; + out[2..2 + n].fill(0xFF); + out[2 + n] = (data.len() % 255) as u8; + let mut at = 3 + n; + for t in [trim.start, trim.end] { + if t > 0 { + out[at..at + 2].copy_from_slice(&(t & 0x1FFF).to_be_bytes()); + at += 2; + } + } + Ok(at) + } + Codec::Ac3 => match data { + [0x0B, 0x77, ..] => Ok(0), + _ => Err(Error::BadFrame("an AC-3 frame must start with its sync word")), + }, + Codec::Eac3 => match data { + // bsid, the top five bits of byte 5, is 11 to 16 for E-AC-3 (ATSC A/52) + [0x0B, 0x77, _, _, _, b5, ..] if (11..=16).contains(&(b5 >> 3)) => Ok(0), + _ => Err(Error::BadFrame("an E-AC-3 frame must start with its sync word and a bsid of 11 to 16")), + }, + Codec::MpegAudio { low_sample_rate } => match data { + [0xFF, b, ..] if b & 0xE0 == 0xE0 => { + // version: 3 MPEG-1, 2 MPEG-2, 0 MPEG 2.5, 1 reserved; layer 0 is reserved + let version = (b >> 3) & 3; + if version == 1 || (b >> 1) & 3 == 0 { + return Err(Error::BadFrame("the MPEG audio frame header has a reserved version or layer")); + } + if (version == 3) == low_sample_rate { + return Err(Error::BadFrame("the MPEG audio frame's version does not match the stream's low_sample_rate")); + } + Ok(0) + } + _ => Err(Error::BadFrame("an MPEG audio frame must start with its sync word")), + }, + Codec::Av1(_) => Err(Error::BadFrame("AV1 frames are not carried with a prefix")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Reads a 33-bit timestamp back from its five bytes. + fn read(b: &[u8]) -> i64 { + (((b[0] >> 1) & 7) as i64) << 30 | (b[1] as i64) << 22 | ((b[2] >> 1) as i64) << 15 | (b[3] as i64) << 7 | (b[4] >> 1) as i64 + } + + #[test] + fn timestamps_carry_their_prefix_and_markers() { + for v in [0, 1, 90_000, (1 << 32) + 12_345, WRAP_90K - 1] { + let b = timestamp(2, v); + assert_eq!(b[0] >> 4, 2); + assert_eq!([b[0] & 1, b[2] & 1, b[4] & 1], [1, 1, 1]); + assert_eq!(read(&b), v); + } + assert_eq!(read(×tamp(2, WRAP_90K + 5)), 5, "wraps at 2^33"); + assert_eq!(read(×tamp(2, -1)), WRAP_90K - 1); + } + + #[test] + fn headers_hold_pts_and_dts() { + let mut h = [0u8; HEADER_MAX]; + assert_eq!(header(&mut h, 0xE0, 0, 3000, Some(0)), 19); + assert_eq!(&h[..9], &[0, 0, 1, 0xE0, 0, 0, 0x84, 0xC0, 10]); + assert_eq!((h[9] >> 4, read(&h[9..14]), h[14] >> 4, read(&h[14..19])), (3, 3000, 1, 0)); + assert_eq!(header(&mut h, 0xC0, 300, 7, None), 14); + assert_eq!(&h[4..9], &[1, 44, 0x84, 0x80, 5]); + } + + #[test] + fn pcr_splits_base_and_extension() { + let clock = 123_456_789i64 * 300 + 299; + let b = pcr(clock); + let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64; + let ext = ((b[4] & 1) as i64) << 8 | b[5] as i64; + assert_eq!((base, ext, b[4] & 0x7E), (123_456_789, 299, 0x7E)); + } + + const NO_TRIM: OpusTrim = OpusTrim { start: 0, end: 0 }; + + #[test] + fn access_unit_delimiters_are_added_once() { + let mut p = [0u8; PREFIX_MAX]; + assert_eq!(prefix(Codec::H264, &[0, 0, 0, 1, 0x65, 0x88], NO_TRIM, &mut p).unwrap(), 6); + assert_eq!(prefix(Codec::H264, &[0, 0, 1, 0x09, 0xF0, 0, 0, 1, 0x65], NO_TRIM, &mut p).unwrap(), 0); + assert_eq!(prefix(Codec::Hevc, &[0, 0, 0, 1, 0x26, 0x01], NO_TRIM, &mut p).unwrap(), 7); + assert_eq!(prefix(Codec::Hevc, &[0, 0, 1, 0x46, 0x01, 0x50], NO_TRIM, &mut p).unwrap(), 0); + assert!(matches!(prefix(Codec::H264, &[0x65, 0x88], NO_TRIM, &mut p), Err(Error::BadFrame(_)))); + assert!(matches!(prefix(Codec::H264, &[0, 0, 1], NO_TRIM, &mut p), Err(Error::BadFrame(_)))); + } + + #[test] + fn opus_control_header_codes_the_size_and_trims() { + let mut p = [0u8; PREFIX_MAX]; + let opus = Codec::Opus { channels: 2 }; + assert_eq!(prefix(opus, &[0xFC; 254], NO_TRIM, &mut p).unwrap(), 3); + assert_eq!(&p[..3], &[0x7F, 0xE0, 254]); + assert_eq!(prefix(opus, &[0xFC; 510], NO_TRIM, &mut p).unwrap(), 5); + assert_eq!(&p[..5], &[0x7F, 0xE0, 0xFF, 0xFF, 0]); + assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 312, end: 0 }, &mut p).unwrap(), 5); + assert_eq!(&p[..5], &[0x7F, 0xF0, 10, 0x01, 0x38]); + assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 1, end: 8191 }, &mut p).unwrap(), 7); + assert_eq!(&p[..7], &[0x7F, 0xF8, 10, 0, 1, 0x1F, 0xFF]); + assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 0, end: 2 }, &mut p).unwrap(), 5); + assert_eq!(&p[..5], &[0x7F, 0xE8, 10, 0, 2]); + } + + #[test] + fn opus_limits_match_the_pes_length() { + for (header, trim) in [(8, 0), (13, 0), (8, 4), (13, 2)] { + let l = data_limit(Codec::Opus { channels: 2 }, header, trim); + let body = |n: usize| header + 3 + n / 255 + trim + n; + assert!(body(l) <= 0xFFFF && body(l + 1) > 0xFFFF, "{header} {trim}: {l}"); + } + assert_eq!(data_limit(Codec::Ac3, 8, 0), 0xFFFF - 8); + assert_eq!(data_limit(Codec::Mpeg4Part2, 13, 0), MAX_VIDEO_FRAME); + } + + #[test] + fn opus_durations_from_the_table_of_contents() { + assert_eq!(opus_samples(&[0xFC]), Some(960), "CELT 20 ms, one frame"); + assert_eq!(opus_samples(&[0x08 | 1]), Some(1920), "SILK 20 ms, two frames"); + assert_eq!(opus_samples(&[0x18 | 3, 3]), Some(3 * 2880), "SILK 60 ms, three frames"); + assert_eq!(opus_samples(&[0x80]), Some(120), "CELT 2.5 ms"); + assert_eq!(opus_samples(&[0x03]), None); + assert_eq!(opus_samples(&[]), None); + } + + #[test] + fn adts_header_for_raw_aac() { + let mut p = [0u8; PREFIX_MAX]; + let codec = Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }; + assert_eq!(prefix(codec, &[0; 100], NO_TRIM, &mut p).unwrap(), 7); + // AAC LC, 48 kHz, 2 channels, 107 bytes + assert_eq!(&p[..7], &[0xFF, 0xF1, 0x4C, 0x80, 0x0D, 0x7F, 0xFC]); + assert!(matches!(prefix(codec, &[0; 8185], NO_TRIM, &mut p), Err(Error::FrameTooLarge { .. }))); + assert_eq!(data_limit(codec, 8, 0), 8184); + } + + fn adts(len: usize) -> Vec { + let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC]; + v.resize(len, 0x11); + v + } + + #[test] + fn adts_frame_lengths_must_tile_the_frame() { + let mut p = [0u8; PREFIX_MAX]; + assert_eq!(prefix(Codec::AacAdts, &adts(100), NO_TRIM, &mut p).unwrap(), 0); + let two = [adts(100), adts(57)].concat(); + assert_eq!(prefix(Codec::AacAdts, &two, NO_TRIM, &mut p).unwrap(), 0); + let mut short = adts(100); + short.pop(); + assert!(matches!(prefix(Codec::AacAdts, &short, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "one byte short"); + let mut long = adts(100); + long.push(0); + assert!(matches!(prefix(Codec::AacAdts, &long, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "a trailing byte"); + let mut zero = adts(100); + zero[3] &= 0xFC; + zero[4] = 0; + zero[5] &= 0x1F; + assert!(matches!(prefix(Codec::AacAdts, &zero, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "frame_length 0"); + // a header with a CRC is 9 bytes, so a frame_length of 8 does not hold it + let mut crc = adts(8); + crc[1] = 0xF0; + assert!(matches!(prefix(Codec::AacAdts, &crc, NO_TRIM, &mut p), Err(Error::BadFrame(_)))); + } + + #[test] + fn mpeg_audio_versions_match_the_stream_type() { + let mut p = [0u8; PREFIX_MAX]; + let (mpeg1, mpeg2, mpeg25, reserved) = ([0xFF, 0xFB, 0x90], [0xFF, 0xF3, 0x90], [0xFF, 0xE3, 0x90], [0xFF, 0xEB, 0x90]); + let high = Codec::MpegAudio { low_sample_rate: false }; + let low = Codec::MpegAudio { low_sample_rate: true }; + assert!(prefix(high, &mpeg1, NO_TRIM, &mut p).is_ok()); + assert!(prefix(low, &mpeg2, NO_TRIM, &mut p).is_ok()); + assert!(prefix(low, &mpeg25, NO_TRIM, &mut p).is_ok()); + assert!(prefix(low, &mpeg1, NO_TRIM, &mut p).is_err()); + assert!(prefix(high, &mpeg2, NO_TRIM, &mut p).is_err()); + assert!(prefix(high, &reserved, NO_TRIM, &mut p).is_err()); + assert!(prefix(high, &[0xFF, 0xF9, 0x90], NO_TRIM, &mut p).is_err(), "layer 0"); + } + + #[test] + fn eac3_needs_its_bsid() { + let mut p = [0u8; PREFIX_MAX]; + assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34, 16 << 3], NO_TRIM, &mut p).is_ok()); + assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34, 8 << 3], NO_TRIM, &mut p).is_err(), "AC-3's bsid"); + assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34], NO_TRIM, &mut p).is_err()); + } +} diff --git a/crates/media/src/mpegts/mux/psi.rs b/crates/media/src/mpegts/mux/psi.rs new file mode 100644 index 000000000..b4c55c3fb --- /dev/null +++ b/crates/media/src/mpegts/mux/psi.rs @@ -0,0 +1,216 @@ +//! Program specific information: the program association section and the program map section +//! (H.222.0 §2.4.4), each ending with the CRC-32 of Annex A that the demuxer checks. + +pub(crate) use super::super::ts::crc32_mpeg as crc32; +use super::{Codec, Error, OpusMapping, Stream}; + +/// Largest `section_length` of a program association or program map section (§2.4.4.3, §2.4.4.8). +pub(crate) const MAX_SECTION_LENGTH: usize = 1021; + +/// Writes `section_length` into bytes 1 and 2 and appends the CRC. `s` holds the section from +/// `table_id` up to the CRC. +fn finish(mut s: Vec) -> Result, Error> { + let length = s.len() + 4 - 3; + if length > MAX_SECTION_LENGTH { + return Err(Error::PsiTooLarge { length }); + } + s[1] = 0xB0 | (length >> 8) as u8; + s[2] = length as u8; + let crc = crc32(&s); + s.extend_from_slice(&crc.to_be_bytes()); + Ok(s) +} + +/// The program association section with one program. +pub(crate) fn pat(transport_stream_id: u16, program_number: u16, pmt_pid: u16) -> Result, Error> { + let mut s = vec![0x00, 0, 0]; + s.extend_from_slice(&transport_stream_id.to_be_bytes()); + // reserved, version_number 0, current_next_indicator 1; section_number 0, last_section_number 0 + s.extend_from_slice(&[0xC1, 0x00, 0x00]); + s.extend_from_slice(&program_number.to_be_bytes()); + s.extend_from_slice(&(0xE000 | pmt_pid).to_be_bytes()); + finish(s) +} + +/// The program map section. +pub(crate) fn pmt(program_number: u16, pcr_pid: u16, streams: &[Stream]) -> Result, Error> { + let mut s = vec![0x02, 0, 0]; + s.extend_from_slice(&program_number.to_be_bytes()); + s.extend_from_slice(&[0xC1, 0x00, 0x00]); + s.extend_from_slice(&(0xE000 | pcr_pid).to_be_bytes()); + // program_info_length 0 + s.extend_from_slice(&[0xF0, 0x00]); + for st in streams { + s.push(st.codec.stream_type()); + s.extend_from_slice(&(0xE000 | st.pid).to_be_bytes()); + let at = s.len(); + s.extend_from_slice(&[0xF0, 0x00]); + descriptors(st, &mut s); + let len = s.len() - at - 2; + s[at] = 0xF0 | (len >> 8) as u8; + s[at + 1] = len as u8; + } + finish(s) +} + +/// The elementary stream descriptors of one stream. +fn descriptors(st: &Stream, s: &mut Vec) { + match st.codec { + // registration_descriptor (§2.6.8) with the format identifier "AC-3" + Codec::Ac3 => s.extend_from_slice(&[0x05, 4, b'A', b'C', b'-', b'3']), + // registration "EAC3" (ATSC A/52) with stream type 0x87 + Codec::Eac3 => s.extend_from_slice(&[0x05, 4, b'E', b'A', b'C', b'3']), + Codec::Opus { channels } => { + // registration_descriptor "Opus", then the Opus audio descriptor as an extension + // descriptor (tag 0x7F) whose channel_config_code is the channel count (1 to 8) + s.extend_from_slice(&[0x05, 4, b'O', b'p', b'u', b's']); + s.extend_from_slice(&[0x7F, 2, OPUS_DESCRIPTOR_EXTENSION, channels]); + } + Codec::OpusMapped(m) => { + s.extend_from_slice(&[0x05, 4, b'O', b'p', b'u', b's']); + let mut body = [0u8; 10]; + let n = opus_explicit(&m, &mut body); + s.extend_from_slice(&[0x7F, 1 + n as u8, OPUS_DESCRIPTOR_EXTENSION]); + s.extend_from_slice(&body[..n]); + } + Codec::Av1(c) => { + // registration_descriptor "AV01" first, then the AV1 video descriptor (tag 0x80) + // (Carriage of AV1 in MPEG-2 TS, §2) + s.extend_from_slice(&[0x05, 4, b'A', b'V', b'0', b'1']); + let b = |v: bool, shift: u8| u8::from(v) << shift; + s.extend_from_slice(&[ + 0x80, + 4, + 0x81, + c.seq_profile << 5 | c.seq_level_idx_0, + b(c.seq_tier_0, 7) + | b(c.high_bitdepth, 6) + | b(c.twelve_bit, 5) + | b(c.monochrome, 4) + | b(c.chroma_subsampling_x, 3) + | b(c.chroma_subsampling_y, 2) + | c.chroma_sample_position, + // hdr_wcg_idc, then reserved zeros and no initial_presentation_delay + c.hdr_wcg_idc << 6, + ]); + } + _ => {} + } + if let Some(lang) = st.language { + // ISO_639_language_descriptor (§2.6.18), audio_type 0 (undefined) + s.extend_from_slice(&[0x0A, 4, lang[0], lang[1], lang[2], 0]); + } +} + +/// `descriptor_tag_extension` of the Opus audio descriptor. The Opus transport draft leaves the +/// value open; 0x80 is the value in use for it. +pub(crate) const OPUS_DESCRIPTOR_EXTENSION: u8 = 0x80; + +/// Bits needed for the values 0 to `n - 1`: ceil(log2(n)). +fn bits_for(n: u32) -> u32 { + if n <= 1 { 0 } else { 32 - (n - 1).leading_zeros() } +} + +/// The opus_audio_descriptor body for an explicit channel configuration (channel_config_code +/// 0x81): channel_count, mapping_family and, for a family above 0, stream_count_minus_one, +/// coupled_stream_count and the channel mapping in as few bits as the draft gives each, padded +/// with zero bits to a byte. Returns its length. +fn opus_explicit(m: &OpusMapping, out: &mut [u8; 10]) -> usize { + out[..3].copy_from_slice(&[0x81, m.channels, m.family]); + if m.family == 0 { + return 3; + } + let (ch, streams, coupled) = (u32::from(m.channels), u32::from(m.streams), u32::from(m.coupled)); + let mut acc: u64 = 0; + let mut bits = 0; + let mut put = |v: u32, n: u32| { + acc = acc << n | u64::from(v & ((1 << n) - 1)); + bits += n; + }; + put(streams - 1, bits_for(ch)); + put(coupled, bits_for(streams + 1)); + let width = bits_for(streams + coupled + 1); + for &c in &m.mapping[..usize::from(m.channels)] { + put(if c == 255 { (1 << width) - 1 } else { u32::from(c) }, width); + } + let bytes = bits.div_ceil(8) as usize; + let acc = acc << (bytes as u32 * 8 - bits); + for (i, o) in out[3..3 + bytes].iter_mut().enumerate() { + *o = (acc >> (8 * (bytes - 1 - i))) as u8; + } + 3 + bytes +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crc_check_value() { + // the CRC-32/MPEG-2 check value of the ASCII digits 1 to 9 + assert_eq!(crc32(b"123456789"), 0x0376_E6E7); + } + + #[test] + fn sections_end_with_a_crc_over_the_whole_section() { + let pat = pat(7, 1, 0x1000).unwrap(); + assert_eq!(pat.len(), 16); + assert_eq!(crc32(&pat), 0); + assert_eq!(&pat[..3], &[0x00, 0xB0, 13]); + assert_eq!(&pat[8..12], &[0x00, 0x01, 0xF0, 0x00]); + let st = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Opus { channels: 2 }).with_language(*b"eng")]; + let pmt = pmt(1, 0x100, &st).unwrap(); + assert_eq!(crc32(&pmt), 0); + assert_eq!(pmt.len(), 3 + ((pmt[1] as usize & 0x0F) << 8 | pmt[2] as usize)); + assert_eq!(&pmt[8..10], &[0xE1, 0x00], "PCR_PID"); + assert_eq!(&pmt[12..17], &[0x1B, 0xE1, 0x00, 0xF0, 0x00], "H.264 without descriptors"); + assert_eq!(&pmt[17..22], &[0x06, 0xE1, 0x01, 0xF0, 16]); + } + + #[test] + fn a_section_past_the_length_limit_is_refused() { + let st: Vec = (0..200).map(|i| Stream::new(0x100 + i, Codec::Ac3).with_language(*b"eng")).collect(); + assert!(matches!(pmt(1, 0x100, &st), Err(Error::PsiTooLarge { .. }))); + } + + /// The descriptors of one stream's PMT entry. + fn stream_descriptors(codec: Codec) -> Vec { + let pmt = pmt(1, 0x100, &[Stream::new(0x100, codec)]).unwrap(); + let len = ((pmt[15] as usize & 0x0F) << 8) | pmt[16] as usize; + pmt[17..17 + len].to_vec() + } + + #[test] + fn explicit_opus_mappings_pack_their_fields() { + // 6 channels, family 1, 4 streams, 2 coupled: 3 + 3 + 6 * 3 = 24 bits + let m = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }; + let d = stream_descriptors(Codec::OpusMapped(m)); + let want = 0b011 << 21 | 0b010 << 18 | 0b000_100_001_010_011_101; + assert_eq!(&d[6..], &[0x7F, 7, 0x80, 0x81, 6, 1, (want >> 16) as u8, (want >> 8) as u8, want as u8]); + // 3 channels, family 255, 3 streams, none coupled, one silent: 2 + 2 + 3 * 2 = 10 bits + let m = OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [2, 255, 0, 0, 0, 0, 0, 0] }; + let d = stream_descriptors(Codec::OpusMapped(m)); + assert_eq!(&d[6..], &[0x7F, 6, 0x80, 0x81, 3, 255, 0b10_00_10_11, 0b00_000000]); + // family 0 carries no stream fields + let m = OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] }; + assert_eq!(&stream_descriptors(Codec::OpusMapped(m))[6..], &[0x7F, 4, 0x80, 0x81, 2, 0]); + } + + #[test] + fn av1_and_eac3_descriptors() { + let c = crate::mpegts::mux::Av1Config { + seq_profile: 1, + seq_level_idx_0: 8, + seq_tier_0: false, + high_bitdepth: true, + twelve_bit: false, + monochrome: false, + chroma_subsampling_x: false, + chroma_subsampling_y: false, + chroma_sample_position: 0, + hdr_wcg_idc: 3, + }; + assert_eq!(stream_descriptors(Codec::Av1(c)), [0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x28, 0x40, 0xC0]); + assert_eq!(stream_descriptors(Codec::Eac3), [0x05, 4, b'E', b'A', b'C', b'3']); + } +} diff --git a/crates/media/src/mpegts/mux/tests.rs b/crates/media/src/mpegts/mux/tests.rs new file mode 100644 index 000000000..d007ea755 --- /dev/null +++ b/crates/media/src/mpegts/mux/tests.rs @@ -0,0 +1,915 @@ +use super::*; + +use std::cell::RefCell; +use std::rc::Rc; + +const WIDE_OPUS: OpusMapping = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }; + +/// One packet's header fields. +#[derive(Debug, Clone, Copy)] +struct Pk { + pid: u16, + pusi: bool, + cc: u8, + payload: bool, + rai: bool, + disc: bool, + pcr: Option, +} + +fn walk(ts: &[u8]) -> Vec { + assert_eq!(ts.len() % PACKET_SIZE, 0); + ts.chunks(PACKET_SIZE) + .map(|p| { + assert_eq!(p[0], 0x47); + let afc = p[3] >> 4 & 3; + let (mut rai, mut disc, mut pcr) = (false, false, None); + if afc & 2 != 0 { + let len = p[4] as usize; + assert!(len <= 183); + if afc == 2 { + assert_eq!(len, 183); + } + if len > 0 { + rai = p[5] & 0x40 != 0; + disc = p[5] & 0x80 != 0; + if p[5] & 0x10 != 0 { + let b = &p[6..12]; + let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64; + pcr = Some(base * 300 + (((b[4] & 1) as i64) << 8 | b[5] as i64)); + } + } + } + Pk { pid: ((p[1] & 0x1F) as u16) << 8 | p[2] as u16, pusi: p[1] & 0x40 != 0, cc: p[3] & 0x0F, payload: afc & 1 != 0, rai, disc, pcr } + }) + .collect() +} + +fn h264(key: bool) -> Vec { + if key { + vec![0, 0, 0, 1, 0x67, 0x42, 0, 0x1E, 0, 0, 0, 1, 0x68, 0xCE, 0, 0, 1, 0x65, 0x88, 0x84, 0x21] + } else { + vec![0, 0, 0, 1, 0x41, 0x9A, 0x11] + } +} + +fn mux(cfg: Config, streams: &[Stream], f: impl FnOnce(&mut Muxer>)) -> Vec { + let mut m = Muxer::new(Vec::new(), cfg, streams).unwrap(); + f(&mut m); + m.finish().unwrap() +} + +#[test] +fn starts_with_pat_pmt_and_a_pcr_on_the_first_frame() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| { + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + assert_eq!(pk.len(), 3); + assert_eq!((pk[0].pid, pk[0].pusi), (0, true)); + assert_eq!((pk[1].pid, pk[1].pusi), (0x1000, true)); + assert_eq!((pk[2].pid, pk[2].pusi, pk[2].rai), (0x100, true, true)); + assert_eq!(pk[2].pcr, Some((90_000 - 63_000) * 300)); + // the payload ends the packet: the access unit delimiter, then the frame + let frame = h264(true); + let p = &ts[2 * PACKET_SIZE..]; + assert_eq!(&p[PACKET_SIZE - frame.len()..PACKET_SIZE], &frame[..]); + assert_eq!(&p[PACKET_SIZE - frame.len() - 6 - 14..PACKET_SIZE - frame.len() - 6][..4], &[0, 0, 1, 0xE0]); + assert_eq!(&p[PACKET_SIZE - frame.len() - 6..PACKET_SIZE - frame.len()], &[0, 0, 0, 1, 9, 0xF0]); +} + +#[test] +fn every_stuffing_length_fills_the_packet() { + // frames whose PES packet ends at every offset of a packet, with and without a PCR + for n in 1..=400usize { + let ts = mux(Config { pcr_pid: Some(0x200), ..Config::default() }, &[Stream::new(0x100, Codec::MpegAudio { low_sample_rate: false })], |m| { + let mut data = vec![0u8; n]; + data[0] = 0xFF; + if n > 1 { + data[1] = 0xFB; + } + if n == 1 { + assert!(matches!(m.write_frame(0, &Frame { data: &data, pts: 90_000, dts: None, key: true }), Err(Error::BadFrame(_)))); + return; + } + m.write_frame(0, &Frame { data: &data, pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &data, pts: 92_000, dts: None, key: false }).unwrap(); + }); + if n == 1 { + continue; + } + let pk = walk(&ts); + let mut payload = 0; + for (p, raw) in pk.iter().zip(ts.chunks(PACKET_SIZE)) { + if p.pid == 0x100 { + let start = if raw[3] & 0x20 != 0 { 5 + raw[4] as usize } else { 4 }; + payload += PACKET_SIZE - start; + } + } + assert_eq!(payload, 2 * (14 + n), "{n}"); + } +} + +#[test] +fn continuity_counters_count_payload_packets_per_pid() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| { + let big = { + let mut v = h264(true); + v.resize(10_000, 0x55); + v + }; + for k in 0..40i64 { + m.write_frame(0, &Frame { data: &big, pts: 90_000 + k * 3000, dts: None, key: k % 10 == 0 }).unwrap(); + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 1, 2, 3], pts: 90_000 + k * 3000, dts: None, key: true }).unwrap(); + } + }); + let mut last: std::collections::HashMap = Default::default(); + for p in walk(&ts) { + if let Some(&c) = last.get(&p.pid) { + let want = if p.payload { (c + 1) & 0x0F } else { c }; + assert_eq!(p.cc, want, "PID {:#x}", p.pid); + } + last.insert(p.pid, p.cc); + } +} + +#[test] +fn pcr_never_lapses_past_the_interval() { + for interval in [900u32, 3600, MAX_PCR_INTERVAL] { + // video on 0x100 carries the PCR; a 2 s gap in the video is filled from the audio clock + let ts = + mux(Config { pcr_interval: interval, ..Config::default() }, &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| { + let mut t = 90_000i64; + for k in 0..200i64 { + if !(50..110).contains(&k) { + m.write_frame(0, &Frame { data: &h264(k == 0), pts: t, dts: None, key: k == 0 }).unwrap(); + } + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 0], pts: t, dts: None, key: true }).unwrap(); + t += 3000; + } + }); + let pcrs: Vec = walk(&ts).iter().filter(|p| p.pid == 0x100).filter_map(|p| p.pcr).collect(); + assert!(pcrs.len() > 1); + for w in pcrs.windows(2) { + assert!(w[1] > w[0], "PCR goes forward"); + assert!(w[1] - w[0] <= i64::from(interval) * 300, "interval {interval}: {} apart", w[1] - w[0]); + } + } +} + +#[test] +fn pcr_on_a_pid_of_its_own_and_through_advance() { + let mut m = Muxer::new(Vec::new(), Config { pcr_pid: Some(0x1FF), ..Config::default() }, &[Stream::new(0x101, Codec::Ac3)]).unwrap(); + assert_eq!(m.pcr_pid(), 0x1FF); + m.advance(63_000).unwrap(); + m.advance(63_000 + 90_000).unwrap(); + m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000 + 90_000, dts: None, key: true }).unwrap(); + let st = m.stats(); + let ts = m.finish().unwrap(); + let pk = walk(&ts); + let pcrs: Vec = pk.iter().filter(|p| p.pid == 0x1FF).map(|p| p.pcr.unwrap()).collect(); + assert_eq!(pcrs.first(), Some(&0)); + assert_eq!(pcrs.last(), Some(&(90_000 * 300))); + assert!(pcrs.windows(2).all(|w| w[1] - w[0] <= 3600 * 300)); + assert!(pk.iter().filter(|p| p.pid == 0x1FF).all(|p| !p.payload && p.cc == 0)); + assert_eq!(st.pcrs as usize, pcrs.len()); + assert_eq!(pcrs.len(), 26, "one PCR, 24 to fill the second, one at its end"); + // at the start, then every 100 ms of the gap, the last one at its end + assert_eq!(st.psi, 11); + let mut last_psi = None; + let mut pcr = 0; + for p in &pk { + if let Some(v) = p.pcr { + pcr = v; + } + if p.pid == 0 { + if let Some(l) = last_psi { + assert!(pcr - l <= (9000 + 3600) * 300, "PAT {} after the last", pcr - l); + } + last_psi = Some(pcr); + } + } + assert_eq!(st.bytes(), ts.len() as u64); +} + +#[test] +fn a_pcr_packet_before_the_first_payload_keeps_the_counter_continuous() { + // the audio frame comes first, so the video PID carries a PCR-only packet before its first + // payload packet + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| { + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + }); + let video: Vec = walk(&ts).into_iter().filter(|p| p.pid == 0x100).collect(); + assert_eq!(video.len(), 2); + assert!(!video[0].payload && video[0].pcr.is_some()); + assert!(video[1].payload); + assert_eq!(video[1].cc, (video[0].cc + 1) & 0x0F); +} + +#[test] +fn a_long_gap_is_closed_by_one_pcr() { + let mut m = Muxer::new(Vec::new(), Config { pcr_interval: 1, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap(); + m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000 + 90_000, dts: None, key: true }).unwrap(); + assert_eq!(m.stats().pcr_gaps, 1); + let pcrs: Vec = walk(&m.finish().unwrap()).iter().filter_map(|p| p.pcr).collect(); + assert_eq!(pcrs.len() as u32, 2 + MAX_PCR_FILL); + assert_eq!(pcrs.last(), Some(&(90_000 * 300))); +} + +#[test] +fn psi_repeats_on_keyframes_and_new_writers() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(false), pts: 93_000, dts: None, key: false }).unwrap(); + assert_eq!(m.stats().psi, 1); + m.write_frame(0, &Frame { data: &h264(true), pts: 96_000, dts: None, key: true }).unwrap(); + assert_eq!(m.stats().psi, 2); + let first = m.replace_writer(Vec::new()).writer; + m.write_frame(0, &Frame { data: &h264(false), pts: 99_000, dts: None, key: false }).unwrap(); + let second = m.finish().unwrap(); + let pk = walk(&second); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "a new segment starts with the PAT and PMT"); + let pk_first = walk(&first); + let last_video = pk_first.iter().rev().find(|p| p.pid == 0x100).unwrap().cc; + assert_eq!(pk.iter().find(|p| p.pid == 0x100).unwrap().cc, (last_video + 1) & 0x0F, "counters carry on"); +} + +#[test] +fn a_keyframe_after_a_gap_follows_the_tables_directly() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| { + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + // the gap reaches past the table interval and several PCR intervals + m.write_frame(0, &Frame { data: &h264(true), pts: 110_000, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + let keys: Vec = pk.iter().enumerate().filter(|(_, p)| p.pid == 0x100 && p.rai).map(|(i, _)| i).collect(); + assert_eq!(keys.len(), 2); + for k in keys { + assert_eq!((pk[k - 2].pid, pk[k - 1].pid), (0, 0x1000), "the PAT and PMT right before the keyframe at packet {k}"); + } + assert!(pk.iter().any(|p| p.pid == 0x100 && !p.payload), "PCR-only packets fill the gap"); + // a packet the caller writes between the tables and a keyframe brings the tables again + let mut null = [0xFF; PACKET_SIZE]; + null[..4].copy_from_slice(&[0x47, 0x1F, 0xFF, 0x10]); + let cfg = Config { pcr_interval: 9_000, psi_interval: 3_600, ..Config::default() }; + let ts = mux(cfg, &[Stream::new(0x100, Codec::H264)], |m| { + m.advance(90_000).unwrap(); + // the tables fall due here and the PCR does not, so the tables are the last packets + m.advance(93_600).unwrap(); + m.get_mut().extend_from_slice(&null); + m.write_frame(0, &Frame { data: &h264(true), pts: 93_600, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + let k = pk.iter().position(|p| p.pid == 0x100 && p.rai).unwrap(); + assert_eq!((pk[k - 3].pid, pk[k - 2].pid, pk[k - 1].pid), (0x1FFF, 0, 0x1000)); +} + +#[test] +fn tables_lost_with_a_failed_write_come_again_before_a_keyframe() { + let cfg = Config { pcr_interval: 9_000, psi_interval: 3_600, ..Config::default() }; + // the second write fails: the one at the end of the second advance + let mut m = Muxer::new(Flaky { fail_on: Some(2), calls: 0, data: Vec::new() }, cfg, &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.advance(90_000).unwrap(); + // the tables fall due and are dropped with the failed batch + assert!(matches!(m.advance(93_600), Err(Error::Io(_)))); + m.write_frame(0, &Frame { data: &h264(true), pts: 93_600, dts: None, key: true }).unwrap(); + let pk = walk(&m.finish().unwrap().data); + let k = pk.iter().position(|p| p.pid == 0x100 && p.rai).unwrap(); + assert_eq!((pk[k - 2].pid, pk[k - 1].pid), (0, 0x1000)); +} + +#[test] +fn every_new_segment_carries_a_pcr() { + for pcr_pid in [None, Some(0x1F0)] { + let mut m = Muxer::new(Vec::new(), Config { pcr_pid, ..Config::default() }, &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + m.replace_writer(Vec::new()); + // a frame within the PCR interval + m.write_frame(0, &Frame { data: &h264(false), pts: 90_001, dts: None, key: false }).unwrap(); + let segment = m.replace_writer(Vec::new()).writer; + m.advance(91_000).unwrap(); + let third = m.finish().unwrap(); + let want = pcr_pid.unwrap_or(0x100); + for (n, ts) in [segment, third].iter().enumerate() { + let pk = walk(ts); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "{pcr_pid:?} segment {n}"); + assert!(pk.iter().any(|p| p.pid == want && p.pcr.is_some()), "{pcr_pid:?} segment {n} has a PCR"); + } + } +} + +#[test] +fn a_segment_after_an_idle_gap_starts_with_the_tables() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + m.replace_writer(Vec::new()); + m.advance(180_000).unwrap(); + let pk = walk(&m.finish().unwrap()); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000)); + assert!(pk.len() > 10, "the gap is filled with PCRs"); +} + +#[test] +fn short_table_intervals_hold_in_idle_gaps() { + let mut m = Muxer::new(Vec::new(), Config { psi_interval: 900, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap(); + m.advance(63_000).unwrap(); + m.advance(63_000 + 90_000).unwrap(); + // every 900 ticks: at the start, 99 times inside the second, and at its end + assert_eq!(m.stats().psi, 101); + // a table interval of one tick fills at most MAX_PCR_FILL repeats per gap, and the PCRs still + // fill the gap + let mut m = Muxer::new(Vec::new(), Config { psi_interval: 1, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap(); + m.advance(63_000).unwrap(); + m.advance(63_000 + 90_000).unwrap(); + assert_eq!(m.stats().psi, 2 + u64::from(MAX_PCR_FILL)); + assert_eq!((m.stats().pcrs, m.stats().pcr_gaps), (26, 0)); +} + +#[test] +fn frames_behind_the_sent_clock_are_refused() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 900_000, dts: None, key: true }).unwrap(); + // the clock is 900 000 - 63 000: audio up to the PCR delay behind the video is fine + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_000, dts: None, key: true }).unwrap(); + let before = m.get_ref().len(); + assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_001, dts: None, key: true }), Err(Error::Timestamp(_)))); + m.advance(2_000_000).unwrap(); + let after = m.get_ref().len(); + assert!(after > before); + assert!(matches!(m.write_frame(0, &Frame { data: &h264(false), pts: 1_000_000, dts: None, key: false }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), after, "nothing is written for a refused frame"); +} + +#[test] +fn timestamps_and_dts() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| { + m.write_frame(0, &Frame { data: &h264(true), pts: (1 << 33) + 6000, dts: Some((1 << 33) + 3000), key: true }).unwrap(); + }); + let p = &ts[2 * PACKET_SIZE..]; + let start = 5 + p[4] as usize; + let h = &p[start..]; + assert_eq!(&h[..9], &[0, 0, 1, 0xE0, 0, (3 + 10 + 6 + h264(true).len()) as u8, 0x84, 0xC0, 10]); + assert_eq!(h[9] >> 4, 3); + assert_eq!(h[14] >> 4, 1); +} + +#[test] +fn bad_frames_and_timestamps_write_nothing() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)]).unwrap(); + fn f(data: &[u8], pts: i64, dts: Option) -> Frame<'_> { + Frame { data, pts, dts, key: true } + } + assert!(matches!(m.write_frame(2, &f(&h264(true), 90_000, None)), Err(Error::NoSuchStream(2)))); + assert!(matches!(m.write_frame(0, &f(&[], 90_000, None)), Err(Error::EmptyFrame))); + assert!(matches!(m.write_frame(0, &f(&h264(true), 90_000, Some(90_001))), Err(Error::Timestamp(_)))); + assert!(matches!(m.write_frame(0, &f(&[0x65, 0x88], 90_000, None)), Err(Error::BadFrame(_)))); + assert!(matches!(m.write_frame(1, &f(&[0xFF, 0xF1, 0, 0, 0, 0], 90_000, None)), Err(Error::BadFrame(_)))); + // ten ADTS frames of 7000 bytes: each is valid, together they pass the PES length + let one = { + let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (7000 >> 11) as u8, (7000 >> 3) as u8, ((7000 & 7) as u8) << 5 | 0x1F, 0xFC]; + v.resize(7000, 0x11); + v + }; + let long_adts = one.repeat(10); + assert!(matches!(m.write_frame(1, &f(&long_adts, 90_000, None)), Err(Error::FrameTooLarge { limit: 65_527, .. }))); + assert!(matches!(m.write_frame(0, &f(&h264(true), i64::MIN, None)), Err(Error::Timestamp(_)))); + assert!(m.get_ref().is_empty()); + m.write_frame(0, &f(&h264(true), 90_000, None)).unwrap(); + assert!(matches!(m.write_frame(0, &f(&h264(true), 80_000, None)), Err(Error::Timestamp(_)))); + // video has no PES length limit + let mut big = h264(true); + big.resize(200_000, 1); + m.write_frame(0, &f(&big, 93_000, None)).unwrap(); +} + +#[test] +fn settings_are_checked() { + let one = [Stream::new(0x100, Codec::H264)]; + let bad = |cfg: Config, streams: &[Stream]| matches!(Muxer::new(Vec::new(), cfg, streams), Err(Error::Config(_))); + let err = |cfg: Config, streams: &[Stream]| Muxer::new(Vec::new(), cfg, streams).err(); + let d = Config::default(); + assert!(bad(d, &[])); + assert!(bad(d, &[Stream::new(0x100, Codec::H264); MAX_STREAMS + 1])); + assert!(bad(Config { program_number: 0, ..d }, &one)); + assert!(matches!(err(Config { pmt_pid: 0x0F, ..d }, &one), Some(Error::BadPid(0x0F)))); + assert!(matches!(err(Config { pmt_pid: 0x1FFF, ..d }, &one), Some(Error::BadPid(0x1FFF)))); + assert!(bad(Config { pcr_interval: 0, ..d }, &one)); + assert!(bad(Config { pcr_interval: MAX_PCR_INTERVAL + 1, ..d }, &one)); + assert!(bad(Config { psi_interval: 0, ..d }, &one)); + assert!(bad(Config { batch_packets: 0, ..d }, &one)); + assert!(bad(Config { batch_packets: MAX_BATCH_PACKETS + 1, ..d }, &one)); + assert!(matches!(err(Config { pcr_delay: 0, ..d }, &one), Some(Error::PcrDelay(0)))); + assert!(matches!(err(Config { pcr_delay: MAX_PCR_DELAY + 1, ..d }, &one), Some(Error::PcrDelay(90_001)))); + assert!(err(Config { pcr_delay: MAX_PCR_DELAY, ..d }, &one).is_none()); + assert!(err(Config { pcr_delay: 1, ..d }, &one).is_none()); + assert!(matches!(err(Config { pcr_pid: Some(0x1000), ..d }, &one), Some(Error::DuplicatePid(0x1000)))); + assert!(matches!(err(Config { pcr_pid: Some(0x2000), ..d }, &one), Some(Error::BadPid(0x2000)))); + assert!(matches!(err(d, &[Stream::new(0x0005, Codec::H264)]), Some(Error::BadPid(5)))); + assert!(matches!(err(d, &[Stream::new(0x1000, Codec::H264)]), Some(Error::DuplicatePid(0x1000)))); + assert!(matches!(err(d, &[Stream::new(0x100, Codec::H264), Stream::new(0x100, Codec::Ac3)]), Some(Error::DuplicatePid(0x100)))); + assert!(!bad(Config { pcr_pid: Some(0x1FFE), ..d }, &one)); +} + +#[test] +fn stream_settings_are_checked() { + let bad = |cfg: Config, streams: &[Stream]| matches!(Muxer::new(Vec::new(), cfg, streams), Err(Error::Config(_))); + let err = |cfg: Config, streams: &[Stream]| Muxer::new(Vec::new(), cfg, streams).err(); + let d = Config::default(); + // the widest program fits: 32 streams of the longest descriptors + let wide: Vec = (0..MAX_STREAMS as u16).map(|i| Stream::new(0x100 + i, Codec::OpusMapped(WIDE_OPUS)).with_language(*b"eng")).collect(); + assert!(err(d, &wide).is_none()); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { streams: 7, ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { coupled: 5, ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [0, 1, 2, 3, 4, 10, 0, 0], ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 0, ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 2, ..WIDE_OPUS }))]), "a reserved family"); + assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 255, ..WIDE_OPUS }))])); + let stereo = OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] }; + assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(stereo))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { coupled: 255, ..stereo }))]), "no overflow"); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [1, 0, 0, 0, 0, 0, 0, 0], ..stereo }))]), "swapped"); + assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [0, 1, 2, 3, 4, 255, 0, 0], ..WIDE_OPUS }))])); + let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + assert!(!bad(d, &[Stream::new(0x100, Codec::Av1(av1))])); + assert!(bad(d, &[Stream::new(0x100, Codec::Av1(Av1Config { seq_profile: 3, ..av1 }))])); + assert!(Av1Config::from_av1c(&[0x01, 0x08, 0x0C, 0x00]).is_err()); + assert!(Av1Config::from_av1c(&[0x81, 0x08, 0x0C]).is_err()); + assert!(bad(d, &[Stream::new(0x100, Codec::Opus { channels: 0 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Opus { channels: 9 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 0, sample_rate_index: 3, channels: 2 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 2, sample_rate_index: 13, channels: 2 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 0 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"e1g")])); + assert!(bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"ENG")])); + assert!(!bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"eng")])); + // the first video stream carries the PCR by default + let m = Muxer::new(Vec::new(), d, &[Stream::new(0x101, Codec::Ac3), Stream::new(0x100, Codec::H264)]).unwrap(); + assert_eq!(m.pcr_pid(), 0x100); +} + +#[test] +fn wide_programs_split_the_pmt_across_packets() { + let streams: Vec = (0..MAX_STREAMS as u16).map(|i| Stream::new(0x100 + i, Codec::Opus { channels: 2 }).with_language(*b"eng")).collect(); + let ts = mux(Config::default(), &streams, |m| { + m.write_frame(0, &Frame { data: &[0xFC, 1], pts: 90_000, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + let pmt: Vec<_> = pk.iter().filter(|p| p.pid == 0x1000).collect(); + assert_eq!(pmt.len(), 4, "32 stream entries of 21 bytes"); + assert!(pmt[0].pusi && pmt[1..].iter().all(|p| !p.pusi)); + assert_eq!(pmt.iter().map(|p| p.cc).collect::>(), [0, 1, 2, 3]); + let mut section: Vec = + ts.chunks(PACKET_SIZE).zip(&pk).filter(|(_, p)| p.pid == 0x1000).flat_map(|(raw, p)| raw[if p.pusi { 5 } else { 4 }..].to_vec()).collect(); + let len = 3 + ((section[1] as usize & 0x0F) << 8 | section[2] as usize); + section.truncate(len); + assert_eq!(psi::crc32(§ion), 0); +} + +/// An output that records the length of every write call. +#[derive(Clone, Default)] +struct Calls(Rc>>); + +impl Write for Calls { + fn write(&mut self, b: &[u8]) -> io::Result { + self.0.borrow_mut().push(b.len()); + Ok(b.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// Video and audio for `seconds`, a 2 s GOP at 30 frames a second, in DTS order: (stream, frame). +fn av_timeline(seconds: i64) -> Vec<(usize, Vec, i64, bool)> { + let mut v = Vec::new(); + for k in 0..seconds * 30 { + let key = k % 60 == 0; + let mut f = h264(key); + f.resize(if key { 3000 } else { 700 }, 0x55); + v.push((0, f, 90_000 + k * 3000, key)); + } + for k in 0..seconds * 1000 / 32 { + v.push((1, vec![0x0B, 0x77, 0, 0, 0x08, 0x40, 0x40, 1, 2, 3], 90_000 + k * 2880, true)); + } + v.sort_by_key(|f| f.2); + v +} + +fn av_streams() -> [Stream; 2] { + [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)] +} + +#[test] +fn packets_go_out_in_batches() { + for hold in [false, true] { + let calls = Calls::default(); + let mut m = Muxer::new(calls.clone(), Config { hold_packets: hold, ..Config::default() }, &av_streams()).unwrap(); + for (s, f, t, key) in av_timeline(2) { + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + let before = m.stats(); + m.flush().unwrap(); + let st = m.stats(); + // held packets are counted once the output takes them + assert_eq!(before.packets == st.packets, !hold); + m.finish().unwrap(); + let lens = calls.0.borrow(); + assert!(lens.iter().all(|&n| n % PACKET_SIZE == 0 && n > 0 && n <= 7 * PACKET_SIZE), "{lens:?}"); + assert_eq!(lens.iter().sum::() as u64, st.bytes()); + if hold { + assert!(lens[..lens.len() - 1].iter().all(|&n| n == 7 * PACKET_SIZE), "held: full batches only"); + } else { + assert!(lens.len() as u64 >= st.frames, "a write at the end of every call"); + } + } +} + +#[test] +fn held_packets_reach_the_old_writer_before_a_swap() { + let cfg = Config { hold_packets: true, batch_packets: 348, ..Config::default() }; + let mut m = Muxer::new(Vec::new(), cfg, &av_streams()).unwrap(); + let mut segments = Vec::new(); + for (s, f, t, key) in av_timeline(10) { + if s == 0 && key && t > 90_000 { + segments.push(m.replace_writer(Vec::new())); + } + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + // held packets count once they reach the output + let held = m.stats(); + let last = m.replace_writer(Vec::new()); + let st = m.stats(); + assert!(held.packets < st.packets); + segments.push(last); + assert_eq!(segments.len(), 5, "a 2 s GOP over 10 s"); + let mut packets = 0; + let mut frames = 0; + for (n, seg) in segments.iter().enumerate() { + assert!(seg.error.is_none()); + assert_eq!(seg.writer.len() as u64, seg.packets * PACKET_SIZE as u64, "segment {n}"); + assert!(seg.starts_with_keyframe, "segment {n}"); + let pk = walk(&seg.writer); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "segment {n}"); + assert!(pk[2].pid == 0x100 && pk[2].pcr.is_some() && pk[2].rai, "segment {n}: the keyframe with a PCR"); + assert_eq!(seg.first_pts, Some(90_000 + n as i64 * 180_000)); + assert!(seg.last_pts.unwrap() < 90_000 + (n as i64 + 1) * 180_000); + packets += seg.packets; + frames += seg.frames; + } + assert_eq!((packets, frames), (st.packets, st.frames)); + // a segment cut before a frame that is not a keyframe says so + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + assert!(m.replace_writer(Vec::new()).starts_with_keyframe); + m.write_frame(0, &Frame { data: &h264(false), pts: 93_000, dts: None, key: false }).unwrap(); + assert!(!m.replace_writer(Vec::new()).starts_with_keyframe); +} + +#[test] +fn a_continuing_swap_leaves_the_packets_unchanged() { + let one = mux(Config::default(), &av_streams(), |m| { + for (s, f, t, key) in av_timeline(3) { + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + }); + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + let mut parts = Vec::new(); + for (n, (s, f, t, key)) in av_timeline(3).into_iter().enumerate() { + if n % 7 == 6 { + parts.push(m.replace_writer_continuing(Vec::new()).writer); + } + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + parts.push(m.finish().unwrap()); + assert!(parts.len() > 10); + assert_eq!(parts.concat(), one); +} + +#[test] +fn a_discontinuity_starts_a_new_time_base() { + for pcr_pid in [None, Some(0x1F0)] { + let mut m = Muxer::new(Vec::new(), Config { pcr_pid, ..Config::default() }, &av_streams()).unwrap(); + for (s, f, t, key) in av_timeline(2) { + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + let before = m.stats().packets as usize; + m.discontinuity(); + // the encoder restarts at a smaller timestamp, the audio first this time + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 9], pts: 100_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 100_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(false), pts: 103_000, dts: None, key: false }).unwrap(); + let ts = m.finish().unwrap(); + let pk = walk(&ts); + assert!(pk[..before].iter().all(|p| !p.disc)); + let after = &pk[before..]; + assert_eq!((after[0].pid, after[1].pid), (0, 0x1000), "{pcr_pid:?}: the tables first"); + let pcr_on = pcr_pid.unwrap_or(0x100); + let first_pcr = after.iter().find(|p| p.pcr.is_some()).unwrap(); + assert_eq!((first_pcr.pid, first_pcr.disc, first_pcr.pcr), (pcr_on, true, Some((100_000 - 63_000) * 300)), "{pcr_pid:?}"); + for pid in [0x100, 0x101] { + let first = after.iter().find(|p| p.pid == pid).unwrap(); + assert!(first.disc, "{pcr_pid:?}: PID {pid:#x}"); + assert_eq!(after.iter().filter(|p| p.pid == pid && p.disc).count(), 1, "{pcr_pid:?}: once on PID {pid:#x}"); + } + } +} + +#[test] +fn the_clock_after_advance_is_on_the_dts_scale() { + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + m.advance(900_000).unwrap(); + let pcrs: Vec = walk(m.get_ref()).iter().filter_map(|p| p.pcr).collect(); + assert_eq!(pcrs, [(900_000 - 63_000) * 300]); + let before = m.get_ref().len(); + assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_001, dts: None, key: true }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), before); + m.write_frame(0, &Frame { data: &h264(true), pts: 900_000 - 63_000, dts: None, key: true }).unwrap(); +} + +#[test] +fn streams_may_skew_by_the_pcr_delay() { + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + // video 500 ms ahead of the audio + for k in 0..30i64 { + m.write_frame(0, &Frame { data: &h264(k == 0), pts: 135_000 + k * 3000, dts: None, key: k == 0 }).unwrap(); + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000 + k * 3000, dts: None, key: true }).unwrap(); + } + // 800 ms behind the video is refused + let before = m.get_ref().len(); + m.write_frame(0, &Frame { data: &h264(false), pts: 900_000, dts: None, key: false }).unwrap(); + let mid = m.get_ref().len(); + assert!(mid > before); + assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 72_000, dts: None, key: true }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), mid); +} + +#[test] +fn video_decoding_times_must_increase() { + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 93_000, dts: Some(90_000), key: true }).unwrap(); + let before = m.get_ref().len(); + assert!(matches!(m.write_frame(0, &Frame { data: &h264(false), pts: 96_000, dts: Some(90_000), key: false }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), before); + // audio frames may share a time + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap(); +} + +#[test] +fn video_frames_past_the_reader_limit_are_refused() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + // zeroed pages are not touched before the size check + let mut big = vec![0u8; MAX_VIDEO_FRAME + 1]; + big[..5].copy_from_slice(&[0, 0, 0, 1, 0x65]); + assert!(matches!( + m.write_frame(0, &Frame { data: &big, pts: 90_000, dts: None, key: true }), + Err(Error::FrameTooLarge { limit: MAX_VIDEO_FRAME, .. }) + )); + assert_eq!(m.stats(), Stats::default()); + assert!(m.get_ref().is_empty()); + // an AV1 frame under the limit whose escapes take it over + let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::Av1(av1))]).unwrap(); + let mut tu = vec![0x0A, 0x05, 0x00, 0x00, 0x00, 0x02, 0x7F, 0x32]; + let payload = MAX_VIDEO_FRAME - 100; + let mut n = payload; + while n >= 0x80 { + tu.push((n & 0x7F) as u8 | 0x80); + n >>= 7; + } + tu.push(n as u8); + tu.resize(tu.len() + payload, 0); + *tu.last_mut().unwrap() = 1; + assert!(tu.len() <= MAX_VIDEO_FRAME); + assert!(matches!( + m.write_frame(0, &Frame { data: &tu, pts: 90_000, dts: None, key: true }), + Err(Error::FrameTooLarge { limit: MAX_VIDEO_FRAME, size }) if size > MAX_VIDEO_FRAME + )); + assert!(m.get_ref().is_empty()); +} + +#[test] +fn audio_specific_configs_become_adts_fields() { + let asc = |b: [u8; 2]| Codec::aac_from_asc(&b); + assert_eq!(asc([0x11, 0x90]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }); + assert_eq!(asc([0x12, 0x08]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 4, channels: 1 }); + assert_eq!(asc([0x11, 0xB0]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 6 }); + assert_eq!(asc([0x11, 0xB8]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 7 }); + assert!(asc([0x17, 0x80]).is_err(), "explicit sampling frequency"); + assert!(asc([0x29, 0x90]).is_err(), "SBR"); + assert!(asc([0x11, 0x80]).is_err(), "channel configuration 0"); + assert!(asc([0x11, 0x94]).is_err(), "frameLengthFlag 1"); + assert!(Codec::aac_from_asc(&[0x11]).is_err()); +} + +#[test] +fn opus_trims_follow_the_draft_rules() { + let opus = [Stream::new(0x100, Codec::Opus { channels: 2 }), Stream::new(0x101, Codec::Ac3)]; + let mut m = Muxer::new(Vec::new(), Config::default(), &opus).unwrap(); + // 8 CELT frames of 20 ms: 7680 samples + let au = [0xFF, 8, 0x11, 0x22]; + let f = |k: i64| Frame { data: &au, pts: 90_000 + k * 14_400, dts: None, key: true }; + assert!(matches!(m.write_frame_with_trim(1, &f(0), OpusTrim { start: 1, end: 0 }), Err(Error::BadFrame(_))), "not Opus"); + assert!(matches!(m.write_frame_with_trim(0, &f(0), OpusTrim { start: 7681, end: 0 }), Err(Error::BadFrame(_))), "longer than the unit"); + assert!(matches!(m.write_frame_with_trim(0, &f(0), OpusTrim { start: 8192, end: 0 }), Err(Error::BadFrame(_))), "13 bits"); + assert!(m.get_ref().is_empty()); + // whole units may be discarded at the start, 65 535 samples in all + for k in 0..8 { + m.write_frame_with_trim(0, &f(k), OpusTrim { start: 7680, end: 0 }).unwrap(); + } + assert!(matches!(m.write_frame_with_trim(0, &f(8), OpusTrim { start: 7680, end: 0 }), Err(Error::BadFrame(_)))); + m.write_frame_with_trim(0, &f(8), OpusTrim { start: 312, end: 0 }).unwrap(); + // the lead-in is over + assert!(matches!(m.write_frame_with_trim(0, &f(9), OpusTrim { start: 1, end: 0 }), Err(Error::BadFrame(_)))); + m.write_frame(0, &f(9)).unwrap(); + m.write_frame_with_trim(0, &f(10), OpusTrim { start: 0, end: 100 }).unwrap(); + // a restarted encoder trims its own start again + m.discontinuity(); + m.write_frame_with_trim(0, &f(0), OpusTrim { start: 312, end: 0 }).unwrap(); + m.write_frame_with_trim(0, &f(1), OpusTrim { start: 0, end: 100 }).unwrap(); + let ts = m.finish().unwrap(); + // the last unit's control header: end trim flag, size 4, end_trim 100 + let last = ts.chunks(PACKET_SIZE).rev().find(|p| p[1] & 0x40 != 0 && (u16::from(p[1] & 0x1F) << 8 | u16::from(p[2])) == 0x100).unwrap(); + let pes = &last[5 + last[4] as usize..]; + assert_eq!(&pes[14..19], &[0x7F, 0xE8, 4, 0, 100]); +} + +/// Each stream PID's PES packets: (random access indicator of the first packet, bytes). +fn pes_of(ts: &[u8], pids: &[u16]) -> std::collections::HashMap)>> { + let mut out: std::collections::HashMap)>> = Default::default(); + for (raw, p) in ts.chunks(PACKET_SIZE).zip(walk(ts)) { + if !pids.contains(&p.pid) || !p.payload { + continue; + } + let start = if raw[3] & 0x20 != 0 { 5 + raw[4] as usize } else { 4 }; + let list = out.entry(p.pid).or_default(); + if p.pusi { + list.push((p.rai, Vec::new())); + } + list.last_mut().unwrap().1.extend_from_slice(&raw[start..]); + } + out +} + +/// Reads a timestamp, checking its prefix and marker bits. +fn read_ts(b: &[u8], prefix: u8) -> i64 { + assert_eq!(b[0] >> 4, prefix); + assert_eq!([b[0] & 1, b[2] & 1, b[4] & 1], [1, 1, 1], "marker bits"); + (((b[0] >> 1) & 7) as i64) << 30 | (b[1] as i64) << 22 | ((b[2] >> 1) as i64) << 15 | (b[3] as i64) << 7 | (b[4] >> 1) as i64 +} + +#[test] +fn pes_headers_hold_their_fixed_bits_lengths_and_keyframes() { + let streams = [ + Stream::new(0x100, Codec::H264), + Stream::new(0x101, Codec::Ac3), + Stream::new(0x102, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }), + ]; + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + let mut frames: [Vec<(bool, i64, i64)>; 3] = Default::default(); + let mut outputs = Vec::new(); + for k in 0..120i64 { + if k % 40 == 0 && k > 0 { + outputs.push(m.replace_writer(Vec::new()).writer); + } + let key = k % 20 == 0; + let mut v = h264(key); + v.resize(if key { 30_000 } else { 70_000 + (k as usize * 997) % 9000 }, 0x55); + let dts = 90_000 + k * 3000; + let pts = dts + if key { 0 } else { 6000 }; + m.write_frame(0, &Frame { data: &v, pts, dts: Some(dts), key }).unwrap(); + frames[0].push((key, pts, dts)); + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 1, 2, 3], pts: dts, dts: None, key: true }).unwrap(); + frames[1].push((true, dts, dts)); + m.write_frame(2, &Frame { data: &vec![7; 1 + (k as usize * 31) % 1500], pts: dts, dts: None, key: true }).unwrap(); + frames[2].push((true, dts, dts)); + } + outputs.push(m.finish().unwrap()); + let mut seen = [0usize; 3]; + for ts in &outputs { + for (pid, list) in pes_of(ts, &[0x100, 0x101, 0x102]) { + let s = usize::from(pid - 0x100); + for (rai, pes) in list { + let (key, pts, dts) = frames[s][seen[s]]; + seen[s] += 1; + assert_eq!(&pes[..3], &[0, 0, 1]); + assert_eq!(pes[3], streams[s].codec.stream_id()); + assert_eq!(pes[6], 0x84, "'10', data_alignment_indicator"); + let length = usize::from(pes[4]) << 8 | usize::from(pes[5]); + if s == 0 && pes.len() - 6 > 0xFFFF { + assert_eq!(length, 0); + } else { + assert_eq!(length, pes.len() - 6, "PID {pid:#x}"); + } + assert_eq!(rai, key, "PID {pid:#x}"); + if pts == dts { + assert_eq!((pes[7], pes[8]), (0x80, 5)); + assert_eq!(read_ts(&pes[9..14], 2), pts); + } else { + assert_eq!((pes[7], pes[8]), (0xC0, 10)); + assert_eq!((read_ts(&pes[9..14], 3), read_ts(&pes[14..19], 1)), (pts, dts)); + } + } + } + } + assert_eq!(seen, [120, 120, 120]); +} + +/// An output that fails on one write call. +struct Flaky { + fail_on: Option, + calls: usize, + data: Vec, +} + +impl Write for Flaky { + fn write(&mut self, b: &[u8]) -> io::Result { + self.calls += 1; + if Some(self.calls) == self.fail_on { + return Err(io::Error::other("upload failed")); + } + self.data.extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn a_new_writer_recovers_from_an_io_error() { + let mut m = Muxer::new(Flaky { fail_on: Some(3), calls: 0, data: Vec::new() }, Config::default(), &av_streams()).unwrap(); + let mut failed = false; + let mut recovered = None; + for (s, f, t, key) in av_timeline(2) { + match m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }) { + Ok(()) => {} + Err(Error::Io(_)) if !failed => { + failed = true; + let old = m.replace_writer(Flaky { fail_on: None, calls: 0, data: Vec::new() }); + assert_eq!(old.writer.data.len() % PACKET_SIZE, 0); + recovered = Some(m.stats().packets); + } + Err(e) => panic!("{e}"), + } + } + assert!(failed && recovered.is_some()); + let ts = m.finish().unwrap().data; + let pk = walk(&ts); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000)); + assert!(pk.iter().take(4).any(|p| p.pcr.is_some()), "a PCR right after the tables"); + // counters run on within the new output + let mut last: std::collections::HashMap = Default::default(); + for p in &pk { + if let Some(&c) = last.get(&p.pid) { + assert_eq!(p.cc, if p.payload { (c + 1) & 0x0F } else { c }); + } + last.insert(p.pid, p.cc); + } +} + +/// An output that takes `take` bytes in all and then fails. +struct Short { + take: usize, + data: Vec, +} + +impl Write for Short { + fn write(&mut self, b: &[u8]) -> io::Result { + if self.data.len() >= self.take { + return Err(io::Error::other("disk full")); + } + // at most 100 bytes a call, so a batch goes out in several calls + let n = b.len().min(100).min(self.take - self.data.len()); + self.data.extend_from_slice(&b[..n]); + Ok(n) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn packet_counts_hold_only_what_the_output_took() { + let take = 5 * PACKET_SIZE + 50; + let mut m = Muxer::new(Short { take, data: Vec::new() }, Config::default(), &av_streams()).unwrap(); + let mut failed = false; + for (s, f, t, key) in av_timeline(1) { + if m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).is_err() { + failed = true; + break; + } + } + assert!(failed); + assert_eq!(m.stats().packets, 5); + let seg = m.replace_writer(Short { take: usize::MAX, data: Vec::new() }); + assert_eq!((seg.packets, seg.writer.data.len()), (5, take)); + // the new output takes a partial write in several calls and counts every packet + m.write_frame(0, &Frame { data: &h264(true), pts: 200_000, dts: None, key: true }).unwrap(); + let st = m.stats(); + let seg = m.replace_writer(Short { take: 0, data: Vec::new() }); + assert_eq!(seg.writer.data.len() as u64, seg.packets * PACKET_SIZE as u64); + assert_eq!(st.packets, 5 + seg.packets); +} diff --git a/crates/media/tests/mpegts_mux/mod.rs b/crates/media/tests/mpegts_mux/mod.rs new file mode 100644 index 000000000..4a3e6f2d1 --- /dev/null +++ b/crates/media/tests/mpegts_mux/mod.rs @@ -0,0 +1,260 @@ +//! Frames for the read-back tests, and a packet-level check of what the muxer wrote. + +#![allow(dead_code)] + +use std::collections::HashMap; + +use craft_media::mpegts::mux::{Codec, Frame, Muxer, PACKET_SIZE}; + +/// A frame queued for the muxer, with the bytes the demuxer should give back for it. +pub struct Item { + pub stream: usize, + pub data: Vec, + pub pts: i64, + pub dts: i64, + pub key: bool, + pub expect: Vec, +} + +/// Writes `items` in DTS order (stable, so equal DTS keep their order). +pub fn write_all(m: &mut Muxer>, items: &mut [Item]) { + items.sort_by_key(|i| i.dts); + for i in items.iter() { + let dts = (i.dts != i.pts).then_some(i.dts); + m.write_frame(i.stream, &Frame { data: &i.data, pts: i.pts, dts, key: i.key }).unwrap(); + } +} + +pub fn h264(key: bool, disposable: bool, size: usize, seed: u8) -> Vec { + let mut v = if key { + vec![0, 0, 0, 1, 0x67, 0x42, 0xC0, 0x1E, 0xDA, 0, 0, 0, 1, 0x68, 0xCE, 0x3C, 0x80, 0, 0, 1, 0x65, 0x88, 0x84] + } else if disposable { + vec![0, 0, 0, 1, 0x01, 0x9E] + } else { + vec![0, 0, 0, 1, 0x41, 0x9A] + }; + fill(&mut v, size, seed); + v +} + +pub fn hevc(key: bool, size: usize, seed: u8) -> Vec { + let mut v = if key { + vec![0, 0, 0, 1, 0x40, 0x01, 0x0C, 0, 0, 0, 1, 0x42, 0x01, 0x01, 0, 0, 0, 1, 0x44, 0x01, 0xC1, 0, 0, 1, 0x26, 0x01, 0xAF] + } else { + vec![0, 0, 0, 1, 0x02, 0x01, 0xD0] + }; + fill(&mut v, size, seed); + v +} + +/// An MPEG-2 picture (I with a sequence and GOP header, or P), `size` bytes. +pub fn mpeg2(key: bool, temporal_reference: u16, size: usize, seed: u8) -> Vec { + let mut v = Vec::new(); + if key { + v.extend_from_slice(&[0, 0, 1, 0xB3, 0x14, 0x00, 0xF0, 0x13, 0xFF, 0xFF, 0xE0, 0x18]); + v.extend_from_slice(&[0, 0, 1, 0xB8, 0x00, 0x08, 0x00, 0x00]); + } + let pct: u8 = if key { 1 } else { 2 }; + let tr = temporal_reference & 0x3FF; + v.extend_from_slice(&[0, 0, 1, 0x00, (tr >> 2) as u8, ((tr & 3) as u8) << 6 | pct << 3 | 0x07, 0xFF, 0xF8]); + v.extend_from_slice(&[0, 0, 1, 0x01, 0x12]); + fill(&mut v, size, seed); + v +} + +/// Pads with bytes that never form a start code. +pub fn fill(v: &mut Vec, size: usize, seed: u8) { + let mut x = seed as u32 | 1; + while v.len() < size { + x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345); + v.push(((x >> 16) as u8).max(1)); + } +} + +/// An ADTS frame: AAC LC, 48 kHz, 2 channels, `payload` bytes after the header. +pub fn adts(payload: usize, seed: u8) -> Vec { + let len = payload + 7; + let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC]; + fill(&mut v, len, seed); + v +} + +/// An AC-3 sync frame: 48 kHz, 64 kbit/s, 256 bytes. +pub fn ac3(seed: u8) -> Vec { + let mut v = vec![0x0B, 0x77, 0, 0, 0x08, 0x40, 0x40]; + fill(&mut v, 256, seed); + v +} + +/// An MPEG-1 Layer III frame (48 kHz, 128 kbit/s, 384 bytes), or with `low` an MPEG-2 one +/// (24 kHz, 64 kbit/s, 192 bytes). +pub fn mp3(low: bool, seed: u8) -> Vec { + let (mut v, size) = if low { (vec![0xFF, 0xF3, 0x84, 0x44], 192) } else { (vec![0xFF, 0xFB, 0x94, 0x44], 384) }; + fill(&mut v, size, seed); + v +} + +/// An E-AC-3 sync frame: independent substream 0, 256 bytes, 48 kHz, six blocks, 2/0, bsid 16. +pub fn eac3(seed: u8) -> Vec { + let mut v = vec![0x0B, 0x77, 0x00, 0x7F, 0x34, 0x80]; + fill(&mut v, 256, seed); + v +} + +/// An MPEG-4 Part 2 frame: a visual object sequence, visual object, video object layer and an +/// I-VOP, or a P-VOP alone. +pub fn mpeg4(key: bool, size: usize, seed: u8) -> Vec { + let mut v = if key { + vec![0, 0, 1, 0xB0, 0x01, 0, 0, 1, 0xB5, 0x09, 0, 0, 1, 0x00, 0, 0, 1, 0x20, 0x00, 0x84, 0x40, 0, 0, 1, 0xB6, 0x10] + } else { + vec![0, 0, 1, 0xB6, 0x50] + }; + fill(&mut v, size, seed); + v +} + +pub fn leb128(mut n: usize, v: &mut Vec) { + loop { + let b = (n & 0x7F) as u8; + n >>= 7; + if n == 0 { + v.push(b); + return; + } + v.push(b | 0x80); + } +} + +/// An AV1 temporal unit in the low overhead format: a temporal delimiter, a sequence header on +/// keyframes, and a frame OBU whose payload holds sequences that need emulation prevention. +pub fn av1(key: bool, size: usize, seed: u8) -> Vec { + let mut v = vec![0x12, 0x00]; + if key { + v.extend_from_slice(&[0x0A, 0x05, 0x00, 0x00, 0x00, 0x02, 0x7F]); + } + let mut payload = vec![0, 0, 1, 0, 0, 3, 0, 0, 0]; + fill(&mut payload, size, seed); + v.push(0x32); + leb128(payload.len(), &mut v); + v.extend_from_slice(&payload); + v +} + +/// The OBUs of a temporal unit without its temporal delimiters. +pub fn av1_without_delimiters(tu: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut at = 0; + while at < tu.len() { + let h = tu[at]; + let mut i = at + 1 + usize::from(h & 4 != 0); + let (mut size, mut shift) = (0usize, 0); + loop { + let b = tu[i]; + i += 1; + size |= usize::from(b & 0x7F) << shift; + shift += 7; + if b & 0x80 == 0 { + break; + } + } + if (h >> 3) & 0x0F != 2 { + out.extend_from_slice(&tu[at..i + size]); + } + at = i + size; + } + out +} + +/// Takes the start codes and emulation prevention bytes out of an AV1 PES payload, checking +/// that no 0x000000, 0x000001 or 0x000002 appears inside an OBU and that every 0x000003 is +/// followed by 0x00 to 0x03. +pub fn av1_unescape(es: &[u8]) -> Vec { + assert!(es.starts_with(&[0, 0, 1])); + let mut out = Vec::new(); + let (mut zeros, mut i) = (0, 0); + while i < es.len() { + if zeros == 0 && es[i..].starts_with(&[0, 0, 1]) { + i += 3; + continue; + } + let b = es[i]; + i += 1; + if zeros >= 2 { + assert!(b >= 3, "0x0000{b:02X} inside an OBU"); + zeros = 0; + if b == 3 { + assert!(es.get(i).is_some_and(|&n| n <= 3), "0x000003 followed by a byte that needs no escape"); + continue; + } + out.push(b); + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + out.push(b); + } + out +} + +/// The Opus control header and packet the demuxer gives back for an Opus frame. +pub fn opus_unit(packet: &[u8]) -> Vec { + let mut v = vec![0x7F, 0xE0]; + v.extend(std::iter::repeat_n(0xFF, packet.len() / 255)); + v.push((packet.len() % 255) as u8); + v.extend_from_slice(packet); + v +} + +/// What the demuxer gives back for a video frame: an access unit delimiter first. +pub fn with_aud(codec: Codec, data: &[u8]) -> Vec { + let mut v = match codec { + Codec::H264 => vec![0, 0, 0, 1, 0x09, 0xF0], + Codec::Hevc => vec![0, 0, 0, 1, 0x46, 0x01, 0x50], + _ => Vec::new(), + }; + v.extend_from_slice(data); + v +} + +/// Checks the packet layer: sync bytes, continuity counters, adaptation fields, and the PCR on +/// `pcr_pid` never more than `limit` (27 MHz) apart. Returns the PCRs. +pub fn check_packets(ts: &[u8], pcr_pid: u16, limit: i64) -> Vec { + assert_eq!(ts.len() % PACKET_SIZE, 0); + let mut cc: HashMap = HashMap::new(); + let mut pcrs = Vec::new(); + for p in ts.chunks(PACKET_SIZE) { + assert_eq!(p[0], 0x47); + assert_eq!(p[1] & 0x80, 0, "transport error indicator"); + assert_eq!(p[3] & 0xC0, 0, "scrambling"); + let pid = ((p[1] & 0x1F) as u16) << 8 | p[2] as u16; + let afc = p[3] >> 4 & 3; + assert_ne!(afc, 0); + let payload = afc & 1 != 0; + if let Some(&c) = cc.get(&pid) { + assert_eq!(p[3] & 0x0F, if payload { (c + 1) & 0x0F } else { c }, "continuity on PID {pid:#x}"); + } + cc.insert(pid, p[3] & 0x0F); + if afc & 2 != 0 { + let len = p[4] as usize; + assert!(if payload { len <= 182 } else { len == 183 }); + if len > 0 && p[5] & 0x10 != 0 { + assert!(len >= 7, "PCR flag in an adaptation field of {len} byte{}", if len == 1 { "" } else { "s" }); + assert_eq!(pid, pcr_pid, "a PCR off the PCR PID"); + let b = &p[6..12]; + assert_eq!(b[4] & 0x7E, 0x7E, "reserved bits"); + let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64; + let ext = ((b[4] & 1) as i64) << 8 | b[5] as i64; + assert!(ext < 300); + pcrs.push(base * 300 + ext); + } + if len > 1 { + assert!(p[6 + if p[5] & 0x10 != 0 { 6 } else { 0 }..5 + len].iter().all(|&b| b == 0xFF), "stuffing bytes"); + } + } + } + let wrap = (1i64 << 33) * 300; + for w in pcrs.windows(2) { + let d = (w[1] - w[0]).rem_euclid(wrap); + assert!(d > 0 && d <= limit, "PCRs {} apart (limit {limit})", d); + } + pcrs +} diff --git a/crates/media/tests/mpegts_mux_fuzz.rs b/crates/media/tests/mpegts_mux_fuzz.rs new file mode 100644 index 000000000..61cb3ee01 --- /dev/null +++ b/crates/media/tests/mpegts_mux_fuzz.rs @@ -0,0 +1,229 @@ +//! Random programs, frames and timelines: the packet layer stays valid, and every frame reads back +//! with the demuxer, across random idle gaps and output swaps. Random bytes for every codec never +//! panic. +// Test code: a failed unwrap is a failed test. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod mpegts_mux; + +use craft_media::mpegts; +use craft_media::mpegts::mux::{Av1Config, Codec, Config, Error, Frame, MAX_PCR_DELAY, MAX_PCR_INTERVAL, Muxer, OpusMapping, OpusTrim, Stream}; +use mpegts_mux::*; +use proptest::prelude::*; + +/// One step of a plan: (stream, size, DTS step, PTS offset, key, idle time before it, cut before +/// it: 0 none, 1 a new segment, 2 a continuing swap). +type Step = (usize, usize, i64, i64, bool, Option, u8); + +#[derive(Debug, Clone)] +struct Plan { + pcr_interval: u32, + pcr_own: bool, + pcr_delay: u32, + psi_interval: u32, + psi_before_keyframes: bool, + batch_packets: u16, + hold_packets: bool, + frames: Vec, +} + +/// The streams of the read-back property, in the order of `Step`'s stream index. +const STREAMS: usize = 8; + +fn plan() -> impl Strategy { + let step = (0usize..STREAMS, 1usize..4000, 1i64..12_000, 0i64..9000, any::(), prop::option::weighted(0.2, 0i64..40_000), 0u8..3); + ( + 1u32..=MAX_PCR_INTERVAL, + any::(), + 1u32..=MAX_PCR_DELAY, + 1u32..200_000, + any::(), + 1u16..400, + any::(), + prop::collection::vec(step, 5..60), + ) + .prop_map(|(pcr_interval, pcr_own, pcr_delay, psi_interval, psi_before_keyframes, batch_packets, hold_packets, frames)| Plan { + pcr_interval, + pcr_own, + pcr_delay, + psi_interval, + psi_before_keyframes, + batch_packets, + hold_packets, + frames, + }) +} + +/// A frame of stream `s` and the bytes the demuxer gives back for it. +fn frame(s: usize, size: usize, key: bool, n: usize) -> (Vec, Vec) { + let seed = n as u8; + match s { + 0 => { + let d = h264(key, false, size.max(30), seed); + let e = with_aud(Codec::H264, &d); + (d, e) + } + 1 => { + let mut d = vec![0xFC]; + fill(&mut d, size.min(1500), seed); + let e = opus_unit(&d); + (d, e) + } + 2 => { + let mut d = Vec::new(); + fill(&mut d, size.min(2000), seed); + let len = d.len() + 7; + let mut e = vec![0xFF, 0xF1, 0x50, 0x40 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC]; + e.extend_from_slice(&d); + (d, e) + } + 3 => { + let d = hevc(key, size.max(40), seed); + let e = with_aud(Codec::Hevc, &d); + (d, e) + } + 4 => (ac3(seed), ac3(seed)), + 5 => (eac3(seed), eac3(seed)), + 6 => (mp3(false, seed), mp3(false, seed)), + _ => { + let d = mpeg2(key, (n % 1024) as u16, size.max(40), seed); + (d.clone(), d) + } + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn random_programs_read_back(p in plan()) { + let streams = [ + Stream::new(0x100, Codec::H264), + Stream::new(0x101, Codec::Opus { channels: 2 }), + Stream::new(0x102, Codec::Aac { object_type: 2, sample_rate_index: 4, channels: 1 }), + Stream::new(0x103, Codec::Hevc), + Stream::new(0x104, Codec::Ac3), + Stream::new(0x105, Codec::Eac3), + Stream::new(0x106, Codec::MpegAudio { low_sample_rate: false }), + Stream::new(0x107, Codec::Mpeg2Video), + ]; + let cfg = Config { + pcr_interval: p.pcr_interval, + pcr_pid: p.pcr_own.then_some(0x1F0), + pcr_delay: p.pcr_delay, + psi_interval: p.psi_interval, + psi_before_keyframes: p.psi_before_keyframes, + batch_packets: p.batch_packets, + hold_packets: p.hold_packets, + ..Config::default() + }; + let mut m = Muxer::new(Vec::new(), cfg, &streams).unwrap(); + let mut t = 100_000i64; + let mut want: [Vec<(Vec, i64, i64)>; STREAMS] = Default::default(); + let mut segments = Vec::new(); + let mut restarted = false; + for (n, &(s, size, step, offset, key, idle, cut)) in p.frames.iter().enumerate() { + if let Some(idle) = idle { + // an idle gap that ends no later than the next frame's DTS + m.advance(t + idle.min(step)).unwrap(); + } + t += step; + match cut { + 1 => { + segments.push((true, m.replace_writer(Vec::new()))); + restarted = true; + } + 2 => segments.push((false, m.replace_writer_continuing(Vec::new()))), + _ => {} + } + let (data, expect) = frame(s, size, key, n); + let pts = if matches!(s, 0 | 3 | 7) { t + offset } else { t }; + m.write_frame(s, &Frame { data: &data, pts, dts: Some(t), key }).unwrap(); + want[s].push((expect, pts, t)); + } + let pcr_pid = m.pcr_pid(); + m.flush().unwrap(); + let stats = m.stats(); + let last = m.finish().unwrap(); + // an output that follows `replace_writer` starts with the PAT + let mut parts: Vec> = Vec::new(); + let mut fresh = false; + for (restart, seg) in segments { + prop_assert!(seg.error.is_none()); + prop_assert_eq!(seg.writer.len() as u64, seg.packets * 188); + if fresh && !seg.writer.is_empty() { + prop_assert_eq!((seg.writer[1] & 0x1F, seg.writer[2]), (0, 0)); + } + fresh = restart; + parts.push(seg.writer); + } + if fresh && !last.is_empty() { + prop_assert_eq!((last[1] & 0x1F, last[2]), (0, 0)); + } + parts.push(last); + let ts = parts.concat(); + prop_assert_eq!(ts.len() as u64, stats.bytes()); + if stats.pcr_gaps == 0 && !restarted { + check_packets(&ts, pcr_pid, i64::from(p.pcr_interval) * 300); + } + let file = mpegts::open(&ts).unwrap(); + prop_assert!(file.warnings.is_empty(), "{:?}", file.warnings); + for (k, w) in want.iter().enumerate() { + let units = &file.streams[k].units; + prop_assert_eq!(units.len(), w.len(), "stream {}", k); + for (n, (u, (bytes, pts, dts))) in units.iter().zip(w).enumerate() { + prop_assert_eq!(u.pts, Some(*pts)); + prop_assert_eq!(u.dts.or(u.pts), Some(*dts)); + prop_assert_eq!(&file.read_unit(&ts, k, n).unwrap(), bytes); + } + } + } + + #[test] + fn random_bytes_never_panic( + codec in 0usize..14, + frames in prop::collection::vec((prop::collection::vec(any::(), 0..3000), any::(), prop::option::of(any::()), any::(), any::(), any::()), 1..30), + interval in 0u32..20_000, + ) { + let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + let mapped = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }; + let codec = [ + Codec::H264, + Codec::Hevc, + Codec::Mpeg2Video, + Codec::AacAdts, + Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }, + Codec::Opus { channels: 2 }, + Codec::Ac3, + Codec::MpegAudio { low_sample_rate: false }, + Codec::MpegAudio { low_sample_rate: true }, + Codec::Mpeg1Video, + Codec::Mpeg4Part2, + Codec::Av1(av1), + Codec::Eac3, + Codec::OpusMapped(mapped), + ][codec]; + let cfg = Config { pcr_interval: interval, ..Config::default() }; + let Ok(mut m) = Muxer::new(Vec::new(), cfg, &[Stream::new(0x100, codec)]) else { + prop_assert!(interval == 0 || interval > MAX_PCR_INTERVAL); + return Ok(()); + }; + for (n, (data, pts, dts, key, start, end)) in frames.iter().enumerate() { + let trim = if n % 3 == 0 { OpusTrim { start: *start, end: *end } } else { OpusTrim::default() }; + match m.write_frame_with_trim(0, &Frame { data, pts: *pts, dts: *dts, key: *key }, trim) { + Ok(()) | Err(Error::BadFrame(_) | Error::EmptyFrame | Error::Timestamp(_) | Error::FrameTooLarge { .. }) => {} + Err(e) => prop_assert!(false, "{e}"), + } + let _ = m.advance(*pts); + if n % 7 == 6 { + m.discontinuity(); + } + } + let ts = m.finish().unwrap(); + prop_assert_eq!(ts.len() % 188, 0); + // the demuxer recognizes a transport stream by five sync bytes in a row + if ts.len() >= 5 * 188 { + prop_assert!(mpegts::open(&ts).is_ok()); + } + } +} diff --git a/crates/media/tests/mpegts_mux_readback.rs b/crates/media/tests/mpegts_mux_readback.rs new file mode 100644 index 000000000..ba2d70956 --- /dev/null +++ b/crates/media/tests/mpegts_mux_readback.rs @@ -0,0 +1,356 @@ +//! The transport stream writer's output read back with the demuxer: streams, codecs, every +//! frame's bytes and timestamps, keyframes, the PCR, and no continuity or CRC warnings. +// Test code: a failed unwrap is a failed test. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod mpegts_mux; + +use craft_media::mpegts::mux::{Av1Config, Codec, Config, Error, Frame, MAX_PCR_INTERVAL, Muxer, OpusMapping, Stream}; +use craft_media::mpegts::{self, Codec as Demuxed, StreamId}; +use mpegts_mux::*; + +const DELAY: i64 = 63_000; + +/// Muxes `items`, reads the file back and compares every unit. Returns the file and the PCRs. +fn round_trip(cfg: Config, streams: &[Stream], items: &mut [Item], want: &[Demuxed]) -> (Vec, Vec) { + let mut m = Muxer::new(Vec::new(), cfg, streams).unwrap(); + write_all(&mut m, items); + let pcr_pid = m.pcr_pid(); + let stats = m.stats(); + let ts = m.finish().unwrap(); + assert_eq!(stats.bytes(), ts.len() as u64); + assert_eq!(stats.frames, items.len() as u64); + let pcrs = check_packets(&ts, pcr_pid, i64::from(cfg.pcr_interval) * 300); + + let file = mpegts::open(&ts).unwrap(); + assert_eq!(file.format, mpegts::Format::Ts { packet_size: 188, sync_offset: 0 }); + assert!(file.warnings.is_empty(), "{:?}", file.warnings); + assert_eq!(file.program, Some(cfg.program_number)); + assert_eq!(file.streams.len(), streams.len()); + assert!(file.pcr_range.is_some()); + for (s, (st, codec)) in file.streams.iter().zip(streams.iter().zip(want)) { + assert_eq!(s.id, StreamId::Pid(st.pid)); + assert_eq!(&s.codec, codec, "PID {:#x}", st.pid); + assert_eq!(s.stream_type, st.codec.stream_type()); + assert_eq!(s.language, st.language.map(|l| String::from_utf8(l.to_vec()).unwrap())); + } + for (k, _) in streams.iter().enumerate() { + let mine: Vec<&Item> = items.iter().filter(|i| i.stream == k).collect(); + let units = &file.streams[k].units; + assert_eq!(units.len(), mine.len(), "stream {k}"); + for (n, (u, i)) in units.iter().zip(&mine).enumerate() { + assert_eq!(u.pts, Some(i.pts), "stream {k} unit {n}"); + assert_eq!(u.dts.or(u.pts), Some(i.dts), "stream {k} unit {n}"); + if streams[k].codec.is_video() && !matches!(want[k], Demuxed::Unknown(_)) { + assert_eq!(u.key, i.key, "stream {k} unit {n}"); + } + assert_eq!(file.read_unit(&ts, k, n).unwrap(), i.expect, "stream {k} unit {n}"); + } + } + (ts, pcrs) +} + +#[test] +fn every_codec_in_one_program() { + let streams = [ + Stream::new(0x100, Codec::H264), + Stream::new(0x101, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }).with_language(*b"eng"), + Stream::new(0x102, Codec::Opus { channels: 2 }).with_language(*b"deu"), + Stream::new(0x103, Codec::Ac3), + Stream::new(0x104, Codec::MpegAudio { low_sample_rate: false }), + ]; + let mut items = Vec::new(); + let t0 = 90_000; + for k in 0..90i64 { + // decode order I P B B P B B ...: P pictures shown 3 frames later, B pictures 1 later + let key = k % 30 == 0; + let (disposable, show) = match k % 3 { + 0 => (false, 3), + _ => (true, 1), + }; + let size = if key { 9000 } else { 300 + (k as usize * 37) % 2000 }; + let data = h264(key, disposable && !key, size, k as u8); + let dts = t0 + k * 3000; + items.push(Item { stream: 0, expect: with_aud(Codec::H264, &data), data, pts: dts + show * 3000, dts, key }); + } + for k in 0..140i64 { + let raw = { + let mut v = Vec::new(); + fill(&mut v, 200 + (k as usize * 13) % 600, k as u8); + v + }; + let mut expect = adts(0, 0)[..7].to_vec(); + let len = raw.len() + 7; + expect[3] = 0x80 | (len >> 11) as u8; + expect[4] = (len >> 3) as u8; + expect[5] = ((len & 7) as u8) << 5 | 0x1F; + expect.extend_from_slice(&raw); + items.push(Item { stream: 1, data: raw, pts: t0 + k * 1920, dts: t0 + k * 1920, key: true, expect }); + } + for k in 0..150i64 { + let mut p = vec![0xFC]; + fill(&mut p, 1 + (k as usize * 41) % 700, k as u8); + items.push(Item { stream: 2, expect: opus_unit(&p), data: p, pts: t0 + k * 1800, dts: t0 + k * 1800, key: true }); + } + for k in 0..90i64 { + let f = ac3(k as u8); + items.push(Item { stream: 3, expect: f.clone(), data: f, pts: t0 + k * 2880, dts: t0 + k * 2880, key: true }); + } + for k in 0..120i64 { + let f = mp3(false, k as u8); + items.push(Item { stream: 4, expect: f.clone(), data: f, pts: t0 + k * 2160, dts: t0 + k * 2160, key: true }); + } + let want = [Demuxed::H264, Demuxed::AacAdts, Demuxed::Unknown(6), Demuxed::Ac3, Demuxed::MpegAudio]; + let (ts, pcrs) = round_trip(Config::default(), &streams, &mut items, &want); + let file = mpegts::open(&ts).unwrap(); + assert_eq!(file.pcr_range, Some((pcrs[0], *pcrs.last().unwrap()))); + assert_eq!(pcrs[0], (t0 - DELAY) * 300); + // the frames' own headers read back with the demuxer's frame parser + let aac = file.read_unit(&ts, 1, 0).unwrap(); + assert_eq!(mpegts::frame_info(&Demuxed::AacAdts, &aac).map(|i| (i.sample_rate, i.channels)), Some((48_000, 2))); +} + +#[test] +fn hevc_with_adts_and_a_pcr_pid_of_its_own() { + let streams = [Stream::new(0x1FFE, Codec::Hevc), Stream::new(0x0010, Codec::AacAdts)]; + let cfg = Config { pcr_pid: Some(0x0011), pcr_interval: MAX_PCR_INTERVAL, psi_interval: 45_000, ..Config::default() }; + let mut items = Vec::new(); + for k in 0..60i64 { + let key = k % 20 == 0; + let data = hevc(key, if key { 20_000 } else { 700 }, k as u8); + let t = 70_000 + k * 3003; + items.push(Item { stream: 0, expect: with_aud(Codec::Hevc, &data), data, pts: t, dts: t, key }); + } + for k in 0..95i64 { + let f = adts(150 + k as usize, k as u8); + let t = 70_000 + k * 1920; + items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); + } + let (ts, _) = round_trip(cfg, &streams, &mut items, &[Demuxed::Hevc, Demuxed::AacAdts]); + let file = mpegts::open(&ts).unwrap(); + assert!(file.pcr_range.is_some(), "the demuxer reads the PCR from the PMT's PCR_PID"); +} + +#[test] +fn mpeg2_video_and_low_rate_mpeg_audio() { + let streams = [Stream::new(0x200, Codec::Mpeg2Video), Stream::new(0x201, Codec::MpegAudio { low_sample_rate: true })]; + let mut items = Vec::new(); + for k in 0..50i64 { + let key = k % 12 == 0; + let data = mpeg2(key, (k % 12) as u16, if key { 4000 } else { 900 }, k as u8); + let t = 100_000 + k * 3600; + items.push(Item { stream: 0, expect: data.clone(), data, pts: t, dts: t, key }); + } + for k in 0..70i64 { + let f = mp3(true, k as u8); + let t = 100_000 + k * 2160; + items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); + } + round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg2Video, Demuxed::MpegAudio]); +} + +#[test] +fn timestamps_run_past_the_33_bit_wrap() { + let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Opus { channels: 1 })]; + let start = (1i64 << 33) - 90_000; + let mut items = Vec::new(); + for k in 0..90i64 { + let data = h264(k == 0, false, 500, k as u8); + let t = start + k * 3000; + items.push(Item { stream: 0, expect: with_aud(Codec::H264, &data), data, pts: t, dts: t, key: k == 0 }); + } + for k in 0..140i64 { + let p = vec![0x08, k as u8 | 1, 0x55]; + let t = start + k * 1800; + items.push(Item { stream: 1, expect: opus_unit(&p), data: p, pts: t, dts: t, key: true }); + } + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264, Demuxed::Unknown(6)]); +} + +#[test] +fn eac3_mpeg1_video_and_mpeg4_part2() { + let streams = + [Stream::new(0x100, Codec::Mpeg1Video), Stream::new(0x101, Codec::Eac3).with_language(*b"spa"), Stream::new(0x102, Codec::Mpeg4Part2)]; + let mut items = Vec::new(); + for k in 0..50i64 { + let key = k % 12 == 0; + let data = mpeg2(key, (k % 12) as u16, if key { 4000 } else { 900 }, k as u8); + let t = 100_000 + k * 3600; + items.push(Item { stream: 0, expect: data.clone(), data, pts: t, dts: t, key }); + let data = mpeg4(key, if key { 3000 } else { 600 }, k as u8); + items.push(Item { stream: 2, expect: data.clone(), data, pts: t, dts: t, key }); + } + for k in 0..60i64 { + let f = eac3(k as u8); + let t = 100_000 + k * 2880; + items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); + } + round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg1Video, Demuxed::Eac3, Demuxed::Unknown(0x10)]); +} + +#[test] +fn av1_reads_back_as_its_obus() { + let config = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + let streams = [Stream::new(0x100, Codec::Av1(config)), Stream::new(0x101, Codec::Opus { channels: 2 })]; + let mut tus = Vec::new(); + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + for k in 0..60i64 { + let key = k % 30 == 0; + let tu = av1(key, if key { 20_000 } else { 300 + (k as usize * 113) % 3000 }, k as u8); + let t = 90_000 + k * 3000; + m.write_frame(0, &Frame { data: &tu, pts: t, dts: None, key }).unwrap(); + m.write_frame(1, &Frame { data: &[0xFC, k as u8 | 1], pts: t, dts: None, key: true }).unwrap(); + tus.push((tu, t)); + } + let ts = m.finish().unwrap(); + check_packets(&ts, 0x100, 3600 * 300); + let file = mpegts::open(&ts).unwrap(); + assert!(file.warnings.is_empty(), "{:?}", file.warnings); + assert_eq!(file.streams[0].codec, Demuxed::Unknown(6)); + assert_eq!(file.streams[0].stream_type, 0x06); + let units = &file.streams[0].units; + assert_eq!(units.len(), tus.len()); + for (n, (u, (tu, t))) in units.iter().zip(&tus).enumerate() { + assert_eq!(u.pts, Some(*t)); + let es = file.read_unit(&ts, 0, n).unwrap(); + assert_eq!(av1_unescape(&es), av1_without_delimiters(tu), "unit {n}"); + } +} + +#[test] +fn opus_with_an_explicit_mapping_and_trims() { + let mapping = OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [0, 1, 2, 0, 0, 0, 0, 0] }; + let streams = [Stream::new(0x100, Codec::OpusMapped(mapping))]; + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + let mut want = Vec::new(); + for k in 0..20i64 { + // three streams of 20 ms: two self-delimited packets, then the last one + let au = [0xFC, 1, 0x55, 0xFC, 1, 0x66, 0xFC, 0x77]; + let trim = if k == 0 { craft_media::mpegts::mux::OpusTrim { start: 312, end: 0 } } else { Default::default() }; + let t = 90_000 + k * 1800; + m.write_frame_with_trim(0, &Frame { data: &au, pts: t, dts: None, key: true }, trim).unwrap(); + let mut unit = if k == 0 { vec![0x7F, 0xF0, 8] } else { vec![0x7F, 0xE0, 8] }; + if k == 0 { + unit.extend_from_slice(&312u16.to_be_bytes()); + } + unit.extend_from_slice(&au); + want.push(unit); + } + let ts = m.finish().unwrap(); + let file = mpegts::open(&ts).unwrap(); + assert!(file.warnings.is_empty(), "{:?}", file.warnings); + assert_eq!(file.streams[0].units.len(), want.len()); + for (n, w) in want.iter().enumerate() { + assert_eq!(&file.read_unit(&ts, 0, n).unwrap(), w); + } +} + +#[test] +fn a_discontinuity_reads_back_in_both_time_bases() { + let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)]; + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + let mut want: [Vec<(Vec, i64)>; 2] = Default::default(); + for (part, start) in [(0, 900_000i64), (1, 200_000)] { + if part == 1 { + m.discontinuity(); + } + for k in 0..30i64 { + let data = h264(k == 0, false, 400, k as u8); + let t = start + k * 3000; + m.write_frame(0, &Frame { data: &data, pts: t, dts: None, key: k == 0 }).unwrap(); + want[0].push((with_aud(Codec::H264, &data), t)); + let f = adts(100, k as u8); + m.write_frame(1, &Frame { data: &f, pts: t, dts: None, key: true }).unwrap(); + want[1].push((f, t)); + } + } + let ts = m.finish().unwrap(); + let file = mpegts::open(&ts).unwrap(); + for (k, w) in want.iter().enumerate() { + let units = &file.streams[k].units; + assert_eq!(units.len(), w.len(), "stream {k}"); + for (n, (u, (bytes, t))) in units.iter().zip(w).enumerate() { + assert_eq!(u.pts.map(|p| p.rem_euclid(1 << 33)), Some(*t), "stream {k} unit {n}"); + assert_eq!(&file.read_unit(&ts, k, n).unwrap(), bytes, "stream {k} unit {n}"); + } + } +} + +/// An output that fails on its third write call. +struct Flaky { + fail_on: Option, + calls: usize, + data: Vec, +} + +impl std::io::Write for Flaky { + fn write(&mut self, b: &[u8]) -> std::io::Result { + self.calls += 1; + if Some(self.calls) == self.fail_on { + return Err(std::io::Error::other("upload failed")); + } + self.data.extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[test] +fn the_output_after_an_io_error_reads_on_its_own() { + let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)]; + let mut m = Muxer::new(Flaky { fail_on: Some(3), calls: 0, data: Vec::new() }, Config::default(), &streams).unwrap(); + let mut after = [0usize; 2]; + let mut failed = false; + for k in 0..60i64 { + let t = 90_000 + k * 3000; + let data = h264(k % 30 == 0, false, 2000, k as u8); + for (s, frame) in + [(0, Frame { data: &data, pts: t, dts: None, key: k % 30 == 0 }), (1, Frame { data: &ac3(k as u8), pts: t, dts: None, key: true })] + { + match m.write_frame(s, &frame) { + Ok(()) if failed => after[s] += 1, + Ok(()) => {} + Err(Error::Io(_)) if !failed => { + failed = true; + m.replace_writer(Flaky { fail_on: None, calls: 0, data: Vec::new() }); + } + Err(e) => panic!("{e}"), + } + } + } + assert!(failed); + let ts = m.finish().unwrap().data; + let file = mpegts::open(&ts).unwrap(); + assert!(file.warnings.is_empty(), "{:?}", file.warnings); + // every frame written after the error reads back + assert_eq!(file.streams[1].units.len(), after[1]); + assert_eq!(file.streams[0].units.len(), after[0]); +} + +#[test] +fn a_single_frame_and_a_huge_one() { + let streams = [Stream::new(0x100, Codec::H264)]; + // 1000 bytes: the demuxer needs five packets in a row to recognize the file + let one = h264(true, false, 1000, 1); + let mut items = vec![Item { stream: 0, expect: with_aud(Codec::H264, &one), data: one, pts: 90_000, dts: 90_000, key: true }]; + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264]); + // past PES_packet_length's 65 535 bytes: an unbounded video PES packet + let big = h264(true, false, 3_000_000, 2); + let small = h264(false, false, 100, 3); + let mut items = vec![ + Item { stream: 0, expect: with_aud(Codec::H264, &big), data: big, pts: 90_000, dts: 90_000, key: true }, + Item { stream: 0, expect: with_aud(Codec::H264, &small), data: small, pts: 93_000, dts: 93_000, key: false }, + ]; + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264]); +} + +#[test] +#[should_panic(expected = "PCR flag in an adaptation field of 1 byte")] +fn the_packet_checker_refuses_a_pcr_flag_in_a_short_adaptation_field() { + // adaptation_field_length 1 holds only the flags byte, so the six bytes after it are payload + let mut p = vec![0x7E; 188]; + p[..6].copy_from_slice(&[0x47, 0x01, 0x00, 0x30, 0x01, 0x10]); + check_packets(&p, 0x100, 3600 * 300); +}