Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions kodecs-h264/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,25 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Changed

- **Breaking:** the parsers take what 0.1's did again: field pictures and MBAFF, 4:0:0 to 4:4:4, bit depths up
to 14, transform bypass, SP and SI slices, data partition A, levels Table A-1 lacks, and
streams over their level's DPB and side limits. `Sps` and `SliceHeader` carry the new fields,
and `SliceType` adds `Sp` and `Si`. See [MIGRATE.md](MIGRATE.md).
- **Breaking:** `Unit::Sps` and `Unit::Pps` carry the stored `Arc<Sps>` and `Arc<Pps>`, and
`Unit::Slice { nal, header, sps, pps }` its NAL header and the sets its header parsed against. `Parser::sps` and
`Parser::pps` return `&Arc`s.
- An SPS that can't read a stored PPS naming its id keeps the PPS for the next SPS that can,
rather than dropping it.

### Added

- `Sps::check_decoder_scope` refuses what a progressive 8-bit 4:2:0 decoder can't decode, which
the parsers no longer refuse for it. A decoder checks it on each slice's `Arc<Sps>`.

## [0.2.2]

### Added
Expand Down
67 changes: 67 additions & 0 deletions kodecs-h264/MIGRATE.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,72 @@
# Migrating kodecs-h264

## kodecs-h264 0.2 -> 0.3

The parsers take everything 0.1's parser did, so MPEG-TS import and other remuxers can read
field-coded, high bit depth, 4:2:2, and 4:4:4 streams again. A decoder that took 0.2's
refusals as its scope check now calls `Sps::check_decoder_scope()` on the SPS of each slice
it decodes: it returns `Unsupported` unless the sequence is progressive 8-bit 4:2:0 without
transform bypass, `Range` for a level Table A-1 lacks for the profile, and `Level` when the
frame's sides, `max_num_ref_frames`, or the VUI's `max_dec_frame_buffering` exceed the
level's limits. Hand the `Parser` every unit, refused sequences included, so its NAL budget
follows the sequence the stream sent. Cache the result by the slice's `Arc<Sps>` pointer
(`Arc::ptr_eq`), since the parser hands out a new `Arc` only when an SPS arrives, and refuse
the slice when it fails; decoding resumes once the stream sends an SPS inside the scope.
Also refuse `SliceType::Sp`, `SliceType::Si`, and data partition A (`NaluType::SliceDpa`)
slices if the decoder lacks them.

### Units carry their parameter sets

- `Unit::Sps` and `Unit::Pps` carry the `Arc<Sps>` and `Arc<Pps>` the parser stored, not
their ids. Read the id from the set (`sps.id`, `pps.id`).
- `Unit::Slice` is a struct variant, `Unit::Slice { nal, header, sps, pps }`, carrying the
NAL header, whose type tells data partition A from a whole slice, and the `Arc<Sps>` and
`Arc<Pps>` its header parsed against. Use those instead of looking the sets
up with `Parser::pps(header.pps_id)` and `Parser::sps(pps.sps_id)`, which a later unit may
have replaced; holding the `Arc`s also saves deep clones of the sets.
- `Parser::sps(id)` and `Parser::pps(id)` return `Option<&Arc<Sps>>` and
`Option<&Arc<Pps>>`, for inspection.
- An SPS that can't read a stored PPS naming its id, such as a 4:4:4 SPS and a PPS with
4:2:0 scaling lists, no longer drops it: `Parser::pps(id)` returns `None` and its slices
fail with `Missing` until an SPS that reads it arrives, so a stream returning to its
earlier sequence needn't resend the PPS.

### What the parsers take

- `Sps::parse` and `Parser` take `frame_mbs_only_flag` 0 (field pictures and MBAFF),
`chroma_format_idc` 0 to 3 with separate colour planes, bit depths 8 to 14, and
`qpprime_y_zero_transform_bypass_flag`. They still refuse a frame larger than the level's
`MaxFS`, and a slice over its level's NAL size.
- A `level_idc` Table A-1 lacks for the profile is no longer `Range`: `Sps::limits` holds
level 6.2's limits for it.
- `max_num_ref_frames` above `MaxDpbFrames`, sides past `Sqrt(8 * MaxFS)`, and a VUI
`max_dec_frame_buffering` above `MaxDpbFrames` parse; `max_num_ref_frames` above 16 is still
`Level`.
- Slice headers of SP and SI slices, and of data partition A, parse. Partitions B and C, slice
groups, and the SVC and MVC extensions are still `Unsupported`.

