craft-media: mpegts::mux writes MPEG-2 transport streams frame by frame to any io::Write (#1998)

* craft-media: mpegts::mux writes MPEG-2 transport streams frame by frame to any io::Write

The mpegts feature gains a transport stream writer (ITU-T H.222.0 |
ISO/IEC 13818-1) next to the demuxer:

- PAT and PMT with the CRC-32 the demuxer checks (ts::crc32_mpeg), at
  the start, every psi_interval, directly before video keyframes, and
  after replace_writer and discontinuity; a PMT longer than one packet
  spans packets.
- One PES packet per frame for H.264, HEVC, MPEG-1, MPEG-2 and MPEG-4
  Part 2 video, AV1 (Carriage of AV1 in MPEG-2 TS), AAC (ADTS, or raw
  frames given an ADTS header), Opus (Opus transport draft V0.1.3,
  including explicit channel mappings and trims), AC-3, E-AC-3 and MPEG
  audio, with PTS and DTS modulo 2^33.
- The PCR on a stream's PID or its own, at most pcr_interval apart
  (100 ms at most), PCR-only packets in gaps, advance() for idle live
  outputs, continuity counters, random access and discontinuity
  indicators.
- Packets go out in batches of batch_packets (7 by default) built in
  fixed buffers; replace_writer returns per-segment facts.
- Frames are checked before anything is written; video frames are
  limited to MAX_UNIT_BYTES so the demuxer reads every one back.

Tests read every codec back with the demuxer (bytes, PTS, DTS, keyframes,
PCR range, no continuity or CRC warnings), check the PES header bits and
the refusals, and fuzz programs, timelines, idle gaps and output swaps.

* craft-media: mpegts::mux leaves out zero-ended AV1 padding and refuses 960-sample AAC configs

An AV1 padding OBU that ends with a zero byte, an empty one included, is
now left out like a temporal delimiter instead of failing the whole
temporal unit. Decoders ignore padding, and the trailing zero would
otherwise form a forbidden sequence with the next start code.

Codec::aac_from_asc refuses an AudioSpecificConfig with frameLengthFlag 1:
an ADTS header has no field for 960-sample frames, so decoders would read
the stream as 1024-sample frames.

* craft-media: the transport stream packet checker refuses a PCR flag in an adaptation field shorter than seven bytes

* craft-media: README states the multistream layout for 3 to 8 channel Opus

An Opus { channels } access unit is one Opus packet for 1 or 2 channels.
For 3 to 8 channels it holds the mapping family 1 streams in the order
of table 4-3 of the Opus transport draft, every stream but the last
self-delimited (RFC 6716 Appendix B). The README now says so, matching
the Codec::Opus doc comment.
This commit is contained in:
.CooCoo
2026-11-18 23:26:00 -05:00
committed by GitHub
parent 2e6f11eabb
commit 7aaa2f8010
12 changed files with 3918 additions and 6 deletions
+11 -2
View File
@@ -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"]
+115 -3
View File
@@ -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):
+1 -1
View File
@@ -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.
+2
View File
@@ -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;
+232
View File
@@ -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<Obu, Error> {
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<usize, Error> {
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<u8> {
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<u8> {
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");
}
}
File diff suppressed because it is too large Load Diff
+389
View File
@@ -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<u32> {
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<i64>) -> 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(&timestamp(3, pts));
out[14..19].copy_from_slice(&timestamp(1, dts));
19
}
None => {
out[7] = 0x80;
out[8] = 5;
out[9..14].copy_from_slice(&timestamp(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<u8> {
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<Prepared, Error> {
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<usize, Error> {
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(&timestamp(2, WRAP_90K + 5)), 5, "wraps at 2^33");
assert_eq!(read(&timestamp(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<u8> {
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());
}
}
+216
View File
@@ -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<u8>) -> Result<Vec<u8>, 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<Vec<u8>, 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<Vec<u8>, 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<u8>) {
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<Stream> = (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<u8> {
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']);
}
}
+915
View File
@@ -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<i64>,
}
fn walk(ts: &[u8]) -> Vec<Pk> {
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<u8> {
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<u8>>)) -> Vec<u8> {
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<u16, u8> = 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<i64> = 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<i64> = 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<Pk> = 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<i64> = 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<usize> = 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<i64>) -> 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<Stream> = (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<Stream> = (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::<Vec<_>>(), [0, 1, 2, 3]);
let mut section: Vec<u8> =
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(&section), 0);
}
/// An output that records the length of every write call.
#[derive(Clone, Default)]
struct Calls(Rc<RefCell<Vec<usize>>>);
impl Write for Calls {
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
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<u8>, 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::<usize>() 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<i64> = 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<u16, Vec<(bool, Vec<u8>)>> {
let mut out: std::collections::HashMap<u16, Vec<(bool, Vec<u8>)>> = 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<usize>,
calls: usize,
data: Vec<u8>,
}
impl Write for Flaky {
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
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<u16, u8> = 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<u8>,
}
impl Write for Short {
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
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);
}
+260
View File
@@ -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<u8>,
pub pts: i64,
pub dts: i64,
pub key: bool,
pub expect: Vec<u8>,
}
/// Writes `items` in DTS order (stable, so equal DTS keep their order).
pub fn write_all(m: &mut Muxer<Vec<u8>>, 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<u8> {
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<u8> {
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<u8> {
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<u8>, 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<u8> {
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<u8> {
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<u8> {
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<u8> {
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<u8> {
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<u8>) {
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<u8> {
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<u8> {
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<u8> {
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<u8> {
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<u8> {
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<i64> {
assert_eq!(ts.len() % PACKET_SIZE, 0);
let mut cc: HashMap<u16, u8> = 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
}
+229
View File
@@ -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<i64>, 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<Step>,
}
/// The streams of the read-back property, in the order of `Step`'s stream index.
const STREAMS: usize = 8;
fn plan() -> impl Strategy<Value = Plan> {
let step = (0usize..STREAMS, 1usize..4000, 1i64..12_000, 0i64..9000, any::<bool>(), prop::option::weighted(0.2, 0i64..40_000), 0u8..3);
(
1u32..=MAX_PCR_INTERVAL,
any::<bool>(),
1u32..=MAX_PCR_DELAY,
1u32..200_000,
any::<bool>(),
1u16..400,
any::<bool>(),
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<u8>, Vec<u8>) {
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<u8>, 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<u8>> = 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::<u8>(), 0..3000), any::<i64>(), prop::option::of(any::<i64>()), any::<bool>(), any::<u16>(), any::<u16>()), 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());
}
}
}
+356
View File
@@ -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<u8>, Vec<i64>) {
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<u8>, 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<usize>,
calls: usize,
data: Vec<u8>,
}
impl std::io::Write for Flaky {
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
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);
}