diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index d03c5238..b00478fd 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -161,6 +161,7 @@ pub struct Encoder { coded_width: usize, coded_height: usize, frames: u64, + gop_position: u64, frame_num: u32, idr_pic_id: u32, next_id: i32, @@ -281,6 +282,7 @@ impl Encoder { coded_width: mb_w as usize * 16, coded_height: mb_h as usize * 16, frames: 0, + gop_position: 0, frame_num: 0, idr_pic_id: 0, next_id: 0, @@ -336,6 +338,16 @@ impl Encoder { /// Code one picture, in display order, and hand back its access unit. pub fn encode(&mut self, frame: &PictureView<'_>) -> Result { + self.encode_with(frame, false) + } + + /// [`Encoder::encode`], coding the picture as an IDR when `force_keyframe` + /// is set; the GOP restarts from it. + pub fn encode_with( + &mut self, + frame: &PictureView<'_>, + force_keyframe: bool, + ) -> Result { if frame.width != self.cfg.width || frame.height != self.cfg.height { return Err(Error::corrupt("frame size differs from the encoder's")); } @@ -347,11 +359,13 @@ impl Encoder { let pps_rbsp = write_pps(self.cfg.cabac, self.cfg.transform_8x8, self.cqo); self.pps_nal = annex_b(NalUnitType::Pps, 3, &pps_rbsp); } - let idr = self.cfg.gop_size <= 1 - || self - .frames - .is_multiple_of(u64::from(self.cfg.gop_size.max(1))); - let idr = idr || !self.have_reference; + let idr = force_keyframe + || !self.have_reference + || self.gop_position >= u64::from(self.cfg.gop_size.max(1)); + if idr { + self.gop_position = 0; + } + self.gop_position += 1; let qp = self.rc.frame_qp(idr); if idr { self.frame_num = 0; diff --git a/crates/ec-h264/tests/it/encode.rs b/crates/ec-h264/tests/it/encode.rs index 8cc35a72..2342b0b5 100644 --- a/crates/ec-h264/tests/it/encode.rs +++ b/crates/ec-h264/tests/it/encode.rs @@ -1620,3 +1620,24 @@ fn balanced_partitions_decode_bit_exactly() { "the sweep has to code every shape, or it proves nothing about them" ); } + +#[test] +fn force_keyframe_restarts_the_gop() { + let (w, h) = (64, 64); + let mut clip = Clip::new(w, h); + let mut cfg = EncoderConfig::new(w as u32, h as u32); + cfg.gop_size = 4; + cfg.threads = 1; + let mut enc = Encoder::new(cfg).expect("encoder"); + let mut stream = Vec::new(); + let keys: Vec = (0..8) + .map(|t| { + clip.render(t); + let pic = enc.encode_with(&clip.view(), t == 2).expect("encode"); + stream.extend_from_slice(&pic.au); + pic.key_frame + }) + .collect(); + assert_eq!(keys, [true, false, true, false, false, false, true, false]); + assert_eq!(decode_all(&stream).len(), 8); +}