forge
Explore
Log in

Don't you dare go Hollow

Write emulation prevention into an RBSP

Browse files at this commit

46b6e85d7322e0526fd10ea8f026581b3f1bce98Ahmet Kaan GümüşParent: 0113e05
  • feat
    • write emulation prevention into an RBSP
Show full message
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.rsmodified+1 -1
@@ -20,7 +20,7 @@ pub mod pps;
2020 pub mod slice;
2121 pub mod sps;
2222
23-pub use nal::{AnnexBIter, NalHeader, NalUnitType, unescape_rbsp};
23+pub use nal::{AnnexBIter, NalHeader, NalUnitType, escape_rbsp, unescape_rbsp};
2424 pub use pps::Pps;
2525 pub use slice::{
2626 DeblockControl, DecRefPicMarking, Mmco, PredWeightTable, RefPicListMod, SliceHeader, SliceType,
crates/ec-h264-syntax/src/nal.rsmodified+22 -0
@@ -172,6 +172,28 @@ impl<'a> Iterator for AnnexBIter<'a> {
172172 }
173173 }
174174
175+/// Insert emulation prevention bytes into an RBSP (spec 7.4.1.1), the inverse
176+/// of [`unescape_rbsp`]: a `00 00 00`, `00 00 01`, `00 00 02` or `00 00 03`
177+/// run gets an `emulation_prevention_three_byte` before its last byte, and a
178+/// payload ending in two zero bytes gets one appended.
179+pub fn escape_rbsp(rbsp: &[u8], out: &mut Vec<u8>) {
180+ let mut zeros = 0usize;
181+ for &b in rbsp {
182+ if zeros >= 2 && b <= 3 {
183+ out.push(3);
184+ zeros = 0;
185+ }
186+ out.push(b);
187+ if b == 0 {
188+ zeros += 1;
189+ } else {
190+ zeros = 0;
191+ }
192+ }
193+ if zeros >= 2 {
194+ out.push(3);
195+ }
196+}
175197 /// Strip emulation-prevention bytes (spec 7.4.1.1): every `00 00 03` becomes
176198 /// `00 00`. `nal` is the NAL payload **after** the header byte; the result is
177199 /// appended into `out`, which is cleared first and whose capacity is reused