forge
Explore
Log in

Don't you dare go Hollow

ec-h264: Encoder::encode_with(frame, force_keyframe) codes an IDR on demand and restarts the GOP from it

Browse files at this commit

7aaf710b0957f0b8b730d7e825fa45d70606efc7Ahmet Kaan GümüşParent: d27d669
crates/ec-h264/src/enc/mod.rsmodified+19 -5
@@ -161,6 +161,7 @@ pub struct Encoder {
161161 coded_width: usize,
162162 coded_height: usize,
163163 frames: u64,
164+ gop_position: u64,
164165 frame_num: u32,
165166 idr_pic_id: u32,
166167 next_id: i32,
@@ -281,6 +282,7 @@ impl Encoder {
281282 coded_width: mb_w as usize * 16,
282283 coded_height: mb_h as usize * 16,
283284 frames: 0,
285+ gop_position: 0,
284286 frame_num: 0,
285287 idr_pic_id: 0,
286288 next_id: 0,
@@ -336,6 +338,16 @@ impl Encoder {
336338
337339 /// Code one picture, in display order, and hand back its access unit.
338340 pub fn encode(&mut self, frame: &PictureView<'_>) -> Result<EncodedPicture> {
341+ self.encode_with(frame, false)
342+ }
343+
344+ /// [`Encoder::encode`], coding the picture as an IDR when `force_keyframe`
345+ /// is set; the GOP restarts from it.
346+ pub fn encode_with(
347+ &mut self,
348+ frame: &PictureView<'_>,
349+ force_keyframe: bool,
350+ ) -> Result<EncodedPicture> {
339351 if frame.width != self.cfg.width || frame.height != self.cfg.height {
340352 return Err(Error::corrupt("frame size differs from the encoder's"));
341353 }
@@ -347,11 +359,13 @@ impl Encoder {
347359 let pps_rbsp = write_pps(self.cfg.cabac, self.cfg.transform_8x8, self.cqo);
348360 self.pps_nal = annex_b(NalUnitType::Pps, 3, &pps_rbsp);
349361 }
350- let idr = self.cfg.gop_size <= 1
351- || self
352- .frames
353- .is_multiple_of(u64::from(self.cfg.gop_size.max(1)));
354- let idr = idr || !self.have_reference;
362+ let idr = force_keyframe
363+ || !self.have_reference
364+ || self.gop_position >= u64::from(self.cfg.gop_size.max(1));
365+ if idr {
366+ self.gop_position = 0;
367+ }
368+ self.gop_position += 1;
355369 let qp = self.rc.frame_qp(idr);
356370 if idr {
357371 self.frame_num = 0;
crates/ec-h264/tests/it/encode.rsmodified+21 -0
@@ -1620,3 +1620,24 @@ fn balanced_partitions_decode_bit_exactly() {
16201620 "the sweep has to code every shape, or it proves nothing about them"
16211621 );
16221622 }
1623+
1624+#[test]
1625+fn force_keyframe_restarts_the_gop() {
1626+ let (w, h) = (64, 64);
1627+ let mut clip = Clip::new(w, h);
1628+ let mut cfg = EncoderConfig::new(w as u32, h as u32);
1629+ cfg.gop_size = 4;
1630+ cfg.threads = 1;
1631+ let mut enc = Encoder::new(cfg).expect("encoder");
1632+ let mut stream = Vec::new();
1633+ let keys: Vec<bool> = (0..8)
1634+ .map(|t| {
1635+ clip.render(t);
1636+ let pic = enc.encode_with(&clip.view(), t == 2).expect("encode");
1637+ stream.extend_from_slice(&pic.au);
1638+ pic.key_frame
1639+ })
1640+ .collect();
1641+ assert_eq!(keys, [true, false, true, false, false, false, true, false]);
1642+ assert_eq!(decode_all(&stream).len(), 8);
1643+}