### Fields

- `Sps` adds `chroma_format_idc`, `separate_colour_plane`, `bit_depth_luma`,
`bit_depth_chroma`, `transform_bypass`, `frame_mbs_only`, and `mb_adaptive_frame_field`, and
`chroma_array_type()`. `height_mbs` stays the frame's height, both fields included.
- `SliceHeader` adds `colour_plane_id`, `field_pic`, `bottom_field`, `sp_for_switch`, and
`slice_qs`. In a field, `delta_pic_order_cnt_bottom` and `delta_pic_order_cnt[1]` are 0, as
the syntax omits them; `num_ref_idx_l0_active` and `num_ref_idx_l1_active` go up to 32, and
`Marking::Adaptive` holds up to `4 * max_num_ref_frames + 3` operations.
- `SliceType` adds `Sp` and `Si`, and `SliceType::inter()` says whether a slice uses list 0.
- `slice_qp` and `Pps::pic_init_qp` go down to `-QpBdOffsetY`, -36 at 14 bits.
- `Matrix::lists_8x8` holds six lists, 384 entries, in a 4:4:4 sequence; the chroma ones fall
back to the list of their kind before them.
- `WeightTable::chroma_log2_denom` is 0, and each `Weight` carries the default chroma weights,
when `chroma_array_type()` is 0.

### Writing

`Sps::write` and `SliceHeader::write` write the new fields. A field-capable SPS needs an even
`height_mbs`, and crop offsets must be whole crop units of its chroma format and frame or field
coding. Builders still build progressive 8-bit 4:2:0.

## kodecs-h264 0.2.1 -> 0.2.2

