From 19f3903e74263efac29a1bc6dc27a458ab44a747 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 09:32:06 +0300 Subject: [PATCH] feat(h264): registry Decoder entry, avcC extradata, mechanism-named refusals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The NAL-level Decoder is what a bitstream tool wants; a demuxer wants packets. H264Decoder implements ec_core::registry::Decoder over the same decode core and adds the two things a container brings with it: parameter sets carried out of band in an avcC record (14496-15 clause 5.3.3.1), and NAL units framed by a length prefix instead of Annex B start codes. The framing is decided once, by whether extradata held an avcC, and the SPS inside it publishes the picture size before the first packet arrives. Every refusal's why-text now names the syntax element that fired and the machinery it would need, not just "not implemented" — the conformance suite proves each one against a stream that really uses the feature, so the text is the capability statement a caller reads. --- Cargo.toml | 1 + crates/ec-h264/Cargo.toml | 4 +- crates/ec-h264/src/cavlc.rs | 8 +- crates/ec-h264/src/codec.rs | 244 ++++++++++++++++++++++++++++++++++ crates/ec-h264/src/decoder.rs | 69 ++++++++-- crates/ec-h264/src/lib.rs | 22 +++ 6 files changed, 331 insertions(+), 17 deletions(-) create mode 100644 crates/ec-h264/src/codec.rs diff --git a/Cargo.toml b/Cargo.toml index c66dd591..913c8afa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ authors = ["Ahmet Kaan Gümüş"] ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" } ec-core = { path = "crates/ec-core", version = "0.1.0" } ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } +ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" } ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } ec-mp4 = { path = "crates/ec-mp4", version = "0.1.0" } diff --git a/crates/ec-h264/Cargo.toml b/crates/ec-h264/Cargo.toml index f3ea4c08..9fa92723 100644 --- a/crates/ec-h264/Cargo.toml +++ b/crates/ec-h264/Cargo.toml @@ -8,9 +8,9 @@ authors.workspace = true [dependencies] ec-core = { workspace = true } -ec-h264-syntax = { path = "../ec-h264-syntax", version = "0.1.0" } +ec-h264-syntax = { workspace = true } wide = { workspace = true } [dev-dependencies] # The conformance harness walks Annex B itself to drive push_nal. -ec-h264-syntax = { path = "../ec-h264-syntax", version = "0.1.0" } +ec-h264-syntax = { workspace = true } diff --git a/crates/ec-h264/src/cavlc.rs b/crates/ec-h264/src/cavlc.rs index be44e906..5cc2796f 100644 --- a/crates/ec-h264/src/cavlc.rs +++ b/crates/ec-h264/src/cavlc.rs @@ -43,7 +43,13 @@ fn read_coeff_token(r: &mut BitCursor<'_>, nc: i32) -> Result<(u8, u8)> { 0..=1 => COEFF_TOKEN_NC0, 2..=3 => COEFF_TOKEN_NC2, 4..=7 => COEFF_TOKEN_NC4, - _ => return Err(Error::unsupported("CAVLC nC = -2", "4:2:2 chroma DC")), + _ => { + return Err(Error::unsupported( + "CAVLC nC = -2", + "nC -2 is the 4:2:2 chroma DC coeff_token table (9.2.1); only \ + 4:2:0 chroma DC (nC -1) is decoded", + )); + } }; let peek = r.peek16(); for &(len, code, tc, t1) in table { diff --git a/crates/ec-h264/src/codec.rs b/crates/ec-h264/src/codec.rs new file mode 100644 index 00000000..d856fa64 --- /dev/null +++ b/crates/ec-h264/src/codec.rs @@ -0,0 +1,244 @@ +//! The [`ec_core::registry::Decoder`] entry path: packets in, frames out. +//! +//! [`crate::Decoder`] is the NAL-level surface a bitstream tool wants. This is +//! the surface a *player* wants, and it adds the two things a container brings +//! with it: parameter sets carried out of band in an `avcC` record +//! (ISO/IEC 14496-15 clause 5.3.3.1) and NAL units framed by a length prefix +//! rather than by Annex B start codes. Which framing a packet uses is decided +//! once, by whether `extradata` held an `avcC`. + +use std::collections::VecDeque; + +use ec_core::BitReader; +use ec_core::error::{Error, Result}; +use ec_core::frame::{Frame, PixelFormat}; +use ec_core::packet::Packet; +use ec_core::registry::{CodecId, CodecParameters, MediaParameters}; +use ec_core::timebase::Timestamp; +use ec_h264_syntax::AnnexBIter; + +use crate::decoder::{Decoder, NalOutcome}; + +/// H.264 decoder behind the codec registry's packet/frame contract. +pub struct H264Decoder { + params: CodecParameters, + inner: Decoder, + /// Bytes of the NAL length prefix when the stream is length framed; + /// `None` means Annex B start codes. + nal_length_size: Option, + frames: VecDeque, + pending_pts: Option, + end_of_stream: bool, +} + +impl H264Decoder { + /// A decoder for `params`. + /// + /// When `params.extradata` holds an `avcC` record its parameter sets are + /// read immediately — so [`H264Decoder::codec_parameters`] reports the + /// picture size before the first packet — and packets are then expected to + /// carry length-prefixed NAL units; otherwise packets are read as Annex B. + pub fn new(params: CodecParameters) -> Result { + if params.codec != CodecId::H264 { + return Err(Error::unsupported( + format!("codec {:?}", params.codec), + "this decoder implements H.264 only", + )); + } + let mut decoder = H264Decoder { + params, + inner: Decoder::new(), + nal_length_size: None, + frames: VecDeque::new(), + pending_pts: None, + end_of_stream: false, + }; + // 7 bytes is the shortest record that can hold the fixed header plus a + // parameter-set count; version 1 is the only one 14496-15 defines. + if let Some(extradata) = decoder.params.extradata.clone() + && extradata.len() >= 7 + && extradata[0] == 1 + { + decoder.parse_avcc(&extradata)?; + } + Ok(decoder) + } + + /// Read an `avcC` record: the NAL length size and the in-band parameter + /// sets (ISO/IEC 14496-15 clause 5.3.3.1). + fn parse_avcc(&mut self, extradata: &[u8]) -> Result<()> { + let mut r = BitReader::new(extradata); + // configurationVersion, AVCProfileIndication, profile_compatibility, + // AVCLevelIndication: all restated by the SPS below. + r.skip_bits(32)?; + let length_size_minus_one = r.read_bits(8)? & 0x03; + self.nal_length_size = Some(length_size_minus_one as usize + 1); + let num_sps = r.read_bits(8)? & 0x1F; + for _ in 0..num_sps { + let len = r.read_bits(16)? as usize; + let unit = r.read_bytes(len)?.to_vec(); + self.push(&unit)?; + } + let num_pps = r.read_bits(8)?; + for _ in 0..num_pps { + let len = r.read_bits(16)? as usize; + let unit = r.read_bytes(len)?.to_vec(); + self.push(&unit)?; + } + Ok(()) + } + + /// Split a packet into NAL units by whichever framing this stream uses. + fn decode_packet_payload(&mut self, data: &[u8]) -> Result<()> { + let Some(size) = self.nal_length_size else { + for unit in AnnexBIter::new(data) { + let unit = unit.to_vec(); + self.push(&unit)?; + } + return Ok(()); + }; + let mut offset = 0usize; + while offset + size <= data.len() { + let mut length = 0usize; + for i in 0..size { + length = (length << 8) | data[offset + i] as usize; + } + offset += size; + let end = offset + .checked_add(length) + .filter(|&end| end <= data.len()) + .ok_or_else(|| { + Error::corrupt(format!( + "H.264: a NAL unit of {length} bytes overruns the packet" + )) + })?; + let unit = data[offset..end].to_vec(); + self.push(&unit)?; + offset = end; + } + Ok(()) + } + + /// Feed one NAL unit, completing the open picture when it starts a new one. + fn push(&mut self, unit: &[u8]) -> Result<()> { + match self.inner.push_nal(unit)? { + NalOutcome::PictureBoundary => { + // The NAL was not consumed: it opens the next picture. + self.finish_picture()?; + self.inner.push_nal(unit)?; + } + NalOutcome::ParameterSet => self.sync_parameters(), + _ => {} + } + Ok(()) + } + + /// Emit the open picture, if there is one, as a frame. + fn finish_picture(&mut self) -> Result<()> { + if !self.inner.picture_open() { + return Ok(()); + } + self.inner.end_picture()?; + let mut frame = self.inner.frame()?; + frame.pts = self.pending_pts.take(); + self.frames.push_back(Frame::Video(frame)); + Ok(()) + } + + /// Publish the active SPS geometry on `params`, the way a demuxer that + /// only had an `avcC` expects to read it back. + fn sync_parameters(&mut self) { + let Some((width, height)) = self.inner.picture_size() else { + return; + }; + if let MediaParameters::Video(video) = &mut self.params.media { + video.width = width; + video.height = height; + video.format = Some(PixelFormat::I420); + } + } +} + +impl ec_core::registry::Decoder for H264Decoder { + fn codec_parameters(&self) -> &CodecParameters { + &self.params + } + + fn send_packet(&mut self, packet: &Packet) -> Result<()> { + self.end_of_stream = false; + self.pending_pts = packet + .pts + .map(|ticks| Timestamp::new(ticks, packet.time_base)); + self.decode_packet_payload(&packet.data)?; + // One packet is one access unit, so whatever picture it started is + // complete once the packet is consumed. + self.finish_picture() + } + + fn receive_frame(&mut self) -> Result { + match self.frames.pop_front() { + Some(frame) => Ok(frame), + None if self.end_of_stream => Err(Error::Eof), + None => Err(Error::NeedMore), + } + } + + fn flush(&mut self) -> Result<()> { + self.finish_picture()?; + self.end_of_stream = true; + Ok(()) + } + + fn reset(&mut self) { + // Parameter sets and the framing decision survive a seek; picture + // state does not. + self.inner.reset_pictures(); + self.frames.clear(); + self.pending_pts = None; + self.end_of_stream = false; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ec_core::TimeBase; + use ec_core::registry::Decoder as _; + + #[test] + fn only_h264_parameters_are_accepted() { + assert!(H264Decoder::new(CodecParameters::new(CodecId::H265)).is_err()); + let decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).unwrap(); + assert_eq!(decoder.codec_parameters().codec, CodecId::H264); + assert!(decoder.nal_length_size.is_none(), "Annex B by default"); + } + + #[test] + fn a_packet_without_parameter_sets_is_corrupt_not_a_panic() { + let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).unwrap(); + // A slice NAL with no SPS or PPS in front of it. + let stream = [0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x00]; + let packet = Packet::new(0, TimeBase::new(1, 25), stream.to_vec()); + let err = decoder.send_packet(&packet).unwrap_err(); + assert!(matches!(err, Error::Corrupt { .. }), "{err}"); + assert!(decoder.receive_frame().unwrap_err().is_need_more()); + } + + #[test] + fn flush_then_drain_reports_end_of_stream() { + let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).unwrap(); + decoder.flush().unwrap(); + assert!(decoder.receive_frame().unwrap_err().is_eof()); + decoder.reset(); + assert!(decoder.receive_frame().unwrap_err().is_need_more()); + } + + /// A truncated `avcC` is a container bug, not a panic: the reader runs out + /// of bytes and says so. + #[test] + fn a_truncated_avcc_is_an_error() { + let mut params = CodecParameters::new(CodecId::H264); + params.extradata = Some(ec_core::Buf::from_vec(vec![1, 66, 0, 30, 0xFF, 0xE1, 0x00])); + assert!(H264Decoder::new(params).is_err()); + } +} diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index aab48b6e..58334bdb 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -175,6 +175,9 @@ pub struct Decoder { /// Scaling factors for intra Y/Cb/Cr 4x4 lists of the active PPS/SPS. ls: [LevelScale4x4; 3], active_pps: Option, + /// `seq_parameter_set_id` of the most recently stored SPS, so a container + /// entry path can publish the picture size before the first slice. + last_sps: Option, } /// What [`Decoder::push_nal`] did with a NAL unit. @@ -212,9 +215,18 @@ impl Decoder { LevelScale4x4::new(&[16; 16]), ], active_pps: None, + last_sps: None, } } + /// Cropped picture size of the most recently stored SPS, `None` until one + /// arrives. Lets a container entry path fill in stream parameters from an + /// `avcC` record without decoding a picture first. + pub fn picture_size(&self) -> Option<(u32, u32)> { + let sps = self.sps_map[self.last_sps? as usize].as_ref()?; + Some((sps.width, sps.height)) + } + /// Decode the first IDR picture of an Annex B stream and return it. pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result { let mut got_slice = false; @@ -245,8 +257,9 @@ impl Decoder { let sps = Sps::parse(&rbsp); self.rbsp = rbsp; let sps = sps?; - let id = sps.id as usize; - self.sps_map[id] = Some(sps); + let id = sps.id; + self.sps_map[id as usize] = Some(sps); + self.last_sps = Some(id); Ok(NalOutcome::ParameterSet) } NalUnitType::Pps => { @@ -266,9 +279,13 @@ impl Decoder { self.rbsp = rbsp; r } - NalUnitType::SliceDataA | NalUnitType::SliceDataB | NalUnitType::SliceDataC => Err( - Error::unsupported("slice data partitioning", "NAL types 2..4 not implemented"), - ), + NalUnitType::SliceDataA | NalUnitType::SliceDataB | NalUnitType::SliceDataC => { + Err(Error::unsupported( + "slice data partitioning", + "nal_unit_type 2 to 4 carry a slice in three NAL units that \ + clause 7.4.1 reassembles by slice_id; not implemented", + )) + } _ => Ok(NalOutcome::Skipped), } } @@ -323,6 +340,13 @@ impl Decoder { self.has_picture && !self.pic.complete } + /// Drop picture state after a seek. Parameter sets survive, because the + /// container does not resend them at every seek point. + pub fn reset_pictures(&mut self) { + self.has_picture = false; + self.pic.complete = false; + } + fn decode_slice_rbsp(&mut self, header: NalHeader, rbsp: &[u8]) -> Result { // Peek first_mb / slice_type / pps_id to select parameter sets. let mut peek = BitReader::new(rbsp); @@ -347,7 +371,8 @@ impl Decoder { if sh.slice_type != SliceType::I { return Err(Error::unsupported( "non-I slice", - "P/B/SP/SI slices arrive with inter prediction (S18c)", + "P/B/SP/SI slices need inter prediction and a decoded picture \ + buffer (clause 8.4); only intra slices are decoded", )); } @@ -409,30 +434,42 @@ impl Decoder { } /// Reject unsupported streams with named reasons before touching pixels. +/// +/// Every `why` here names the syntax element that fired and the machinery it +/// would need: a refusal is a capability statement about this binary, and the +/// conformance suite proves each one against a stream that really uses the +/// feature. fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> { if pps.entropy_coding_mode { return Err(Error::unsupported( "CABAC entropy coding", - "only CAVLC is implemented (S18b)", + "entropy_coding_mode_flag 1 needs the arithmetic decoder and the \ + context models of clause 9.3; only CAVLC (9.2) is implemented", )); } if pps.num_slice_groups > 1 { return Err(Error::unsupported( "FMO slice groups", - "num_slice_groups > 1 not implemented", + "num_slice_groups_minus1 > 0 needs the macroblock-to-slice-group \ + map of clause 8.2.2; only one slice group per picture is decoded", )); } if sps.chroma_format_idc != 1 { return Err(Error::unsupported( "chroma format", - format!("chroma_format_idc {} (only 4:2:0)", sps.chroma_format_idc), + format!( + "chroma_format_idc {} needs its own chroma prediction, scan and \ + DC transform; only 4:2:0 (ChromaArrayType 1) is decoded", + sps.chroma_format_idc + ), )); } if sps.bit_depth_luma != 8 || sps.bit_depth_chroma != 8 { return Err(Error::unsupported( "bit depth", format!( - "{}-bit luma / {}-bit chroma (only 8-bit)", + "{}-bit luma / {}-bit chroma needs 16-bit sample planes and the \ + widened transform clip of clause 8.5; only 8-bit is decoded", sps.bit_depth_luma, sps.bit_depth_chroma ), )); @@ -440,19 +477,22 @@ fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> { if !sps.frame_mbs_only { return Err(Error::unsupported( "interlaced coding", - "field pictures / MBAFF not implemented", + "frame_mbs_only_flag 0 admits field pictures and MBAFF, whose \ + neighbour derivation (6.4.9) and field deblocking are not implemented", )); } if sps.separate_colour_plane { return Err(Error::unsupported( "separate colour planes", - "4:4:4 separate planes not implemented", + "separate_colour_plane_flag 1 codes 4:4:4 as three monochrome \ + planes with their own slice headers; not implemented", )); } if sps.transform_bypass { return Err(Error::unsupported( "transform bypass", - "qpprime_y_zero_transform_bypass not implemented", + "qpprime_y_zero_transform_bypass_flag 1 makes QP'Y 0 lossless, \ + bypassing the transform and scaling of 8.5 entirely; not implemented", )); } if slice_type_code > 9 { @@ -619,7 +659,8 @@ fn decode_macroblock( if !is_i16 && ctx.transform_8x8_mode && r.read_bit()? { return Err(Error::unsupported( "8x8 transform", - "transform_size_8x8_flag not implemented", + "transform_size_8x8_flag 1 selects the 8x8 intra prediction of \ + clause 8.3.2 and the 8x8 transform of 8.5.13; not implemented", )); } diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs index b7533160..17812c94 100644 --- a/crates/ec-h264/src/lib.rs +++ b/crates/ec-h264/src/lib.rs @@ -7,16 +7,38 @@ //! //! Implemented from Rec. ITU-T H.264 (V15, 08/2024) only; no third-party //! decoder source was consulted. +//! +//! Two entry surfaces over one decode core: [`Decoder`] takes NAL units, which +//! is what a bitstream tool has, and [`H264Decoder`] implements +//! [`ec_core::registry::Decoder`] over packets — including `avcC` extradata and +//! length-prefixed NAL units — which is what a demuxer hands over. +//! +//! ```no_run +//! use ec_core::registry::{CodecId, CodecParameters, Decoder}; +//! use ec_core::{Packet, TimeBase}; +//! use ec_h264::H264Decoder; +//! +//! # fn main() -> ec_core::Result<()> { +//! let annex_b: Vec = std::fs::read("stream.264")?; +//! let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264))?; +//! decoder.send_packet(&Packet::new(0, TimeBase::new(1, 25), annex_b))?; +//! let frame = decoder.receive_frame()?; // the first decoded picture, I420 +//! # let _ = frame; +//! # Ok(()) +//! # } +//! ``` #![forbid(unsafe_code)] mod bits; mod cavlc; +mod codec; mod deblock; mod decoder; mod pred; mod tables; mod transform; +pub use codec::H264Decoder; pub use decoder::{Decoder, NalOutcome}; pub use ec_core::error::{Error, Result};