From 46b6e85d7322e0526fd10ea8f026581b3f1bce98 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 16:17:30 +0300 Subject: [PATCH] feat(h264-syntax): write emulation prevention into an RBSP escape_rbsp is the inverse of unescape_rbsp, and the encoder needs it to frame every NAL unit it emits. Same shape as the h265 syntax crate's. --- crates/ec-h264-syntax/src/lib.rs | 2 +- crates/ec-h264-syntax/src/nal.rs | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/ec-h264-syntax/src/lib.rs b/crates/ec-h264-syntax/src/lib.rs index 84f8cac5..fec9ab2f 100644 --- a/crates/ec-h264-syntax/src/lib.rs +++ b/crates/ec-h264-syntax/src/lib.rs @@ -20,7 +20,7 @@ pub mod pps; pub mod slice; pub mod sps; -pub use nal::{AnnexBIter, NalHeader, NalUnitType, unescape_rbsp}; +pub use nal::{AnnexBIter, NalHeader, NalUnitType, escape_rbsp, unescape_rbsp}; pub use pps::Pps; pub use slice::{ DeblockControl, DecRefPicMarking, Mmco, PredWeightTable, RefPicListMod, SliceHeader, SliceType, diff --git a/crates/ec-h264-syntax/src/nal.rs b/crates/ec-h264-syntax/src/nal.rs index 7ff5d126..14072465 100644 --- a/crates/ec-h264-syntax/src/nal.rs +++ b/crates/ec-h264-syntax/src/nal.rs @@ -172,6 +172,28 @@ impl<'a> Iterator for AnnexBIter<'a> { } } +/// Insert emulation prevention bytes into an RBSP (spec 7.4.1.1), the inverse +/// of [`unescape_rbsp`]: a `00 00 00`, `00 00 01`, `00 00 02` or `00 00 03` +/// run gets an `emulation_prevention_three_byte` before its last byte, and a +/// payload ending in two zero bytes gets one appended. +pub fn escape_rbsp(rbsp: &[u8], out: &mut Vec) { + let mut zeros = 0usize; + for &b in rbsp { + if zeros >= 2 && b <= 3 { + out.push(3); + zeros = 0; + } + out.push(b); + if b == 0 { + zeros += 1; + } else { + zeros = 0; + } + } + if zeros >= 2 { + out.push(3); + } +} /// Strip emulation-prevention bytes (spec 7.4.1.1): every `00 00 03` becomes /// `00 00`. `nal` is the NAL payload **after** the header byte; the result is /// appended into `out`, which is cleared first and whose capacity is reused