forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

slice_fix.rs527 lines, 18.5 KiBHistoryRawDownload
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
26use cros_codecs::codec::h264::parser::Level;
27use cros_codecs::codec::h265::parser::Level as H265Level;
28
29const NAL_SLICE: u8 = 1;
30const NAL_IDR: u8 = 5;
31const 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)]
35pub 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
55impl 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.
110fn 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
134fn 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
148fn 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
160struct Bits<'a> {
161 data: &'a [u8],
162 pos: usize,
163}
164
165impl<'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
198fn 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).
213fn 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.
272fn 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 H.264 level the plugin asks the driver for: [`engine::export::h264_level_idc`]
311/// as the vendored encoder's enum, 6.2 for anything it has no name for.
312pub fn h264_level(width: u32, height: u32, fps_num: u32, fps_den: u32) -> Level {
313 Level::try_from(engine::export::h264_level_idc(width, height, fps_num, fps_den))
314 .unwrap_or(Level::L6_2)
315}
316
317/// The lowest HEVC level (Table A.8, Main tier) whose luma picture size and
318/// sample rate hold the picture; 6.2 past the table.
319pub fn hevc_level(width: u32, height: u32, fps_num: u32, fps_den: u32) -> H265Level {
320 const LEVELS: [(H265Level, u64, u64); 13] = [
321 (H265Level::L1, 36_864, 552_960),
322 (H265Level::L2, 122_880, 3_686_400),
323 (H265Level::L2_1, 245_760, 7_372_800),
324 (H265Level::L3, 552_960, 16_588_800),
325 (H265Level::L3_1, 983_040, 33_177_600),
326 (H265Level::L4, 2_228_224, 66_846_720),
327 (H265Level::L4_1, 2_228_224, 133_693_440),
328 (H265Level::L5, 8_912_896, 267_386_880),
329 (H265Level::L5_1, 8_912_896, 534_773_760),
330 (H265Level::L5_2, 8_912_896, 1_069_547_520),
331 (H265Level::L6, 35_651_584, 1_069_547_520),
332 (H265Level::L6_1, 35_651_584, 2_139_095_040),
333 (H265Level::L6_2, 35_651_584, 4_278_190_080),
334 ];
335 let luma_ps = u64::from(width) * u64::from(height);
336 let fps = f64::from(fps_num.max(1)) / f64::from(fps_den.max(1));
337 let luma_sr = (luma_ps as f64 * fps).ceil() as u64;
338 LEVELS
339 .iter()
340 .find(|&&(_, max_ps, max_sr)| luma_ps <= max_ps && luma_sr <= max_sr)
341 .map_or(H265Level::L6_2, |&(level, ..)| level)
342}
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347
348 struct Writer {
349 bytes: Vec<u8>,
350 bits: usize,
351 }
352 impl Writer {
353 fn new() -> Self {
354 Self { bytes: Vec::new(), bits: 0 }
355 }
356 fn u(&mut self, width: u8, v: u32) {
357 for i in 0..usize::from(width) {
358 if self.bits % 8 == 0 {
359 self.bytes.push(0);
360 }
361 if (v >> (usize::from(width) - 1 - i)) & 1 == 1 {
362 let at = self.bits;
363 self.bytes[at / 8] |= 0x80 >> (at % 8);
364 }
365 self.bits += 1;
366 }
367 }
368 fn ue(&mut self, v: u32) {
369 let k = v + 1;
370 let len = 32 - k.leading_zeros() as u8;
371 self.u(len - 1, 0);
372 self.u(len, k);
373 }
374 fn done(mut self) -> Vec<u8> {
375 self.u(1, 1); // rbsp trailing bit
376 self.bytes
377 }
378 }
379
380 /// Main profile SPS the way cros-codecs writes one at a 2 s GOP and 30 fps:
381 /// MaxFrameNum 32, MaxPocLsb 64, frame_mbs_only.
382 fn sps() -> Vec<u8> {
383 let mut w = Writer::new();
384 w.u(8, 77);
385 w.u(8, 0);
386 w.u(8, 40);
387 w.ue(0); // sps id
388 w.ue(1); // log2_max_frame_num_minus4
389 w.ue(0); // poc type
390 w.ue(2); // log2_max_pic_order_cnt_lsb_minus4
391 w.ue(1); // max_num_ref_frames
392 w.u(1, 0);
393 w.ue(119);
394 w.ue(67);
395 w.u(1, 1); // frame_mbs_only
396 w.u(1, 1);
397 w.u(1, 0);
398 w.u(1, 0);
399 let mut nal = vec![0, 0, 0, 1, 0x67];
400 escape(&w.done(), &mut nal);
401 nal
402 }
403
404 /// A slice header as the driver writes it (both counters zero), with
405 /// `tail` bytes of "macroblock data" after it.
406 fn slice(idr: bool, tail: &[u8]) -> Vec<u8> {
407 let mut w = Writer::new();
408 w.ue(0); // first_mb_in_slice
409 w.ue(if idr { 7 } else { 5 }); // slice_type I / P
410 w.ue(0); // pps id
411 w.u(5, 0); // frame_num
412 if idr {
413 w.ue(0); // idr_pic_id
414 }
415 w.u(6, 0); // pic_order_cnt_lsb
416 let mut rbsp = w.done();
417 rbsp.extend_from_slice(tail);
418 let mut nal = vec![0, 0, 0, 1, if idr { 0x65 } else { 0x41 }];
419 escape(&rbsp, &mut nal);
420 nal
421 }
422
423 /// Reads the two counters back out of an escaped slice NAL.
424 fn read(nal: &[u8]) -> (u32, u32) {
425 let (start, end) = nal_ranges(nal)[0];
426 let idr = nal[start] & 0x1f == NAL_IDR;
427 let rbsp = unescape(&nal[start + 1..end]);
428 let mut b = Bits::new(&rbsp);
429 b.ue().unwrap();
430 b.ue().unwrap();
431 b.ue().unwrap();
432 let frame_num = b.bits(5).unwrap();
433 if idr {
434 b.ue().unwrap();
435 }
436 (frame_num, b.bits(6).unwrap())
437 }
438
439 #[test]
440 fn frame_num_holds_across_a_non_reference_picture() {
441 // 7.4.3: a non-reference picture (nal_ref_idc 0) takes PrevRefFrameNum
442 // + 1 like any other, but it is not a reference, so the picture after
443 // it takes the same frame_num. The POC still steps every picture.
444 let mut fix = SliceCounters::default();
445 let mut idr = sps();
446 idr.extend(slice(true, &[]));
447 fix.fix_au(&mut idr);
448 let mut p = slice(false, &[]);
449 fix.fix_au(&mut p);
450 assert_eq!(read(&p), (1, 2));
451 let mut b = slice(false, &[]);
452 b[4] = 0x01; // nal_ref_idc 0, type 1
453 fix.fix_au(&mut b);
454 assert_eq!(read(&b), (2, 4));
455 let mut p = slice(false, &[]);
456 fix.fix_au(&mut p);
457 assert_eq!(read(&p), (2, 6), "the picture after a non-reference keeps its frame_num");
458 }
459
460 #[test]
461 fn counters_step_per_picture_and_restart_at_idr() {
462 let mut fix = SliceCounters::default();
463 let mut idr = sps();
464 idr.extend(slice(true, &[0xAB; 40]));
465 fix.fix_au(&mut idr);
466 let slice_nal = nal_ranges(&idr)[1];
467 assert_eq!(read(&idr[slice_nal.0 - 4..]), (0, 0));
468 let mut seen = Vec::new();
469 for _ in 0..40 {
470 let mut p = slice(false, &[0xCD; 40]);
471 fix.fix_au(&mut p);
472 seen.push(read(&p));
473 }
474 // frame_num wraps at MaxFrameNum 32, POC lsb at 64 -- both as 8.2.1 derives.
475 assert_eq!(seen[0], (1, 2));
476 assert_eq!(seen[30], (31, 62));
477 assert_eq!(seen[31], (0, 0));
478 assert_eq!(seen[32], (1, 2));
479 let mut again = sps();
480 again.extend(slice(true, &[]));
481 fix.fix_au(&mut again);
482 let at = nal_ranges(&again)[1].0 - 4;
483 assert_eq!(read(&again[at..]), (0, 0), "an IDR restarts the count");
484 let mut p = slice(false, &[]);
485 fix.fix_au(&mut p);
486 assert_eq!(read(&p), (1, 2));
487 }
488
489 #[test]
490 fn macroblock_data_survives_byte_for_byte() {
491 let mut fix = SliceCounters::default();
492 let mut idr = sps();
493 idr.extend(slice(true, &[]));
494 fix.fix_au(&mut idr);
495 // A tail that the escaper has to touch both before and after: the
496 // rewritten header must not disturb it.
497 let tail = [0, 0, 1, 0, 0, 3, 0, 0, 0, 7, 0xFF, 0, 0];
498 let mut p = slice(false, &tail);
499 let before = unescape(&p[5..]);
500 fix.fix_au(&mut p);
501 let after = unescape(&p[5..]);
502 assert_eq!(before.len(), after.len());
503 assert_eq!(&before[3..], &after[3..]);
504 assert_eq!(&after[after.len() - tail.len()..], &tail);
505 }
506
507 #[test]
508 fn nothing_is_touched_before_an_sps() {
509 let mut fix = SliceCounters::default();
510 let mut p = slice(false, &[1, 2, 3]);
511 let before = p.clone();
512 fix.fix_au(&mut p);
513 assert_eq!(p, before);
514 }
515
516 #[test]
517 fn levels_follow_table_a1() {
518 assert_eq!(h264_level(1920, 1080, 30, 1), Level::L4);
519 assert_eq!(h264_level(1920, 1080, 60, 1), Level::L4_2);
520 assert_eq!(h264_level(3840, 1608, 24000, 1001), Level::L5_1);
521 assert_eq!(h264_level(3840, 2160, 60, 1), Level::L5_2);
522 assert_eq!(h264_level(640, 360, 30, 1), Level::L3);
523 assert_eq!(hevc_level(1920, 1080, 30, 1), H265Level::L4);
524 assert_eq!(hevc_level(3840, 2160, 30, 1), H265Level::L5);
525 assert_eq!(hevc_level(3840, 2160, 60, 1), H265Level::L5_1);
526 }
527}