B pictures, display order, frame_num gaps, zero-alloc on B
Browse files at this commit6e48da7f58e2235aaf0c8b58563f3db752b21797Parent: 18b2689- test
- B pictures, display order, frame_num gaps, zero-alloc on B
3 changed files +348 -132
- crates/ec-h264/src/decoder.rs +33 -22
- crates/ec-h264/src/dpb.rs +19 -0
- crates/ec-h264/tests/conformance.rs +296 -110
crates/ec-h264/src/decoder.rsmodified+33 -22
| @@ -304,13 +304,15 @@ impl Decoder { | ||
| 304 | 304 | self.cur.extend_borders(); |
| 305 | 305 | self.cur.complete = true; |
| 306 | 306 | self.last_decoded = self.cur.id; |
| 307 | - let sps = self.sps_map[self.cur.sps_id as usize] | |
| 308 | - .as_ref() | |
| 309 | - .ok_or_else(|| Error::corrupt("active SPS vanished"))? | |
| 310 | - .clone(); | |
| 307 | + let sps_id = self.cur.sps_id as usize; | |
| 308 | + let sps = self.sps_map[sps_id] | |
| 309 | + .take() | |
| 310 | + .ok_or_else(|| Error::corrupt("active SPS vanished"))?; | |
| 311 | 311 | let pic = core::mem::take(&mut self.cur); |
| 312 | 312 | let marking = self.has_marking.then_some(&self.cur_marking); |
| 313 | - self.dpb.store(pic, &sps, &self.cur_info, marking)?; | |
| 313 | + let stored = self.dpb.store(pic, &sps, &self.cur_info, marking); | |
| 314 | + self.sps_map[sps_id] = Some(sps); | |
| 315 | + stored?; | |
| 314 | 316 | self.has_picture = false; |
| 315 | 317 | self.pump_output(false) |
| 316 | 318 | } |
| @@ -381,11 +383,8 @@ impl Decoder { | ||
| 381 | 383 | |
| 382 | 384 | /// Copy a stored picture out as a cropped I420 frame. |
| 383 | 385 | fn picture_to_frame(&self, pic: &Picture) -> Result<VideoFrame> { |
| 384 | - let sps = self.sps_map[pic.sps_id as usize] | |
| 385 | - .as_ref() | |
| 386 | - .ok_or_else(|| Error::corrupt("active SPS vanished"))?; | |
| 387 | - let (w, h) = (sps.width as usize, sps.height as usize); | |
| 388 | - let (cx, cy) = (sps.crop.0 as usize, sps.crop.2 as usize); | |
| 386 | + let (w, h) = (pic.out_size.0 as usize, pic.out_size.1 as usize); | |
| 387 | + let (cx, cy) = (pic.crop.0 as usize, pic.crop.1 as usize); | |
| 389 | 388 | let copy = |p: &Plane8, x0: usize, y0: usize, w: usize, h: usize| -> Plane { |
| 390 | 389 | let mut out = vec![0u8; w * h]; |
| 391 | 390 | for row in 0..h { |
| @@ -400,14 +399,7 @@ impl Decoder { | ||
| 400 | 399 | copy(&pic.cr, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), |
| 401 | 400 | ]; |
| 402 | 401 | let mut frame = VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)?; |
| 403 | - if let Some(vui) = &sps.vui { | |
| 404 | - frame.color.full_range = vui.video_full_range; | |
| 405 | - if let Some((p, t, m)) = vui.colour_description { | |
| 406 | - frame.color.primaries = p; | |
| 407 | - frame.color.transfer = t; | |
| 408 | - frame.color.matrix = m; | |
| 409 | - } | |
| 410 | - } | |
| 402 | + frame.color = pic.color; | |
| 411 | 403 | frame.pts = pic.pts; |
| 412 | 404 | Ok(frame) |
| 413 | 405 | } |
| @@ -433,11 +425,30 @@ impl Decoder { | ||
| 433 | 425 | |
| 434 | 426 | check_supported(sps, pps, slice_type_code)?; |
| 435 | 427 | let sh = SliceHeader::parse(rbsp, header, sps, pps)?; |
| 436 | - let sps = sps.clone(); | |
| 437 | - let pps = pps.clone(); | |
| 438 | - | |
| 428 | + // Borrow the parameter sets out of their slots for the duration of the | |
| 429 | + // slice: cloning them per slice would allocate, and a decode loop that | |
| 430 | + // allocates per slice is the thing the whole layout is built to avoid. | |
| 431 | + let sps_slot = pps.sps_id as usize; | |
| 432 | + let sps = self.sps_map[sps_slot].take().expect("checked above"); | |
| 433 | + let pps = self.pps_map[pps_id as usize].take().expect("checked above"); | |
| 434 | + let outcome = self.decode_slice_data(&sps, &pps, &sh, header, rbsp, first_mb); | |
| 435 | + self.sps_map[sps_slot] = Some(sps); | |
| 436 | + self.pps_map[pps_id as usize] = Some(pps); | |
| 437 | + outcome | |
| 438 | + } | |
| 439 | + | |
| 440 | + #[allow(clippy::too_many_arguments)] | |
| 441 | + fn decode_slice_data( | |
| 442 | + &mut self, | |
| 443 | + sps: &Sps, | |
| 444 | + pps: &Pps, | |
| 445 | + sh: &SliceHeader, | |
| 446 | + header: NalHeader, | |
| 447 | + rbsp: &[u8], | |
| 448 | + first_mb: u32, | |
| 449 | + ) -> Result<NalOutcome> { | |
| 439 | 450 | if !self.has_picture || self.cur.complete { |
| 440 | - self.start_picture(&sps, &pps, &sh, header)?; | |
| 451 | + self.start_picture(sps, pps, sh, header)?; | |
| 441 | 452 | } |
| 442 | 453 | if self.cur.sps_id != sps.id { |
| 443 | 454 | return Err(Error::corrupt("SPS changed mid-picture")); |
crates/ec-h264/src/dpb.rsmodified+19 -0
| @@ -184,6 +184,14 @@ pub(crate) struct Picture { | ||
| 184 | 184 | /// travels with the picture rather than with the packet, because display |
| 185 | 185 | /// order reorders the two apart. |
| 186 | 186 | pub pts: Option<ec_core::timebase::Timestamp>, |
| 187 | + /// Cropped output size and the crop origin, in luma samples. A stored | |
| 188 | + /// picture describes its own output geometry so that emitting it needs no | |
| 189 | + /// lookup back into the parameter sets — which a later sequence may have | |
| 190 | + /// replaced by then. | |
| 191 | + pub out_size: (u32, u32), | |
| 192 | + pub crop: (u32, u32), | |
| 193 | + /// Colour description carried from the VUI. | |
| 194 | + pub color: ec_core::frame::ColorInfo, | |
| 187 | 195 | } |
| 188 | 196 | |
| 189 | 197 | impl Picture { |
| @@ -229,6 +237,17 @@ impl Picture { | ||
| 229 | 237 | self.long_term_frame_idx = 0; |
| 230 | 238 | self.frame_num_wrap = 0; |
| 231 | 239 | self.pic_num = 0; |
| 240 | + self.out_size = (sps.width, sps.height); | |
| 241 | + self.crop = (sps.crop.0, sps.crop.2); | |
| 242 | + self.color = ec_core::frame::ColorInfo::default(); | |
| 243 | + if let Some(vui) = &sps.vui { | |
| 244 | + self.color.full_range = vui.video_full_range; | |
| 245 | + if let Some((p, t, m)) = vui.colour_description { | |
| 246 | + self.color.primaries = p; | |
| 247 | + self.color.transfer = t; | |
| 248 | + self.color.matrix = m; | |
| 249 | + } | |
| 250 | + } | |
| 232 | 251 | } |
| 233 | 252 | |
| 234 | 253 | /// Replicate every plane's borders once the picture is fully reconstructed. |
crates/ec-h264/tests/conformance.rsmodified+296 -110
| @@ -376,11 +376,13 @@ fn jvt_cavlc_first_idr_bit_exact() { | ||
| 376 | 376 | ); |
| 377 | 377 | } |
| 378 | 378 | |
| 379 | -/// Steady-state decode loop performs zero heap allocations: after one warm-up | |
| 380 | -/// picture, re-decoding the same slices into the reused picture context | |
| 381 | -/// (including deblocking) must not allocate. Frame emission (`frame()`) | |
| 382 | -/// allocates the output planes and is measured separately as nonzero to prove | |
| 383 | -/// the counter works. | |
| 379 | +/// Steady-state slice decoding performs zero heap allocations. | |
| 380 | +/// | |
| 381 | +/// After a warm-up pass the picture pool, every per-picture array and the | |
| 382 | +/// parameter-set store are all sized, so decoding the same stream again must | |
| 383 | +/// not allocate at all: not per macroblock, not per slice, not per picture. | |
| 384 | +/// Emitting a frame is measured separately and *does* allocate — it hands the | |
| 385 | +/// caller owned planes — which also proves the counter is alive. | |
| 384 | 386 | #[test] |
| 385 | 387 | fn steady_state_decode_loop_zero_alloc() { |
| 386 | 388 | let base = vectors_dir(); |
| @@ -388,38 +390,59 @@ fn steady_state_decode_loop_zero_alloc() { | ||
| 388 | 390 | eprintln!("SKIP: fixtures missing"); |
| 389 | 391 | return; |
| 390 | 392 | } |
| 391 | - // One stream per entropy coder: the CABAC reader carries its 402 context | |
| 392 | - // variables inline for exactly this reason. | |
| 393 | - let mut dec = Decoder::new(); | |
| 394 | - for name in ["BA1_Sony_D", "CABA1_SVA_B"] { | |
| 395 | - let stream = find_stream(&base.join(name)).expect("fixture"); | |
| 393 | + // One stream per entropy coder, and one with B slices and multiple | |
| 394 | + // reference frames so the decoded picture buffer really recycles pictures. | |
| 395 | + for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B"] { | |
| 396 | + let Some(stream) = find_stream(&base.join(name)) else { | |
| 397 | + continue; | |
| 398 | + }; | |
| 396 | 399 | let bytes = std::fs::read(stream).unwrap(); |
| 397 | - // Warm-up: full first picture, growing every reusable buffer. | |
| 398 | - let _ = dec.decode_first_idr(&bytes).expect("warm-up decode"); | |
| 400 | + let mut dec = Decoder::new(); | |
| 401 | + let mut drive = |dec: &mut Decoder, count: bool| -> usize { | |
| 402 | + let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); | |
| 403 | + let mut frames = 0usize; | |
| 404 | + for nal in &nals { | |
| 405 | + if count { | |
| 406 | + COUNTING_HERE.with(|c| c.set(true)); | |
| 407 | + } | |
| 408 | + let outcome = dec.push_nal(nal); | |
| 409 | + if count { | |
| 410 | + COUNTING_HERE.with(|c| c.set(false)); | |
| 411 | + } | |
| 412 | + match outcome { | |
| 413 | + Ok(ec_h264::NalOutcome::PictureBoundary) => { | |
| 414 | + dec.end_picture().expect("end_picture"); | |
| 415 | + dec.push_nal(nal).expect("re-push"); | |
| 416 | + } | |
| 417 | + Ok(_) => {} | |
| 418 | + Err(e) => panic!("{name}: {e}"), | |
| 419 | + } | |
| 420 | + while dec.next_frame().is_some() { | |
| 421 | + frames += 1; | |
| 422 | + } | |
| 423 | + } | |
| 424 | + dec.flush().expect("flush"); | |
| 425 | + while dec.next_frame().is_some() { | |
| 426 | + frames += 1; | |
| 427 | + } | |
| 428 | + frames | |
| 429 | + }; | |
| 430 | + // Warm-up: every reusable buffer reaches its final size. | |
| 431 | + let warm = drive(&mut dec, false); | |
| 432 | + assert!(warm > 1, "{name}: only {warm} frames decoded"); | |
| 433 | + dec.reset_pictures(); | |
| 399 | 434 | |
| 400 | - // Steady state: same IDR slices again, counted. | |
| 401 | - let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); | |
| 402 | 435 | ALLOCS.store(0, Ordering::SeqCst); |
| 403 | - COUNTING_HERE.with(|c| c.set(true)); | |
| 404 | - let mut decoded = false; | |
| 405 | - for nal in &nals { | |
| 406 | - match dec.push_nal(nal) { | |
| 407 | - Ok(ec_h264::NalOutcome::PictureBoundary) => break, | |
| 408 | - Ok(ec_h264::NalOutcome::SliceDecoded) => decoded = true, | |
| 409 | - Ok(_) => {} | |
| 410 | - Err(e) => panic!("steady-state push failed: {e}"), | |
| 411 | - } | |
| 412 | - } | |
| 413 | - dec.end_picture().expect("end_picture"); | |
| 414 | - COUNTING_HERE.with(|c| c.set(false)); | |
| 415 | - assert!(decoded, "no slice decoded in steady-state pass of {name}"); | |
| 436 | + let again = drive(&mut dec, true); | |
| 416 | 437 | let n = ALLOCS.load(Ordering::SeqCst); |
| 417 | - assert_eq!(n, 0, "{name}: steady-state decode loop allocated {n} times"); | |
| 438 | + assert_eq!(again, warm, "{name}: frame count changed on the second pass"); | |
| 439 | + assert_eq!(n, 0, "{name}: steady-state slice decode allocated {n} times"); | |
| 418 | 440 | } |
| 441 | + | |
| 442 | + // Sanity: the counter is alive — emitting a frame does allocate. | |
| 419 | 443 | let bytes = std::fs::read(find_stream(&base.join("BA1_Sony_D")).unwrap()).unwrap(); |
| 444 | + let mut dec = Decoder::new(); | |
| 420 | 445 | let _ = dec.decode_first_idr(&bytes).expect("decode"); |
| 421 | - | |
| 422 | - // Sanity: the counter is alive — frame emission does allocate. | |
| 423 | 446 | ALLOCS.store(0, Ordering::SeqCst); |
| 424 | 447 | COUNTING_HERE.with(|c| c.set(true)); |
| 425 | 448 | let frame = dec.frame().expect("frame"); |
| @@ -882,86 +905,6 @@ fn refusals_name_a_feature_the_stream_really_uses() { | ||
| 882 | 905 | assert!(proved >= 2, "too few refusals proved against real streams"); |
| 883 | 906 | } |
| 884 | 907 | |
| 885 | -/// Inter slices are refused by name under CABAC as well as CAVLC: the | |
| 886 | -/// arithmetic decoder landing does not imply P and B macroblock parsing, and a | |
| 887 | -/// stream whose first picture decodes must not silently produce wrong pixels | |
| 888 | -/// for its second. | |
| 889 | -#[test] | |
| 890 | -fn inter_slices_under_cabac_are_refused_by_name() { | |
| 891 | - if !have_ffmpeg() { | |
| 892 | - eprintln!("SKIP: ffmpeg not on PATH"); | |
| 893 | - return; | |
| 894 | - } | |
| 895 | - let dir = scratch("inter-cabac"); | |
| 896 | - let stream = dir.join("gop.264"); | |
| 897 | - let ok = run( | |
| 898 | - "ffmpeg", | |
| 899 | - &[ | |
| 900 | - "-hide_banner", | |
| 901 | - "-loglevel", | |
| 902 | - "error", | |
| 903 | - "-y", | |
| 904 | - "-f", | |
| 905 | - "lavfi", | |
| 906 | - "-i", | |
| 907 | - "testsrc=size=176x144:rate=25:duration=1", | |
| 908 | - "-pix_fmt", | |
| 909 | - "yuv420p", | |
| 910 | - "-c:v", | |
| 911 | - "libx264", | |
| 912 | - "-frames:v", | |
| 913 | - "6", | |
| 914 | - "-profile:v", | |
| 915 | - "main", | |
| 916 | - "-coder", | |
| 917 | - "ac", | |
| 918 | - "-qp", | |
| 919 | - "26", | |
| 920 | - "-f", | |
| 921 | - "h264", | |
| 922 | - &stream.to_string_lossy(), | |
| 923 | - ], | |
| 924 | - ); | |
| 925 | - assert!(ok, "ffmpeg cannot encode a CABAC GOP"); | |
| 926 | - let bytes = std::fs::read(&stream).unwrap(); | |
| 927 | - | |
| 928 | - // The first (IDR) picture decodes; the first P slice must refuse by name. | |
| 929 | - let mut dec = Decoder::new(); | |
| 930 | - let first = dec.decode_first_idr(&bytes).expect("CABAC IDR decodes"); | |
| 931 | - assert_eq!((first.width, first.height), (176, 144)); | |
| 932 | - | |
| 933 | - let mut refusal = None; | |
| 934 | - let mut pictures = 1; | |
| 935 | - for nal in ec_h264_syntax::AnnexBIter::new(&bytes) { | |
| 936 | - match dec.push_nal(nal) { | |
| 937 | - Ok(ec_h264::NalOutcome::PictureBoundary) => { | |
| 938 | - dec.end_picture().expect("end_picture"); | |
| 939 | - pictures += 1; | |
| 940 | - if let Err(e) = dec.push_nal(nal) { | |
| 941 | - refusal = Some(e); | |
| 942 | - break; | |
| 943 | - } | |
| 944 | - } | |
| 945 | - Ok(_) => {} | |
| 946 | - Err(e) => { | |
| 947 | - refusal = Some(e); | |
| 948 | - break; | |
| 949 | - } | |
| 950 | - } | |
| 951 | - } | |
| 952 | - let _ = std::fs::remove_dir_all(&dir); | |
| 953 | - match refusal { | |
| 954 | - Some(Error::Unsupported { what, why }) => { | |
| 955 | - assert!( | |
| 956 | - what.contains("non-I slice") || why.contains("P/B"), | |
| 957 | - "refused as {what} ({why}), expected the inter-slice refusal" | |
| 958 | - ); | |
| 959 | - eprintln!("CABAC GOP: {pictures} intra picture(s) decoded, then refused: {what}"); | |
| 960 | - } | |
| 961 | - other => panic!("expected an inter-slice refusal, got {other:?}"), | |
| 962 | - } | |
| 963 | -} | |
| 964 | - | |
| 965 | 908 | /// The `avcC` entry path: parameter sets out of band and NAL units length |
| 966 | 909 | /// prefixed — how an MP4 or Matroska demuxer hands H.264 over. |
| 967 | 910 | #[test] |
| @@ -1236,3 +1179,246 @@ fn jvt_full_sequence_bit_exact() { | ||
| 1236 | 1179 | ); |
| 1237 | 1180 | assert!(failed.is_empty(), "{failed:#?}"); |
| 1238 | 1181 | } |
| 1182 | + | |
| 1183 | +/// Decode a whole stream in decode order rather than display order. | |
| 1184 | +fn decode_all_in_decode_order(bytes: &[u8]) -> Result<Vec<Vec<u8>>, Error> { | |
| 1185 | + let mut dec = Decoder::new(); | |
| 1186 | + dec.set_output_order(ec_h264::OutputOrder::Decode); | |
| 1187 | + let mut frames = Vec::new(); | |
| 1188 | + for nal in ec_h264_syntax::AnnexBIter::new(bytes) { | |
| 1189 | + if dec.push_nal(nal)? == NalOutcome::PictureBoundary { | |
| 1190 | + dec.end_picture()?; | |
| 1191 | + dec.push_nal(nal)?; | |
| 1192 | + } | |
| 1193 | + while let Some(f) = dec.next_frame() { | |
| 1194 | + frames.push(frame_bytes(&f)); | |
| 1195 | + } | |
| 1196 | + } | |
| 1197 | + dec.flush()?; | |
| 1198 | + while let Some(f) = dec.next_frame() { | |
| 1199 | + frames.push(frame_bytes(&f)); | |
| 1200 | + } | |
| 1201 | + Ok(frames) | |
| 1202 | +} | |
| 1203 | + | |
| 1204 | +/// Count I, P and B slices in an Annex B stream, straight from the slice | |
| 1205 | +/// headers. A test that claims to exercise B pictures has to prove the encoder | |
| 1206 | +/// actually produced some — x264's adaptive decision drops them on flat | |
| 1207 | +/// synthetic sources, and the test would then pass while measuring nothing. | |
| 1208 | +fn slice_type_counts(bytes: &[u8]) -> [usize; 3] { | |
| 1209 | + let mut counts = [0usize; 3]; | |
| 1210 | + for nal in ec_h264_syntax::AnnexBIter::new(bytes) { | |
| 1211 | + let Some((&header, payload)) = nal.split_first() else { | |
| 1212 | + continue; | |
| 1213 | + }; | |
| 1214 | + if !matches!(header & 0x1F, 1 | 5) { | |
| 1215 | + continue; | |
| 1216 | + } | |
| 1217 | + let mut r = ec_core::BitReader::new(payload); | |
| 1218 | + if r.read_ue().is_err() { | |
| 1219 | + continue; | |
| 1220 | + } | |
| 1221 | + let Ok(code) = r.read_ue() else { continue }; | |
| 1222 | + match code % 5 { | |
| 1223 | + 0 => counts[1] += 1, | |
| 1224 | + 1 => counts[2] += 1, | |
| 1225 | + 2 => counts[0] += 1, | |
| 1226 | + _ => {} | |
| 1227 | + } | |
| 1228 | + } | |
| 1229 | + counts | |
| 1230 | +} | |
| 1231 | + | |
| 1232 | +/// A GOP with B pictures, every frame bit-exact against ffmpeg, under both | |
| 1233 | +/// entropy coders and both direct modes. | |
| 1234 | +/// | |
| 1235 | +/// B pictures are where the decoded picture buffer earns its keep: two | |
| 1236 | +/// reference lists, direct prediction from a co-located picture, implicit | |
| 1237 | +/// weighting, and pictures that leave the buffer in a different order than | |
| 1238 | +/// they arrived. | |
| 1239 | +#[test] | |
| 1240 | +fn b_pictures_match_ffmpeg_every_frame() { | |
| 1241 | + if !have_ffmpeg() { | |
| 1242 | + eprintln!("SKIP: ffmpeg not on PATH"); | |
| 1243 | + return; | |
| 1244 | + } | |
| 1245 | + let dir = scratch("b-gop"); | |
| 1246 | + let cases: &[(&str, &[&str])] = &[ | |
| 1247 | + ("spatial", &["-x264-params", "bframes=3:b-adapt=0:direct=spatial:weightp=0"]), | |
| 1248 | + ("temporal", &["-x264-params", "bframes=3:b-adapt=0:direct=temporal:weightp=0"]), | |
| 1249 | + // B pictures used as references, which makes the buffer hold pictures | |
| 1250 | + // that are neither the newest nor the oldest. | |
| 1251 | + ( | |
| 1252 | + "pyramid", | |
| 1253 | + &["-x264-params", "bframes=3:b-adapt=0:b-pyramid=normal:direct=spatial"], | |
| 1254 | + ), | |
| 1255 | + // Weighted prediction on: explicit for P, implicit for B. | |
| 1256 | + ( | |
| 1257 | + "weighted", | |
| 1258 | + &["-x264-params", "bframes=3:b-adapt=0:weightp=2:weightb=1:direct=spatial"], | |
| 1259 | + ), | |
| 1260 | + ]; | |
| 1261 | + let mut failures = Vec::new(); | |
| 1262 | + let mut table = String::new(); | |
| 1263 | + for (mode, profile) in ENTROPY_MODES { | |
| 1264 | + if mode == "cavlc" { | |
| 1265 | + continue; // baseline forbids B pictures; main covers CAVLC below | |
| 1266 | + } | |
| 1267 | + for (tag, case) in cases { | |
| 1268 | + for coder in ["ac", "0"] { | |
| 1269 | + let mut extra = vec!["-profile:v", "main", "-coder", coder, "-qp", "26"]; | |
| 1270 | + extra.extend_from_slice(case); | |
| 1271 | + let name = format!("{tag}-{}", if coder == "ac" { "cabac" } else { "cavlc" }); | |
| 1272 | + match x264_encode_gop(&dir, &name, "176x144", 20, &extra) { | |
| 1273 | + Some(stream) => { | |
| 1274 | + let counts = slice_type_counts(&std::fs::read(&stream).unwrap()); | |
| 1275 | + if counts[2] == 0 { | |
| 1276 | + failures.push(format!("{name}: encoder produced no B slices")); | |
| 1277 | + continue; | |
| 1278 | + } | |
| 1279 | + match compare_sequence(&stream) { | |
| 1280 | + Ok(n) => table.push_str(&format!( | |
| 1281 | + "{name:<18} {n:>3} frames bit-exact ({} B slices)\n", | |
| 1282 | + counts[2] | |
| 1283 | + )), | |
| 1284 | + Err(e) => failures.push(format!("{name}: {e}")), | |
| 1285 | + } | |
| 1286 | + } | |
| 1287 | + None => failures.push(format!("{name}: ffmpeg cannot encode")), | |
| 1288 | + } | |
| 1289 | + } | |
| 1290 | + } | |
| 1291 | + let _ = profile; | |
| 1292 | + } | |
| 1293 | + let _ = std::fs::remove_dir_all(&dir); | |
| 1294 | + eprintln!("{table}"); | |
| 1295 | + assert!(failures.is_empty(), "{failures:#?}"); | |
| 1296 | +} | |
| 1297 | + | |
| 1298 | +/// Frames come out in display order, and that is a real reordering. | |
| 1299 | +/// | |
| 1300 | +/// Matching ffmpeg frame for frame already implies display order, but only if | |
| 1301 | +/// the stream actually reorders — so this also decodes the same stream in | |
| 1302 | +/// decode order and requires the two to differ. Without that second half the | |
| 1303 | +/// test would pass on a decoder that never reorders anything. | |
| 1304 | +#[test] | |
| 1305 | +fn output_is_display_order_and_the_reorder_is_real() { | |
| 1306 | + if !have_ffmpeg() { | |
| 1307 | + eprintln!("SKIP: ffmpeg not on PATH"); | |
| 1308 | + return; | |
| 1309 | + } | |
| 1310 | + let dir = scratch("order"); | |
| 1311 | + let extra = [ | |
| 1312 | + "-profile:v", | |
| 1313 | + "main", | |
| 1314 | + "-coder", | |
| 1315 | + "ac", | |
| 1316 | + "-qp", | |
| 1317 | + "26", | |
| 1318 | + "-x264-params", | |
| 1319 | + "bframes=3:b-adapt=0:b-pyramid=normal", | |
| 1320 | + ]; | |
| 1321 | + let stream = x264_encode_gop(&dir, "reorder", "176x144", 20, &extra).expect("encode"); | |
| 1322 | + let bytes = std::fs::read(&stream).unwrap(); | |
| 1323 | + let counts = slice_type_counts(&bytes); | |
| 1324 | + assert!(counts[2] > 0, "the encoder produced no B slices to reorder"); | |
| 1325 | + let display = decode_all(&bytes).expect("display order decode"); | |
| 1326 | + let decode = decode_all_in_decode_order(&bytes).expect("decode order decode"); | |
| 1327 | + let ffmpeg = ffmpeg_all_frames(&stream, display[0].len()).expect("ffmpeg"); | |
| 1328 | + let _ = std::fs::remove_dir_all(&dir); | |
| 1329 | + | |
| 1330 | + assert_eq!(display.len(), ffmpeg.len()); | |
| 1331 | + assert_eq!(decode.len(), display.len()); | |
| 1332 | + for (i, (a, b)) in display.iter().zip(&ffmpeg).enumerate() { | |
| 1333 | + assert!( | |
| 1334 | + first_diff(a, b).is_none(), | |
| 1335 | + "display-order frame {i} differs from ffmpeg" | |
| 1336 | + ); | |
| 1337 | + } | |
| 1338 | + // Every decode-order frame is somewhere in the display-order set: the two | |
| 1339 | + // are permutations of one another, not different pictures. | |
| 1340 | + for (i, f) in decode.iter().enumerate() { | |
| 1341 | + assert!( | |
| 1342 | + display.iter().any(|d| d == f), | |
| 1343 | + "decode-order frame {i} is not in the display-order output" | |
| 1344 | + ); | |
| 1345 | + } | |
| 1346 | + let moved = decode | |
| 1347 | + .iter() | |
| 1348 | + .zip(&display) | |
| 1349 | + .filter(|(a, b)| a != b) | |
| 1350 | + .count(); | |
| 1351 | + assert!( | |
| 1352 | + moved > 0, | |
| 1353 | + "decode order and display order are identical: the stream does not \ | |
| 1354 | + reorder, so this test proves nothing" | |
| 1355 | + ); | |
| 1356 | + eprintln!("{} of {} frames move under reordering", moved, display.len()); | |
| 1357 | +} | |
| 1358 | + | |
| 1359 | +/// A gap in frame_num decodes instead of stalling (clause 8.2.5.2). | |
| 1360 | +/// | |
| 1361 | +/// This is what a seek into the middle of a GOP looks like, and what a lossy | |
| 1362 | +/// transport delivers: the pictures a later frame_num implies never arrived. | |
| 1363 | +/// The spec infers them; a decoder that treats the gap as corruption drops | |
| 1364 | +/// every following picture, which is the failure an editor sees as a frozen | |
| 1365 | +/// preview after a seek. | |
| 1366 | +#[test] | |
| 1367 | +fn a_frame_num_gap_keeps_decoding() { | |
| 1368 | + if !have_ffmpeg() { | |
| 1369 | + eprintln!("SKIP: ffmpeg not on PATH"); | |
| 1370 | + return; | |
| 1371 | + } | |
| 1372 | + let dir = scratch("gap"); | |
| 1373 | + let extra = [ | |
| 1374 | + "-profile:v", | |
| 1375 | + "baseline", | |
| 1376 | + "-qp", | |
| 1377 | + "26", | |
| 1378 | + "-x264-params", | |
| 1379 | + "bframes=0:ref=1:keyint=100", | |
| 1380 | + ]; | |
| 1381 | + let stream = x264_encode_gop(&dir, "gap", "176x144", 12, &extra).expect("encode"); | |
| 1382 | + let bytes = std::fs::read(&stream).unwrap(); | |
| 1383 | + let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&bytes) | |
| 1384 | + .map(<[u8]>::to_vec) | |
| 1385 | + .collect(); | |
| 1386 | + let _ = std::fs::remove_dir_all(&dir); | |
| 1387 | + | |
| 1388 | + // Drop the fourth picture entirely, leaving frame_num 3 missing. | |
| 1389 | + let mut vcl_seen = 0; | |
| 1390 | + let mut dec = Decoder::new(); | |
| 1391 | + let mut frames = 0usize; | |
| 1392 | + let mut errors = Vec::new(); | |
| 1393 | + for unit in &units { | |
| 1394 | + if matches!(unit[0] & 0x1F, 1 | 5) { | |
| 1395 | + vcl_seen += 1; | |
| 1396 | + if vcl_seen == 4 { | |
| 1397 | + continue; // the lost picture | |
| 1398 | + } | |
| 1399 | + } | |
| 1400 | + match dec.push_nal(unit) { | |
| 1401 | + Ok(NalOutcome::PictureBoundary) => { | |
| 1402 | + dec.end_picture().expect("end_picture"); | |
| 1403 | + dec.push_nal(unit).expect("re-push"); | |
| 1404 | + } | |
| 1405 | + Ok(_) => {} | |
| 1406 | + Err(e) => errors.push(format!("{e}")), | |
| 1407 | + } | |
| 1408 | + while dec.next_frame().is_some() { | |
| 1409 | + frames += 1; | |
| 1410 | + } | |
| 1411 | + } | |
| 1412 | + dec.flush().expect("flush"); | |
| 1413 | + while dec.next_frame().is_some() { | |
| 1414 | + frames += 1; | |
| 1415 | + } | |
| 1416 | + assert!(errors.is_empty(), "decoding stopped at the gap: {errors:?}"); | |
| 1417 | + // 12 pictures coded, one dropped; the gap is filled by an inferred frame, | |
| 1418 | + // so every remaining picture still decodes and is output. | |
| 1419 | + assert!( | |
| 1420 | + frames >= 11, | |
| 1421 | + "only {frames} frames survived a single dropped picture" | |
| 1422 | + ); | |
| 1423 | + eprintln!("frame_num gap: {frames} frames decoded after dropping one picture"); | |
| 1424 | +} |