forge
Explore
Log in

Don't you dare go Hollow

A third pyramid level -- a hidden mid ARF inside each mini-GOP

Browse files at this commit

55024804bc2bf0df0b99f0c7eb5b402306d1e611Ahmet Kaan GümüşParent: 8f9d371
  • feat
    • a third pyramid level -- a hidden mid ARF inside each mini-GOP
Show full message
feat(av1): a third pyramid level -- a hidden mid ARF inside each mini-GOP

Pyramid gains mid_q_offset (EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>[:<mid>],
'off' for the two-level shape). A group of at least four codes a second
hidden frame at the middle of its leaf run, off the anchor with the top ARF
as its backward reference; the leaves before it name it as ALTREF and the
first leaf after it starts its chain from it. Default stays two-level until
the long-GOP sweep decides.
crates/ec-av1/src/encoder.rsmodified+114 -26
@@ -379,6 +379,15 @@ pub struct Pyramid {
379 /// Added to `base_q_idx` for each shown leaf — positive, since nothing379 /// Added to `base_q_idx` for each shown leaf — positive, since nothing
380 /// predicts off a leaf but the next leaf.380 /// predicts off a leaf but the next leaf.
381 pub leaf_q_offset: i16,381 pub leaf_q_offset: i16,
382+ /// THE THIRD LEVEL, or `None` for the two-level pyramid: the offset a
383+ /// second hidden frame, at the middle of the mini-GOP, is coded at
384+ /// (between [`Pyramid::arf_q_offset`] and [`Pyramid::leaf_q_offset`], so
385+ /// the group reads key -> top ARF -> mid ARF -> leaves). The leaves
386+ /// before it name it as their `ALTREF_FRAME` and the leaves after it
387+ /// start their chain from it, which halves every leaf's distance to its
388+ /// nearest good reference. Ignored by a group of fewer than four
389+ /// pictures, where there is no leaf on both sides of a midpoint.
390+ pub mid_q_offset: Option<i16>,
382 }391 }
383 392
384 /// How many pictures the mini-GOP now being collected takes, given how many393 /// How many pictures the mini-GOP now being collected takes, given how many
@@ -416,7 +425,8 @@ fn absorb_tail() -> bool {
416 425
417 impl Pyramid {426 impl Pyramid {
418 /// The pyramid a run asks for through the environment:427 /// The pyramid a run asks for through the environment:
419- /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]`, with428+ /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>[:<mid>]]`,
429+ /// where `<mid>` is the third level's offset or `off` for none, with
420 /// `0` (or anything that is not a mini-GOP of at least 2, e.g. `flat`)430 /// `0` (or anything that is not a mini-GOP of at least 2, e.g. `flat`)
421 /// meaning the flat one-picture-one-frame path. UNSET is431 /// meaning the flat one-picture-one-frame path. UNSET is
422 /// [`Pyramid::default`]: the pyramid is what432 /// [`Pyramid::default`]: the pyramid is what
@@ -437,6 +447,14 @@ impl Pyramid {
437 mini_gop,447 mini_gop,
438 arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset),448 arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset),
439 leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset),449 leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset),
450+ // A fourth field is the mid-level offset; the literal `off` asks
451+ // for the two-level pyramid at the same shape (the A/B arm the
452+ // sweep needs), and no field at all keeps the default's.
453+ mid_q_offset: match f.next() {
454+ None => d.mid_q_offset,
455+ Some("off") => None,
456+ Some(v) => v.parse().ok().or(d.mid_q_offset),
457+ },
440 })458 })
441 }459 }
442 }460 }
@@ -671,6 +689,7 @@ impl Default for Pyramid {
671 mini_gop: 8,689 mini_gop: 8,
672 arf_q_offset: -32,690 arf_q_offset: -32,
673 leaf_q_offset: 16,691 leaf_q_offset: 16,
692+ mid_q_offset: MID_DEFAULT,
674 }693 }
675 }694 }
676 }695 }
@@ -702,6 +721,14 @@ const ANCHOR_SLOTS: [u8; 2] = [3, 4];
702 /// The slot the leaf chain refreshes and reads as `LAST_FRAME`.721 /// The slot the leaf chain refreshes and reads as `LAST_FRAME`.
703 const LEAF_SLOT: u8 = 0;722 const LEAF_SLOT: u8 = 0;
704 723
724+/// The slot the mid-level hidden frame of a three-level group refreshes
725+/// ([`Pyramid::mid_q_offset`]): free of the two anchors (3, 4), of the leaf
726+/// chain (0) and of `GOLDEN_SLOT` (1), so all four levels are live at once.
727+const MID_SLOT: u8 = 2;
728+
729+/// [`Pyramid::default`]'s third level (`None` = the two-level pyramid).
730+const MID_DEFAULT: Option<i16> = None;
731+
705 /// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per732 /// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per
706 /// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a733 /// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a
707 /// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a734 /// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a
@@ -1273,14 +1300,14 @@ impl Av1Encoder {
1273 altref_slot: u8,1300 altref_slot: u8,
1274 show_frame: bool,1301 show_frame: bool,
1275 level: Level,1302 level: Level,
1303+ // The quantizer offset comes from the CALLER, not from `level`: a
1304+ // three-level group codes two `Level::Arf` frames (the group's top
1305+ // ARF and the mid one) at different offsets, and they share the
1306+ // rate-control slot but not the offset.
1307+ offset: i16,
1276 ) -> Result<Packet> {1308 ) -> Result<Packet> {
1277 let render = (self.config.width, self.config.height);1309 let render = (self.config.width, self.config.height);
1278 let order_hint = (order & 0x7f) as u32;1310 let order_hint = (order & 0x7f) as u32;
1279- let pyramid = self.pyramid.expect("pyramid mode");
1280- let offset = match level {
1281- Level::Arf => pyramid.arf_q_offset,
1282- _ => pyramid.leaf_q_offset,
1283- };
1284 let base = self1311 let base = self
1285 .rate_loop1312 .rate_loop
1286 .as_ref()1313 .as_ref()
@@ -1385,6 +1412,7 @@ impl Av1Encoder {
1385 let anchor_slot = ANCHOR_SLOTS[self.anchor];1412 let anchor_slot = ANCHOR_SLOTS[self.anchor];
1386 let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor];1413 let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor];
1387 let (arf_order, arf_picture) = group.last().cloned().expect("non-empty");1414 let (arf_order, arf_picture) = group.last().cloned().expect("non-empty");
1415+ let pyramid = self.pyramid.expect("pyramid mode");
1388 if group.len() == 1 {1416 if group.len() == 1 {
1389 // Nothing to predict backward, so no hidden frame: one shown leaf1417 // Nothing to predict backward, so no hidden frame: one shown leaf
1390 // that also becomes the next group's anchor.1418 // that also becomes the next group's anchor.
@@ -1396,10 +1424,12 @@ impl Av1Encoder {
1396 GOLDEN_SLOT,1424 GOLDEN_SLOT,
1397 true,1425 true,
1398 Level::Leaf,1426 Level::Leaf,
1427+ pyramid.leaf_q_offset,
1399 )?);1428 )?);
1400 self.anchor = 1 - self.anchor;1429 self.anchor = 1 - self.anchor;
1401 return Ok(packets);1430 return Ok(packets);
1402 }1431 }
1432+ // The group's top level: the last picture, hidden, off the anchor.
1403 packets.push(self.encode_pyramid_inter(1433 packets.push(self.encode_pyramid_inter(
1404 arf_order,1434 arf_order,
1405 &arf_picture,1435 &arf_picture,
@@ -1408,17 +1438,28 @@ impl Av1Encoder {
1408 GOLDEN_SLOT,1438 GOLDEN_SLOT,
1409 false,1439 false,
1410 Level::Arf,1440 Level::Arf,
1441+ pyramid.arf_q_offset,
1411 )?);1442 )?);
1412- for (i, (order, picture)) in group[..group.len() - 1].iter().enumerate() {1443+ let leaves = group.len() - 1;
1413- let last_slot = if i == 0 { anchor_slot } else { LEAF_SLOT };1444+ // THE THIRD LEVEL: a second hidden frame at the middle of the leaf
1445+ // run, coded off the anchor with the top ARF as its own backward
1446+ // reference. It needs a leaf on both sides of it, so a group of
1447+ // three or fewer stays two-level.
1448+ let mid = pyramid.mid_q_offset.filter(|_| leaves >= 3).map(|offset| {
1449+ let at = (leaves - 1) / 2;
1450+ (at, offset)
1451+ });
1452+ if let Some((at, offset)) = mid {
1453+ let (order, picture) = group[at].clone();
1414 packets.push(self.encode_pyramid_inter(1454 packets.push(self.encode_pyramid_inter(
1415- *order,1455+ order,
1416- picture,1456+ &picture,
1417- last_slot,1457+ anchor_slot,
1418- LEAF_SLOT,1458+ MID_SLOT,
1419 next_anchor_slot,1459 next_anchor_slot,
1420- true,1460+ false,
1421- Level::Leaf,1461+ Level::Arf,
1462+ offset,
1422 )?);1463 )?);
1423 }1464 }
1424 let (seq, _) = crate::encode::key_frame_headers(1465 let (seq, _) = crate::encode::key_frame_headers(
@@ -1426,12 +1467,45 @@ impl Av1Encoder {
1426 self.config.height,1467 self.config.height,
1427 self.config.base_q_idx,1468 self.config.base_q_idx,
1428 )?;1469 )?;
1429- let mut data = crate::obu::temporal_delimiter();1470+ let show_existing = |encoder: &mut Self, slot: u8, order: u64| -> Result<Packet> {
1430- data.extend_from_slice(&crate::frame::show_existing_frame_obu(1471+ let mut data = crate::obu::temporal_delimiter();
1431- &seq,1472+ data.extend_from_slice(&crate::frame::show_existing_frame_obu(&seq, slot)?);
1432- next_anchor_slot,1473+ Ok(encoder.packet(data, false, order, Level::ShowExisting))
1433- )?);1474+ };
1434- packets.push(self.packet(data, false, arf_order, Level::ShowExisting));1475+ // The leaves, in display order, so every `show_existing_frame` lands
1476+ // in its own display position. A leaf before the mid frame names it
1477+ // as `ALTREF_FRAME` (the nearer backward reference); the first leaf
1478+ // after it starts its chain FROM it.
1479+ for (i, (order, picture)) in group[..leaves].iter().enumerate() {
1480+ if let Some((at, _)) = mid {
1481+ if i == at {
1482+ let packet = show_existing(self, MID_SLOT, *order)?;
1483+ packets.push(packet);
1484+ continue;
1485+ }
1486+ }
1487+ let last_slot = match (i, mid) {
1488+ (0, _) => anchor_slot,
1489+ (i, Some((at, _))) if i == at + 1 => MID_SLOT,
1490+ _ => LEAF_SLOT,
1491+ };
1492+ let altref_slot = match mid {
1493+ Some((at, _)) if i < at => MID_SLOT,
1494+ _ => next_anchor_slot,
1495+ };
1496+ packets.push(self.encode_pyramid_inter(
1497+ *order,
1498+ picture,
1499+ last_slot,
1500+ LEAF_SLOT,
1501+ altref_slot,
1502+ true,
1503+ Level::Leaf,
1504+ pyramid.leaf_q_offset,
1505+ )?);
1506+ }
1507+ let packet = show_existing(self, next_anchor_slot, arf_order)?;
1508+ packets.push(packet);
1435 self.anchor = 1 - self.anchor;1509 self.anchor = 1 - self.anchor;
1436 Ok(packets)1510 Ok(packets)
1437 }1511 }
@@ -2235,6 +2309,24 @@ mod tests {
2235 /// display-order list and fails here.2309 /// display-order list and fails here.
2236 #[test]2310 #[test]
2237 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {2311 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
2312+ pyramid_round_trip(Pyramid { mini_gop: 4, mid_q_offset: None, ..Pyramid::default() }, 2);
2313+ }
2314+
2315+ /// The same round trip over a THREE-level group (`mid_q_offset`): each
2316+ /// mini-GOP now codes two hidden frames -- the top ARF at the group's
2317+ /// last picture and the mid ARF at the middle of the leaf run -- and
2318+ /// re-outputs both with `show_existing_frame`, so a mid frame emitted in
2319+ /// the wrong display position, or twice, fails the display-order compare
2320+ /// against ffmpeg exactly as a top ARF does.
2321+ #[test]
2322+ fn a_three_level_pyramid_stream_decodes_in_display_order() {
2323+ pyramid_round_trip(
2324+ Pyramid { mini_gop: 8, mid_q_offset: Some(-8), ..Pyramid::default() },
2325+ 2,
2326+ );
2327+ }
2328+
2329+ fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) {
2238 let (width, height) = (128usize, 128usize);2330 let (width, height) = (128usize, 128usize);
2239 let config = EncoderConfig {2331 let config = EncoderConfig {
2240 width,2332 width,
@@ -2245,10 +2337,6 @@ mod tests {
2245 tile_cols_log2: 0,2337 tile_cols_log2: 0,
2246 tile_rows_log2: 0,2338 tile_rows_log2: 0,
2247 };2339 };
2248- let pyramid = Pyramid {
2249- mini_gop: 4,
2250- ..Pyramid::default()
2251- };
2252 // The content gate ([`Av1Encoder::encode_frames`]) would drop a2340 // The content gate ([`Av1Encoder::encode_frames`]) would drop a
2253 // screen-content stream to the flat path, and a synthetic test card2341 // screen-content stream to the flat path, and a synthetic test card
2254 // is exactly the few-colour picture the detector fires on: this gate2342 // is exactly the few-colour picture the detector fires on: this gate
@@ -2275,7 +2363,7 @@ mod tests {
2275 assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture");2363 assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture");
2276 assert_ne!(coded, sorted, "the pyramid never reordered anything");2364 assert_ne!(coded, sorted, "the pyramid never reordered anything");
2277 let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count();2365 let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count();
2278- assert_eq!(shown, 2, "one show_existing_frame per closed mini-GOP");2366+ assert_eq!(shown, hidden, "one show_existing_frame per hidden frame");
2279 for (i, p) in packets.iter().enumerate() {2367 for (i, p) in packets.iter().enumerate() {
2280 assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position");2368 assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position");
2281 }2369 }
@@ -2287,7 +2375,7 @@ mod tests {
2287 hist(Level::Leaf),2375 hist(Level::Leaf),
2288 hist(Level::ShowExisting),2376 hist(Level::ShowExisting),
2289 );2377 );
2290- assert_eq!(hist(Level::Arf), 2, "two hidden frames");2378+ assert_eq!(hist(Level::Arf), hidden, "hidden frames");
2291 let refs = crate::encode::take_ref_frame_hits();2379 let refs = crate::encode::take_ref_frame_hits();
2292 eprintln!(2380 eprintln!(
2293 "blocks per reference: LAST {} GOLDEN {} ALTREF {}",2381 "blocks per reference: LAST {} GOLDEN {} ALTREF {}",