`Nalu::next` and `Parser::next` skip an empty Annex B unit (such as one between
Expand Down
18 changes: 10 additions & 8 deletions kodecs-h264/README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# kodecs-h264

H.264 bitstream syntax for Rust: NAL units, sequence parameter sets with their
VUI and HRD, picture parameter sets, and slice headers, both parsed and written,
for progressive 8-bit 4:2:0 streams up to High profile.
VUI and HRD, picture parameter sets, and slice headers, both parsed and written.
The parsers take frames and fields (PAFF and MBAFF), 4:0:0 to 4:4:4, and bit
depths up to 14. `Sps::check_decoder_scope` tells a decoder whether a sequence
is progressive 8-bit 4:2:0 within its level.

- `Parser::new(max_bytes)` frames an Annex B stream (`next`) or takes one NAL
unit (`parse`), keeps the stream's parameter sets, and parses slice headers
against them. `Sps::parse` takes one SPS NAL unit, and `SpsMetadata::parse`
reads the catalog fields of any SPS, interlaced or high bit depth included.
against them, handing each slice the `Arc<Sps>` and `Arc<Pps>` it used. `Sps::parse` takes one SPS NAL unit, and `SpsMetadata::parse`
reads the catalog fields of any SPS, keeping them when its VUI is damaged.
- `SpsBuilder`, `PpsBuilder`, and `SliceHeaderBuilder` build what the parser
reads back. `Sps::write` and `Pps::write` append Annex B NAL units.
`SliceHeader::write` returns the count of padding bits at the end of the
Expand All @@ -16,11 +18,11 @@ for progressive 8-bit 4:2:0 streams up to High profile.
- `BitReader` reads the Exp-Golomb syntax H.264 and H.265 share, and `escape`
and `unescape` add and remove emulation prevention.

The parsers refuse malformed input, and input beyond its level's limits or the
supported scope, with an `Error`. Verus proves they stay within the bounds the
level sets. The
The parsers refuse malformed input, frames larger than their level allows, slice
groups, data partitions B and C, and the SVC and MVC extensions with an `Error`.
Verus proves they stay within the bounds the largest level sets. The
[fuzz target](https://github.com/moq-dev/kodecs/tree/main/kodecs-h264/fuzz)
checks that every SPS, PPS, and slice header that parses writes back to the same
values. [Migration notes](MIGRATE.md) cover the move from 0.1.
values. [Migration notes](MIGRATE.md) cover each breaking release.

Licensed under either of [Apache-2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT).
36 changes: 24 additions & 12 deletions kodecs-h264/src/fuzz.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! The fuzz target's body, which the tests also run over the fixtures.

use crate::{Nalu, NaluHeader, NaluType, Parser, Sps, SpsMetadata, Unit, escape, unescape};
use crate::{Nalu, NaluHeader, NaluType, Parser, Pps, SliceHeader, Sps, SpsMetadata, Unit, escape, unescape};

/// The raw NAL budget: larger than any level's, so the levels bound what parses.
const MAX_BYTES: usize = 1 << 24;
Expand All @@ -21,20 +21,34 @@ pub fn stream(data: &[u8]) {
let _ = SpsMetadata::parse(&raw, MAX_BYTES);
}
match parser.parse(&raw) {
Ok(Unit::Sps(id)) => sps(parser.sps(id).expect("stored")),
Ok(Unit::Pps(id)) => {
let pps = parser.pps(id).expect("stored");
Ok(Unit::Sps(sps)) => {
assert_eq!(parser.sps(sps.id), Some(&sps), "the SPS is stored");
self::sps(&sps)
}
Ok(Unit::Pps(pps)) => {
assert_eq!(parser.pps(pps.id), Some(&pps), "the PPS is stored");
let sps = parser.sps(pps.sps_id).expect("the PPS's SPS");
let mut check = Parser::new(MAX_BYTES);
let mut out = Vec::new();
sps.write(3, &mut out).expect("a parsed SPS writes");
pps.write(nal.header.ref_idc, &mut out).expect("a parsed PPS writes");
let mut written = &out[..];
check.next(&mut written).expect("the SPS reads back");
assert_eq!(check.next(&mut written), Ok(Some(Unit::Pps(id))), "the PPS reads back");
assert_eq!(check.pps(id), Some(pps), "the PPS round trips");
assert_eq!(
check.next(&mut written),
Ok(Some(Unit::Pps(pps))),
"the PPS round trips"
);
}
Ok(Unit::Slice {
nal: parsed,
header,
sps,
pps,
}) => {
assert_eq!(parsed, nal.header, "the slice keeps its NAL header");
slice(nal.header, header, &sps, &pps)
}
Ok(Unit::Slice(header)) => slice(&parser, nal.header, header),
Ok(Unit::Other(_)) | Err(_) => {}
}
}
Expand All @@ -50,9 +64,7 @@ fn sps(sps: &Sps) {
);
}

fn slice(parser: &Parser, nal: NaluHeader, header: crate::SliceHeader) {
let pps = parser.pps(header.pps_id).expect("the slice's PPS");
let sps = parser.sps(pps.sps_id).expect("the PPS's SPS");
fn slice(nal: NaluHeader, header: SliceHeader, sps: &Sps, pps: &Pps) {
let mut out = Vec::new();
let padding = header
.write(nal, sps, pps, &mut out)
Expand Down Expand Up @@ -80,10 +92,10 @@ fn slice(parser: &Parser, nal: NaluHeader, header: crate::SliceHeader) {
check.next(&mut sets).expect("the SPS reads back");
check.next(&mut sets).expect("the PPS reads back");
match check.parse(&written) {
Ok(Unit::Slice(reparsed)) => {
Ok(Unit::Slice { header: reparsed, .. }) => {
assert_eq!(reparsed.header_bit_size, bits, "the header ends where the writer says");
// An unneeded override or weight flag in the input changes the size, not the values.
let without_size = |mut h: crate::SliceHeader| {
let without_size = |mut h: SliceHeader| {
h.header_bit_size = 0;
h
};
Expand Down
31 changes: 22 additions & 9 deletions kodecs-h264/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
#![warn(missing_docs)]

//! H.264 bitstream syntax for progressive 8-bit 4:2:0 streams: NAL units, sequence parameter
//! sets with their VUI and HRD, picture parameter sets, and slice headers, read and written.
//! H.264 bitstream syntax: NAL units, sequence parameter sets with their VUI and HRD, picture
//! parameter sets, and slice headers, read and written.
//!
//! Section numbers refer to ITU-T H.264 (08/2024). Parsing refuses malformed input, and input
//! beyond its level's limits or the supported scope, with an [`Error`] instead of panicking,
//! since a bitstream is untrusted. [`SpsMetadata`] reads catalog fields from any SPS,
//! interlaced and high bit depth included.
//! Section numbers refer to ITU-T H.264 (08/2024). The parsers take frames and fields (PAFF and
//! MBAFF), 4:0:0 to 4:4:4, and bit depths up to 14, as timestamp derivation and remuxing need.
//! They refuse malformed input, frames larger than their level allows, slice groups, data
//! partitions B and C, and the SVC and MVC extensions with an [`Error`] instead of panicking,
//! since a bitstream is untrusted.
//! [`Sps::check_decoder_scope`] tells a decoder whether a sequence is progressive 8-bit 4:2:0
//! within its level. [`SpsMetadata`] reads catalog fields from any SPS, keeping them when its
//! VUI is damaged.
//!
//! ```
//! // libx264's Constrained Baseline SPS for 64x64 pictures at 30 fps.
Expand All @@ -33,12 +37,21 @@ pub use syntax::*;
mod tests {
use super::*;

/// The streams under `tests/data`, from libx264 and openh264.
pub(crate) const FIXTURES: [&str; 6] = [
/// The streams under `tests/data`: from libx264 and openh264, and the headers of a 1080i
/// broadcast capture, `kyrion_1080i_headers.h264`, whose slices keep 40 bytes each.
pub(crate) const FIXTURES: [&str; 14] = [
"bframes_64x64_pattern_30f.h264",
"gray_64x64_4f.h264",
"high10_64x64_6f.h264",
"high422_interlaced_64x64_6f.h264",
"high444_cqm_64x64_6f.h264",
"high444_lossless_64x64_2f.h264",
"idr_64x64_blue_2f.h264",
"kyrion_1080i_headers.h264",
"main_64x64_yellow_5f.h264",
"main_poc0_64x64_pattern_5f.h264",
"mbaff_64x64_8f.h264",
"overlevel_512x16_4f.h264",
"seq_100x66_pattern_5f.h264",
"seq_64x64_pattern_5f.h264",
];
Expand All @@ -52,7 +65,7 @@ mod tests {
let mut stream = &data[..];
let mut slices = 0;
while let Some(unit) = parser.next(&mut stream).unwrap() {
slices += usize::from(matches!(unit, Unit::Slice(_)));
slices += usize::from(matches!(unit, Unit::Slice { .. }));
}
assert!(slices > 0, "{name} holds slices");
}
Expand Down
3 changes: 2 additions & 1 deletion kodecs-h264/src/syntax/bits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ pub enum Error {
/// The stream needs more than its level allows (Table A-1).
#[cfg_attr(not(verus_keep_ghost), error("the stream exceeds its level's limits"))]
Level,
/// The stream uses a feature outside the decoder's scope.
/// The stream uses a feature the parser leaves out (slice groups, data partitions B and C, or
/// the SVC and MVC extensions), or that `Sps::check_decoder_scope` finds outside the decoder's.
#[cfg_attr(not(verus_keep_ghost), error("unsupported H.264 feature"))]
Unsupported,
/// A parameter set refers to one the parser has not seen.
Expand Down
2 changes: 1 addition & 1 deletion kodecs-h264/src/syntax/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! H.264 syntax for progressive, 8-bit 4:2:0 streams.
//! H.264 syntax: NAL units, parameter sets, and slice headers.

#[cfg(not(verus_keep_ghost))]
macro_rules! proof {
Expand Down
Loading