forge
Explore
Log in

Don't you dare go Hollow

Rewrite H.264 frame_num/POC the driver zeroes

Browse files at this commit

243682681b2a0568f58eddae40cd11ceb41ca5cbAhmet Kaan GümüşParent: 1638944
  • fix
    • rewrite H.264 frame_num/POC the driver zeroes
Show full message
🐛 fix(engine-hw): rewrite H.264 frame_num/POC the driver zeroes

mesa radeonsi (26.1.7) writes its own slice headers and ignores the
frame_num and pic_order_cnt_lsb cros-codecs passes in, so every slice of
every export carried 0 for both. Desktop decoders tolerate it; stateful
phone decoders judder at every GOP (measured on three real exports).

slice_fix rewrites both fields per access unit on the plugin side
(frame_num on reference pictures, POC per picture, IDR resets), and the
level_idc now follows Table A-1 / Table A.8 instead of a hard-coded L4.
Header-only: macroblock data is byte-identical, bitrate unchanged.

Verified: ffmpeg trace_headers on a plugin dump (frame_num 0..31 wrap,
POC 2n, IDR restart, level 40 at 1080p30); 2560x1440 re-export plays
clean on the phone that juddered before.
crates/engine-hw/src/lib.rsmodified+11 -4
@@ -24,6 +24,8 @@
24 //! exists: give `vh_open_at`/`vh_next_frame` the message tags `vh_enc_*` have in24 //! exists: give `vh_open_at`/`vh_next_frame` the message tags `vh_enc_*` have in
25 //! `hwproc` and let the same helper hold both.25 //! `hwproc` and let the same helper hold both.
26 26
27+mod slice_fix;
28+
27 use std::collections::VecDeque;29 use std::collections::VecDeque;
28 use std::ffi::{CStr, c_char, c_void};30 use std::ffi::{CStr, c_char, c_void};
29 use std::os::fd::IntoRawFd;31 use std::os::fd::IntoRawFd;
@@ -34,8 +36,8 @@ use std::rc::Rc;
34 use cros_codecs::backend::vaapi::decoder::VaapiBackend;36 use cros_codecs::backend::vaapi::decoder::VaapiBackend;
35 use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;37 use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;
36 use cros_codecs::codec::av1::parser::Profile as Av1Profile;38 use cros_codecs::codec::av1::parser::Profile as Av1Profile;
37-use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};39+use cros_codecs::codec::h264::parser::Profile as H264Profile;
38-use cros_codecs::codec::h265::parser::{Level as H265Level, Profile as H265Profile};40+use cros_codecs::codec::h265::parser::Profile as H265Profile;
39 use cros_codecs::decoder::stateless::av1::Av1;41 use cros_codecs::decoder::stateless::av1::Av1;
40 use cros_codecs::decoder::stateless::h264::H264;42 use cros_codecs::decoder::stateless::h264::H264;
41 use cros_codecs::decoder::stateless::h265::H265;43 use cros_codecs::decoder::stateless::h265::H265;
@@ -1181,6 +1183,9 @@ struct EncSession {
1181 /// differs: the H.264 driver leaves a *NAL* header byte at zero, and1183 /// differs: the H.264 driver leaves a *NAL* header byte at zero, and
1182 /// neither an HEVC access unit nor an AV1 temporal unit has that one.1184 /// neither an HEVC access unit nor an AV1 temporal unit has that one.
1183 codec: EncCodec,1185 codec: EncCodec,
1186+ /// The H.264 counters the driver zeroes, rewritten per access unit
1187+ /// ([`slice_fix`]).
1188+ counters: slice_fix::SliceCounters,
1184 /// Owns the DRM node the buffer objects below were allocated from.1189 /// Owns the DRM node the buffer objects below were allocated from.
1185 _gbm: gbm::Device<std::fs::File>,1190 _gbm: gbm::Device<std::fs::File>,
1186 /// [`enc_depth`] input buffers, used round-robin.1191 /// [`enc_depth`] input buffers, used round-robin.
@@ -1397,7 +1402,7 @@ impl EncSession {
1397 let config = H265Config {1402 let config = H265Config {
1398 resolution: Resolution { width, height },1403 resolution: Resolution { width, height },
1399 profile: H265Profile::Main,1404 profile: H265Profile::Main,
1400- level: H265Level::L4,1405+ level: slice_fix::hevc_level(width, height, fps_num, fps_den),
1401 pred_structure: PredictionStructure::LowDelay { limit: 1 },1406 pred_structure: PredictionStructure::LowDelay { limit: 1 },
1402 initial_tunings: Tunings {1407 initial_tunings: Tunings {
1403 rate_control: RateControl::ConstantBitrate(bitrate),1408 rate_control: RateControl::ConstantBitrate(bitrate),
@@ -1429,7 +1434,7 @@ impl EncSession {
1429 let config = H264Config {1434 let config = H264Config {
1430 resolution: Resolution { width, height },1435 resolution: Resolution { width, height },
1431 profile: H264Profile::Main,1436 profile: H264Profile::Main,
1432- level: Level::L4,1437+ level: slice_fix::h264_level(width, height, fps_num, fps_den),
1433 pred_structure,1438 pred_structure,
1434 initial_tunings: Tunings {1439 initial_tunings: Tunings {
1435 rate_control: RateControl::ConstantBitrate(bitrate),1440 rate_control: RateControl::ConstantBitrate(bitrate),
@@ -1466,6 +1471,7 @@ impl EncSession {
1466 depth,1471 depth,
1467 slot: 0,1472 slot: 0,
1468 in_flight: 0,1473 in_flight: 0,
1474+ counters: slice_fix::SliceCounters::default(),
1469 layout,1475 layout,
1470 coded,1476 coded,
1471 width: width as usize,1477 width: width as usize,
@@ -1672,6 +1678,7 @@ impl EncSession {
1672 let mut au = coded.bitstream;1678 let mut au = coded.bitstream;
1673 if self.codec == EncCodec::H264 {1679 if self.codec == EncCodec::H264 {
1674 fix_slice_nal_headers(&mut au);1680 fix_slice_nal_headers(&mut au);
1681+ self.counters.fix_au(&mut au);
1675 }1682 }
1676 self.ready.push_back(au);1683 self.ready.push_back(au);
1677 self.in_flight = self.in_flight.saturating_sub(1);1684 self.in_flight = self.in_flight.saturating_sub(1);
crates/engine-hw/src/slice_fix.rsadded+552 -0
@@ -0,0 +1,552 @@
1+//! Repairs the two counters the H.264 driver writes wrong.
2+//!
3+//! cros-codecs hands `frame_num` and `pic_order_cnt_lsb` to VA-API in the
4+//! picture and slice parameter buffers, and mesa radeonsi (26.1.7, measured on
5+//! a recent AMD GPU) writes the slice header itself with **both at zero on every
6+//! picture** -- the same driver habit already noted for HEVC in `lib.rs`. The
7+//! stream then breaks 7.4.3: consecutive reference pictures with the same
8+//! `frame_num` are a gap a decoder must conceal, and every picture claiming
9+//! output order 0 leaves a decoder that bumps by POC -- which is what a phone's
10+//! stateful hardware decoder does -- to emit pictures in bursts. Desktop
11+//! decoders (ffmpeg, openh264, the VA-API one on this very card) ignore both
12+//! fields for a one-reference stream and play it clean, which is why the
13+//! defect was only ever seen on a phone: three real exports judder every few
14+//! seconds in every player there, before and after a WhatsApp transcode.
15+//!
16+//! Both fields are fixed-width (`u(v)`, widths from the SPS), so the repair is
17+//! an in-place bit rewrite: unescape the NAL, set the bits, re-escape. The
18+//! values are what cros-codecs meant: the picture's index since the last IDR,
19+//! modulo `MaxFrameNum`, and twice that modulo `MaxPicOrderCntLsb` -- POC type
20+//! 0 with no B-frames, so output order is decode order.
21+//!
22+//! Level is the other header field that was wrong ([`h264_level`],
23+//! [`hevc_level`]): `L4` was hard-coded, which a 3840x1608 picture overflows
24+//! (Table A-1 caps 4.0 at 8192 macroblocks a frame).
25+
26+use cros_codecs::codec::h264::parser::Level;
27+use cros_codecs::codec::h265::parser::Level as H265Level;
28+
29+const NAL_SLICE: u8 = 1;
30+const NAL_IDR: u8 = 5;
31+const NAL_SPS: u8 = 7;
32+
33+/// What the slice header rewrite needs from the SPS, plus the running count.
34+#[derive(Debug, Default, Clone, Copy)]
35+pub struct SliceCounters {
36+ /// `log2_max_frame_num_minus4 + 4`; 0 until an SPS has been seen.
37+ log2_max_frame_num: u8,
38+ /// `log2_max_pic_order_cnt_lsb_minus4 + 4` when `pic_order_cnt_type == 0`,
39+ /// else 0 (no `pic_order_cnt_lsb` field in the slice header).
40+ log2_max_poc_lsb: u8,
41+ /// `frame_mbs_only_flag`; a field-coded stream carries more fields before
42+ /// `pic_order_cnt_lsb` than this rewrites, so it is left alone.
43+ frame_mbs_only: bool,
44+ /// Pictures since the last IDR, the IDR itself being 0: the POC runs on
45+ /// this (7.4.3, POC type 0: `pic_order_cnt_lsb` of frame n is 2n).
46+ count: u32,
47+ /// *Reference* pictures since the last IDR: `frame_num` runs on this one,
48+ /// because 7.4.3 has it step only after a picture with `nal_ref_idc != 0`.
49+ /// The vendored encoder marks every picture a reference, so the two agree
50+ /// today; kept apart so a non-reference picture is numbered right the day
51+ /// the encoder writes one.
52+ refs: u32,
53+}
54+
55+impl SliceCounters {
56+ /// Rewrites every slice in one access unit. An SPS in the unit is parsed
57+ /// first (cros-codecs writes one at every IDR and only there). A unit whose
58+ /// SPS cannot be read, or that arrives before any SPS, is left untouched.
59+ pub fn fix_au(&mut self, au: &mut Vec<u8>) {
60+ let nals = nal_ranges(au);
61+ for &(start, end) in &nals {
62+ if au[start] & 0x1f == NAL_SPS {
63+ if let Some(parsed) = parse_sps(&unescape(&au[start + 1..end])) {
64+ *self = SliceCounters { count: self.count, refs: self.refs, ..parsed };
65+ }
66+ }
67+ }
68+ if self.log2_max_frame_num == 0 || !self.frame_mbs_only {
69+ return;
70+ }
71+ // An IDR restarts the count; every slice of one picture takes the same
72+ // numbers, so the count steps once per access unit, after the rewrite.
73+ if nals.iter().any(|&(s, _)| au[s] & 0x1f == NAL_IDR) {
74+ self.count = 0;
75+ self.refs = 0;
76+ }
77+ let frame_num = self.refs & ((1u32 << self.log2_max_frame_num) - 1);
78+ let poc_lsb = (self.count.wrapping_mul(2)) & ((1u32 << self.log2_max_poc_lsb) - 1);
79+ let mut out = Vec::with_capacity(au.len() + 8);
80+ let mut cursor = 0;
81+ for &(start, end) in &nals {
82+ out.extend_from_slice(&au[cursor..start]);
83+ let kind = au[start] & 0x1f;
84+ if kind == NAL_SLICE || kind == NAL_IDR {
85+ out.push(au[start]);
86+ let mut rbsp = unescape(&au[start + 1..end]);
87+ if rewrite_slice(&mut rbsp, kind == NAL_IDR, self, frame_num, poc_lsb) {
88+ escape(&rbsp, &mut out);
89+ } else {
90+ out.extend_from_slice(&au[start + 1..end]);
91+ }
92+ } else {
93+ out.extend_from_slice(&au[start..end]);
94+ }
95+ cursor = end;
96+ }
97+ out.extend_from_slice(&au[cursor..]);
98+ *au = out;
99+ self.count = self.count.wrapping_add(1);
100+ let is_ref = |&(s, _): &(usize, usize)| {
101+ matches!(au[s] & 0x1f, NAL_SLICE | NAL_IDR) && au[s] & 0x60 != 0
102+ };
103+ if nals.iter().any(is_ref) {
104+ self.refs = self.refs.wrapping_add(1);
105+ }
106+ }
107+}
108+
109+/// `(first byte after the start code, end)` of every NAL in an Annex B unit.
110+fn nal_ranges(au: &[u8]) -> Vec<(usize, usize)> {
111+ let mut starts = Vec::new();
112+ let mut i = 0;
113+ while i + 3 <= au.len() {
114+ if au[i..i + 3] == [0, 0, 1] {
115+ starts.push(i + 3);
116+ i += 3;
117+ } else {
118+ i += 1;
119+ }
120+ }
121+ let mut ranges = Vec::with_capacity(starts.len());
122+ for (n, &s) in starts.iter().enumerate() {
123+ let mut end = starts.get(n + 1).map_or(au.len(), |&next| next - 3);
124+ // A four-byte start code's leading zero belongs to the separator.
125+ while end > s && au[end - 1] == 0 && n + 1 < starts.len() {
126+ end -= 1;
127+ }
128+ ranges.push((s, end));
129+ }
130+ ranges.retain(|&(s, e)| e > s);
131+ ranges
132+}
133+
134+fn unescape(bytes: &[u8]) -> Vec<u8> {
135+ let mut out = Vec::with_capacity(bytes.len());
136+ let mut zeros = 0usize;
137+ for &b in bytes {
138+ if zeros >= 2 && b == 3 {
139+ zeros = 0;
140+ continue;
141+ }
142+ out.push(b);
143+ zeros = if b == 0 { zeros + 1 } else { 0 };
144+ }
145+ out
146+}
147+
148+fn escape(rbsp: &[u8], out: &mut Vec<u8>) {
149+ let mut zeros = 0usize;
150+ for &b in rbsp {
151+ if zeros >= 2 && b <= 3 {
152+ out.push(3);
153+ zeros = 0;
154+ }
155+ out.push(b);
156+ zeros = if b == 0 { zeros + 1 } else { 0 };
157+ }
158+}
159+
160+struct Bits<'a> {
161+ data: &'a [u8],
162+ pos: usize,
163+}
164+
165+impl<'a> Bits<'a> {
166+ fn new(data: &'a [u8]) -> Self {
167+ Self { data, pos: 0 }
168+ }
169+ fn bit(&mut self) -> Option<u32> {
170+ let byte = *self.data.get(self.pos / 8)?;
171+ let bit = (byte >> (7 - self.pos % 8)) & 1;
172+ self.pos += 1;
173+ Some(u32::from(bit))
174+ }
175+ fn bits(&mut self, n: u8) -> Option<u32> {
176+ let mut v = 0;
177+ for _ in 0..n {
178+ v = (v << 1) | self.bit()?;
179+ }
180+ Some(v)
181+ }
182+ fn ue(&mut self) -> Option<u32> {
183+ let mut zeros = 0;
184+ while self.bit()? == 0 {
185+ zeros += 1;
186+ if zeros > 31 {
187+ return None;
188+ }
189+ }
190+ Some((1u32 << zeros) - 1 + self.bits(zeros)?)
191+ }
192+ fn se(&mut self) -> Option<i32> {
193+ let k = self.ue()?;
194+ Some(if k % 2 == 1 { (k as i32 + 1) / 2 } else { -(k as i32 / 2) })
195+ }
196+}
197+
198+fn put_bits(data: &mut [u8], pos: usize, width: u8, value: u32) {
199+ for i in 0..usize::from(width) {
200+ let bit = (value >> (usize::from(width) - 1 - i)) & 1;
201+ let at = pos + i;
202+ let mask = 0x80 >> (at % 8);
203+ if bit == 1 {
204+ data[at / 8] |= mask;
205+ } else {
206+ data[at / 8] &= !mask;
207+ }
208+ }
209+}
210+
211+/// Reads the SPS fields the rewrite depends on (§7.3.2.1.1) from an unescaped
212+/// payload (NAL header byte already stripped).
213+fn parse_sps(rbsp: &[u8]) -> Option<SliceCounters> {
214+ let mut b = Bits::new(rbsp);
215+ let profile_idc = b.bits(8)?;
216+ b.bits(8)?; // constraint flags + reserved
217+ b.bits(8)?; // level_idc
218+ b.ue()?; // seq_parameter_set_id
219+ if matches!(
220+ profile_idc,
221+ 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
222+ ) {
223+ let chroma_format_idc = b.ue()?;
224+ if chroma_format_idc == 3 {
225+ b.bit()?; // separate_colour_plane_flag
226+ }
227+ b.ue()?; // bit_depth_luma_minus8
228+ b.ue()?; // bit_depth_chroma_minus8
229+ b.bit()?; // qpprime_y_zero_transform_bypass_flag
230+ if b.bit()? == 1 {
231+ // seq_scaling_matrix_present_flag: never written by cros-codecs, and
232+ // walking the lists is not worth carrying for a stream that has them.
233+ return None;
234+ }
235+ }
236+ let log2_max_frame_num = u8::try_from(b.ue()? + 4).ok()?;
237+ let poc_type = b.ue()?;
238+ let log2_max_poc_lsb = match poc_type {
239+ 0 => u8::try_from(b.ue()? + 4).ok()?,
240+ 1 => {
241+ b.bit()?;
242+ b.se()?;
243+ b.se()?;
244+ let cycle = b.ue()?;
245+ for _ in 0..cycle {
246+ b.se()?;
247+ }
248+ 0
249+ }
250+ _ => 0,
251+ };
252+ if log2_max_frame_num > 16 || log2_max_poc_lsb > 16 {
253+ return None;
254+ }
255+ b.ue()?; // max_num_ref_frames
256+ b.bit()?; // gaps_in_frame_num_value_allowed_flag
257+ b.ue()?; // pic_width_in_mbs_minus1
258+ b.ue()?; // pic_height_in_map_units_minus1
259+ let frame_mbs_only = b.bit()? == 1;
260+ Some(SliceCounters {
261+ log2_max_frame_num,
262+ log2_max_poc_lsb,
263+ frame_mbs_only,
264+ count: 0,
265+ refs: 0,
266+ })
267+}
268+
269+/// Sets `frame_num` and (POC type 0) `pic_order_cnt_lsb` in one unescaped
270+/// slice payload (§7.3.3). `false` where the header could not be walked, in
271+/// which case the payload is unchanged.
272+fn rewrite_slice(
273+ rbsp: &mut [u8],
274+ idr: bool,
275+ sps: &SliceCounters,
276+ frame_num: u32,
277+ poc_lsb: u32,
278+) -> bool {
279+ let (frame_num_at, poc_at) = {
280+ let mut b = Bits::new(rbsp);
281+ let mut walk = || -> Option<(usize, Option<usize>)> {
282+ b.ue()?; // first_mb_in_slice
283+ b.ue()?; // slice_type
284+ b.ue()?; // pic_parameter_set_id
285+ let frame_num_at = b.pos;
286+ b.bits(sps.log2_max_frame_num)?;
287+ if idr {
288+ b.ue()?; // idr_pic_id
289+ }
290+ let poc_at = (sps.log2_max_poc_lsb > 0).then_some(b.pos);
291+ if let Some(at) = poc_at {
292+ if at + usize::from(sps.log2_max_poc_lsb) > rbsp.len() * 8 {
293+ return None;
294+ }
295+ }
296+ Some((frame_num_at, poc_at))
297+ };
298+ match walk() {
299+ Some(v) => v,
300+ None => return false,
301+ }
302+ };
303+ put_bits(rbsp, frame_num_at, sps.log2_max_frame_num, frame_num);
304+ if let Some(at) = poc_at {
305+ put_bits(rbsp, at, sps.log2_max_poc_lsb, poc_lsb);
306+ }
307+ true
308+}
309+
310+/// The lowest H.264 level (Table A-1) whose frame size and macroblock rate
311+/// hold `width`x`height` at `fps`; 6.2 past the table.
312+pub fn h264_level(width: u32, height: u32, fps_num: u32, fps_den: u32) -> Level {
313+ const LEVELS: [(u8, u64, u64); 17] = [
314+ (10, 1485, 99),
315+ (11, 3000, 396),
316+ (12, 6000, 396),
317+ (13, 11880, 396),
318+ (20, 11880, 396),
319+ (21, 19800, 792),
320+ (22, 20250, 1620),
321+ (30, 40500, 1620),
322+ (31, 108000, 3600),
323+ (32, 216000, 5120),
324+ (40, 245760, 8192),
325+ (41, 245760, 8192),
326+ (42, 522240, 8704),
327+ (50, 589824, 22080),
328+ (51, 983040, 36864),
329+ (52, 2073600, 36864),
330+ (60, 4177920, 139264),
331+ ];
332+ let frame_mbs = u64::from(width.div_ceil(16)) * u64::from(height.div_ceil(16));
333+ let fps = f64::from(fps_num.max(1)) / f64::from(fps_den.max(1));
334+ let mbps = (frame_mbs as f64 * fps).ceil() as u64;
335+ let idc = LEVELS
336+ .iter()
337+ .find(|&&(_, max_mbps, max_fs)| mbps <= max_mbps && frame_mbs <= max_fs)
338+ .map_or(62, |&(idc, ..)| idc);
339+ Level::try_from(idc).unwrap_or(Level::L6_2)
340+}
341+
342+/// The lowest HEVC level (Table A.8, Main tier) whose luma picture size and
343+/// sample rate hold the picture; 6.2 past the table.
344+pub fn hevc_level(width: u32, height: u32, fps_num: u32, fps_den: u32) -> H265Level {
345+ const LEVELS: [(H265Level, u64, u64); 13] = [
346+ (H265Level::L1, 36_864, 552_960),
347+ (H265Level::L2, 122_880, 3_686_400),
348+ (H265Level::L2_1, 245_760, 7_372_800),
349+ (H265Level::L3, 552_960, 16_588_800),
350+ (H265Level::L3_1, 983_040, 33_177_600),
351+ (H265Level::L4, 2_228_224, 66_846_720),
352+ (H265Level::L4_1, 2_228_224, 133_693_440),
353+ (H265Level::L5, 8_912_896, 267_386_880),
354+ (H265Level::L5_1, 8_912_896, 534_773_760),
355+ (H265Level::L5_2, 8_912_896, 1_069_547_520),
356+ (H265Level::L6, 35_651_584, 1_069_547_520),
357+ (H265Level::L6_1, 35_651_584, 2_139_095_040),
358+ (H265Level::L6_2, 35_651_584, 4_278_190_080),
359+ ];
360+ let luma_ps = u64::from(width) * u64::from(height);
361+ let fps = f64::from(fps_num.max(1)) / f64::from(fps_den.max(1));
362+ let luma_sr = (luma_ps as f64 * fps).ceil() as u64;
363+ LEVELS
364+ .iter()
365+ .find(|&&(_, max_ps, max_sr)| luma_ps <= max_ps && luma_sr <= max_sr)
366+ .map_or(H265Level::L6_2, |&(level, ..)| level)
367+}
368+
369+#[cfg(test)]
370+mod tests {
371+ use super::*;
372+
373+ struct Writer {
374+ bytes: Vec<u8>,
375+ bits: usize,
376+ }
377+ impl Writer {
378+ fn new() -> Self {
379+ Self { bytes: Vec::new(), bits: 0 }
380+ }
381+ fn u(&mut self, width: u8, v: u32) {
382+ for i in 0..usize::from(width) {
383+ if self.bits % 8 == 0 {
384+ self.bytes.push(0);
385+ }
386+ if (v >> (usize::from(width) - 1 - i)) & 1 == 1 {
387+ let at = self.bits;
388+ self.bytes[at / 8] |= 0x80 >> (at % 8);
389+ }
390+ self.bits += 1;
391+ }
392+ }
393+ fn ue(&mut self, v: u32) {
394+ let k = v + 1;
395+ let len = 32 - k.leading_zeros() as u8;
396+ self.u(len - 1, 0);
397+ self.u(len, k);
398+ }
399+ fn done(mut self) -> Vec<u8> {
400+ self.u(1, 1); // rbsp trailing bit
401+ self.bytes
402+ }
403+ }
404+
405+ /// Main profile SPS the way cros-codecs writes one at a 2 s GOP and 30 fps:
406+ /// MaxFrameNum 32, MaxPocLsb 64, frame_mbs_only.
407+ fn sps() -> Vec<u8> {
408+ let mut w = Writer::new();
409+ w.u(8, 77);
410+ w.u(8, 0);
411+ w.u(8, 40);
412+ w.ue(0); // sps id
413+ w.ue(1); // log2_max_frame_num_minus4
414+ w.ue(0); // poc type
415+ w.ue(2); // log2_max_pic_order_cnt_lsb_minus4
416+ w.ue(1); // max_num_ref_frames
417+ w.u(1, 0);
418+ w.ue(119);
419+ w.ue(67);
420+ w.u(1, 1); // frame_mbs_only
421+ w.u(1, 1);
422+ w.u(1, 0);
423+ w.u(1, 0);
424+ let mut nal = vec![0, 0, 0, 1, 0x67];
425+ escape(&w.done(), &mut nal);
426+ nal
427+ }
428+
429+ /// A slice header as the driver writes it (both counters zero), with
430+ /// `tail` bytes of "macroblock data" after it.
431+ fn slice(idr: bool, tail: &[u8]) -> Vec<u8> {
432+ let mut w = Writer::new();
433+ w.ue(0); // first_mb_in_slice
434+ w.ue(if idr { 7 } else { 5 }); // slice_type I / P
435+ w.ue(0); // pps id
436+ w.u(5, 0); // frame_num
437+ if idr {
438+ w.ue(0); // idr_pic_id
439+ }
440+ w.u(6, 0); // pic_order_cnt_lsb
441+ let mut rbsp = w.done();
442+ rbsp.extend_from_slice(tail);
443+ let mut nal = vec![0, 0, 0, 1, if idr { 0x65 } else { 0x41 }];
444+ escape(&rbsp, &mut nal);
445+ nal
446+ }
447+
448+ /// Reads the two counters back out of an escaped slice NAL.
449+ fn read(nal: &[u8]) -> (u32, u32) {
450+ let (start, end) = nal_ranges(nal)[0];
451+ let idr = nal[start] & 0x1f == NAL_IDR;
452+ let rbsp = unescape(&nal[start + 1..end]);
453+ let mut b = Bits::new(&rbsp);
454+ b.ue().unwrap();
455+ b.ue().unwrap();
456+ b.ue().unwrap();
457+ let frame_num = b.bits(5).unwrap();
458+ if idr {
459+ b.ue().unwrap();
460+ }
461+ (frame_num, b.bits(6).unwrap())
462+ }
463+
464+ #[test]
465+ fn frame_num_holds_across_a_non_reference_picture() {
466+ // 7.4.3: a non-reference picture (nal_ref_idc 0) takes PrevRefFrameNum
467+ // + 1 like any other, but it is not a reference, so the picture after
468+ // it takes the same frame_num. The POC still steps every picture.
469+ let mut fix = SliceCounters::default();
470+ let mut idr = sps();
471+ idr.extend(slice(true, &[]));
472+ fix.fix_au(&mut idr);
473+ let mut p = slice(false, &[]);
474+ fix.fix_au(&mut p);
475+ assert_eq!(read(&p), (1, 2));
476+ let mut b = slice(false, &[]);
477+ b[4] = 0x01; // nal_ref_idc 0, type 1
478+ fix.fix_au(&mut b);
479+ assert_eq!(read(&b), (2, 4));
480+ let mut p = slice(false, &[]);
481+ fix.fix_au(&mut p);
482+ assert_eq!(read(&p), (2, 6), "the picture after a non-reference keeps its frame_num");
483+ }
484+
485+ #[test]
486+ fn counters_step_per_picture_and_restart_at_idr() {
487+ let mut fix = SliceCounters::default();
488+ let mut idr = sps();
489+ idr.extend(slice(true, &[0xAB; 40]));
490+ fix.fix_au(&mut idr);
491+ let slice_nal = nal_ranges(&idr)[1];
492+ assert_eq!(read(&idr[slice_nal.0 - 4..]), (0, 0));
493+ let mut seen = Vec::new();
494+ for _ in 0..40 {
495+ let mut p = slice(false, &[0xCD; 40]);
496+ fix.fix_au(&mut p);
497+ seen.push(read(&p));
498+ }
499+ // frame_num wraps at MaxFrameNum 32, POC lsb at 64 -- both as 8.2.1 derives.
500+ assert_eq!(seen[0], (1, 2));
501+ assert_eq!(seen[30], (31, 62));
502+ assert_eq!(seen[31], (0, 0));
503+ assert_eq!(seen[32], (1, 2));
504+ let mut again = sps();
505+ again.extend(slice(true, &[]));
506+ fix.fix_au(&mut again);
507+ let at = nal_ranges(&again)[1].0 - 4;
508+ assert_eq!(read(&again[at..]), (0, 0), "an IDR restarts the count");
509+ let mut p = slice(false, &[]);
510+ fix.fix_au(&mut p);
511+ assert_eq!(read(&p), (1, 2));
512+ }
513+
514+ #[test]
515+ fn macroblock_data_survives_byte_for_byte() {
516+ let mut fix = SliceCounters::default();
517+ let mut idr = sps();
518+ idr.extend(slice(true, &[]));
519+ fix.fix_au(&mut idr);
520+ // A tail that the escaper has to touch both before and after: the
521+ // rewritten header must not disturb it.
522+ let tail = [0, 0, 1, 0, 0, 3, 0, 0, 0, 7, 0xFF, 0, 0];
523+ let mut p = slice(false, &tail);
524+ let before = unescape(&p[5..]);
525+ fix.fix_au(&mut p);
526+ let after = unescape(&p[5..]);
527+ assert_eq!(before.len(), after.len());
528+ assert_eq!(&before[3..], &after[3..]);
529+ assert_eq!(&after[after.len() - tail.len()..], &tail);
530+ }
531+
532+ #[test]
533+ fn nothing_is_touched_before_an_sps() {
534+ let mut fix = SliceCounters::default();
535+ let mut p = slice(false, &[1, 2, 3]);
536+ let before = p.clone();
537+ fix.fix_au(&mut p);
538+ assert_eq!(p, before);
539+ }
540+
541+ #[test]
542+ fn levels_follow_table_a1() {
543+ assert_eq!(h264_level(1920, 1080, 30, 1), Level::L4);
544+ assert_eq!(h264_level(1920, 1080, 60, 1), Level::L4_2);
545+ assert_eq!(h264_level(3840, 1608, 24000, 1001), Level::L5_1);
546+ assert_eq!(h264_level(3840, 2160, 60, 1), Level::L5_2);
547+ assert_eq!(h264_level(640, 360, 30, 1), Level::L3);
548+ assert_eq!(hevc_level(1920, 1080, 30, 1), H265Level::L4);
549+ assert_eq!(hevc_level(3840, 2160, 30, 1), H265Level::L5);
550+ assert_eq!(hevc_level(3840, 2160, 60, 1), H265Level::L5_1);
551+ }
552+}
crates/engine/tests/hw_encode.rsmodified+127 -0
@@ -286,3 +286,130 @@ fn decode_and_encode_load_independently() {
286 assert!(HwSession::open(&asset).is_some());286 assert!(HwSession::open(&asset).is_some());
287 assert!(HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some());287 assert!(HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some());
288 }288 }
289+
290+/// Walks the Annex B stream and reads, per slice, `(is_idr, frame_num,
291+/// pic_order_cnt_lsb)`, plus the SPS `level_idc`. Main profile, POC type 0 and
292+/// frame_mbs_only -- the SPS the vendored encoder writes -- is all this reads;
293+/// the test fails loudly on anything else rather than guessing.
294+fn slice_counters(stream: &[u8]) -> (u8, Vec<(bool, u32, u32)>) {
295+ struct Bits<'a>(&'a [u8], usize);
296+ impl Bits<'_> {
297+ fn bit(&mut self) -> u32 {
298+ let b = (self.0[self.1 / 8] >> (7 - self.1 % 8)) & 1;
299+ self.1 += 1;
300+ u32::from(b)
301+ }
302+ fn bits(&mut self, n: u32) -> u32 {
303+ (0..n).fold(0, |v, _| (v << 1) | self.bit())
304+ }
305+ fn ue(&mut self) -> u32 {
306+ let mut zeros = 0;
307+ while self.bit() == 0 {
308+ zeros += 1;
309+ }
310+ (1 << zeros) - 1 + self.bits(zeros)
311+ }
312+ }
313+ fn unescape(bytes: &[u8]) -> Vec<u8> {
314+ let mut out = Vec::with_capacity(bytes.len());
315+ let mut zeros = 0;
316+ for &b in bytes {
317+ if zeros >= 2 && b == 3 {
318+ zeros = 0;
319+ continue;
320+ }
321+ out.push(b);
322+ zeros = if b == 0 { zeros + 1 } else { 0 };
323+ }
324+ out
325+ }
326+ let mut nals = Vec::new();
327+ let mut i = 0;
328+ while i + 3 <= stream.len() {
329+ if stream[i..i + 3] == [0, 0, 1] {
330+ nals.push(i + 3);
331+ i += 3;
332+ } else {
333+ i += 1;
334+ }
335+ }
336+ let (mut level, mut log2_fn, mut log2_poc) = (0u8, 0u32, 0u32);
337+ let mut out = Vec::new();
338+ for (n, &s) in nals.iter().enumerate() {
339+ let e = nals.get(n + 1).map_or(stream.len(), |&x| x - 3);
340+ let kind = stream[s] & 0x1f;
341+ // Only the header is needed; 64 bytes of RBSP covers every field read.
342+ let rbsp = unescape(&stream[s + 1..e.min(s + 1 + 64)]);
343+ let mut b = Bits(&rbsp, 0);
344+ match kind {
345+ 7 => {
346+ let profile = b.bits(8);
347+ assert_eq!(profile, 77, "Main profile SPS expected");
348+ b.bits(8);
349+ level = b.bits(8) as u8;
350+ b.ue();
351+ log2_fn = b.ue() + 4;
352+ assert_eq!(b.ue(), 0, "pic_order_cnt_type 0 expected");
353+ log2_poc = b.ue() + 4;
354+ }
355+ 1 | 5 => {
356+ assert!(log2_fn > 0, "slice before any SPS");
357+ b.ue();
358+ b.ue();
359+ b.ue();
360+ let frame_num = b.bits(log2_fn);
361+ if kind == 5 {
362+ b.ue();
363+ }
364+ out.push((kind == 5, frame_num, b.bits(log2_poc)));
365+ }
366+ _ => {}
367+ }
368+ }
369+ (level, out)
370+}
371+
372+/// The driver on this box writes `frame_num = 0` and `pic_order_cnt_lsb = 0`
373+/// into every slice it codes (mesa radeonsi 26.1.7, measured on three real
374+/// exports); phones' stateful decoders then judder every few seconds. The
375+/// plugin rewrites both, and this is the stream-level proof: over two GOPs the
376+/// counters step the way 7.4.3 wants, restart at the second IDR, and the level
377+/// is the one Table A-1 gives 1080p30 -- not the `L4` that used to be
378+/// hard-coded for every size. `HW_ENCODE_DUMP=<path>` keeps the stream for
379+/// `ffmpeg -bsf:v trace_headers`.
380+#[test]
381+#[ignore = "needs libengine_hw.so and a VA-API driver with an H.264 encode entrypoint"]
382+fn slice_headers_carry_frame_num_and_poc() {
383+ let (width, height) = (1920u32, 1080u32);
384+ let count = 100; // a 2 s GOP at 30 fps is 60: two IDRs, frame_num wraps at 32
385+ let (stream, units) =
386+ encode(width, height, count).expect("no hardware encode plugin/driver available");
387+ assert_eq!(units, count);
388+ if let Ok(path) = std::env::var("HW_ENCODE_DUMP") {
389+ std::fs::write(&path, &stream).expect("dump");
390+ println!("stream written to {path}");
391+ }
392+ let (level, slices) = slice_counters(&stream);
393+ assert_eq!(level, 40, "1920x1080 at 30 fps is level 4.0");
394+ assert_eq!(slices.len() as u32, count, "one slice per picture");
395+ let idrs: Vec<usize> = slices
396+ .iter()
397+ .enumerate()
398+ .filter(|(_, s)| s.0)
399+ .map(|(i, _)| i)
400+ .collect();
401+ assert_eq!(idrs, vec![0, 60], "an IDR every 2 s GOP");
402+ let mut since_idr = 0u32;
403+ for (i, &(idr, frame_num, poc)) in slices.iter().enumerate() {
404+ if idr {
405+ since_idr = 0;
406+ }
407+ assert_eq!(frame_num, since_idr % 32, "slice {i} frame_num");
408+ assert_eq!(poc, (since_idr * 2) % 64, "slice {i} pic_order_cnt_lsb");
409+ since_idr += 1;
410+ }
411+ let distinct: std::collections::BTreeSet<u32> = slices.iter().map(|s| s.1).collect();
412+ assert!(distinct.len() > 1, "frame_num never moved -- the rewrite did not run");
413+ // The rewrite is header-only: the picture still decodes.
414+ assert_eq!(decode(&stream).len(), count as usize);
415+}