ec-h265: SequenceEncoder, a push-style IDR+P encoder (encode(frame, force_keyframe)), byte-identical to encode_sequence; forced IDRs restart the GOP
Browse files at this commit19320a9deb61d27aaaedf2f18948184ca7838730Parent: 7aaf7103 changed files +206 -65
- crates/ec-h265/src/enc_p.rs +159 -65
- crates/ec-h265/src/lib.rs +1 -0
- crates/ec-h265/tests/it/encode_threads.rs +46 -0
crates/ec-h265/src/enc_p.rsmodified+159 -65
| @@ -2489,73 +2489,167 @@ impl Encoder { | |||
| 2489 | I: IntoIterator<Item = VideoFrame>, | 2489 | I: IntoIterator<Item = VideoFrame>, |
| 2490 | F: FnMut(EncodedPicture) -> Result<()>, | 2490 | F: FnMut(EncodedPicture) -> Result<()>, |
| 2491 | { | 2491 | { |
| 2492 | - let mut prev: Option<PRecon> = None; | 2492 | + let mut st = self.seq_state(); |
| 2493 | - let mut prev_pic: Option<PrevPic> = None; | 2493 | + for frame in frames { |
| 2494 | - let mut ref_planes = RefPlanes::new( | 2494 | + sink(self.code_sequence_frame(&mut st, keyint, fixed_qp, rc, &frame, false)?)?; |
| 2495 | - self.coded_width, | 2495 | + } |
| 2496 | - self.coded_height, | 2496 | + Ok(()) |
| 2497 | - u32::from(self.cfg.bit_depth), | 2497 | + } |
| 2498 | - ); | 2498 | + |
| 2499 | - for (i, frame) in frames.into_iter().enumerate() { | 2499 | + fn seq_state(&self) -> SeqState { |
| 2500 | - let want = self.frame_format(); | 2500 | + SeqState { |
| 2501 | - if frame.format != want { | 2501 | + prev: None, |
| 2502 | + prev_pic: None, | ||
| 2503 | + ref_planes: RefPlanes::new( | ||
| 2504 | + self.coded_width, | ||
| 2505 | + self.coded_height, | ||
| 2506 | + u32::from(self.cfg.bit_depth), | ||
| 2507 | + ), | ||
| 2508 | + poc: 0, | ||
| 2509 | + } | ||
| 2510 | + } | ||
| 2511 | + | ||
| 2512 | + fn code_sequence_frame( | ||
| 2513 | + &self, | ||
| 2514 | + st: &mut SeqState, | ||
| 2515 | + keyint: usize, | ||
| 2516 | + fixed_qp: Option<i32>, | ||
| 2517 | + rc: &mut Option<BitRateControl>, | ||
| 2518 | + frame: &VideoFrame, | ||
| 2519 | + force_idr: bool, | ||
| 2520 | + ) -> Result<EncodedPicture> { | ||
| 2521 | + let want = self.frame_format(); | ||
| 2522 | + if frame.format != want { | ||
| 2523 | + return Err(Error::unsupported( | ||
| 2524 | + format!("HEVC encode of {:?}", frame.format), | ||
| 2525 | + format!("this encoder codes {want:?} at {} bits", self.cfg.bit_depth), | ||
| 2526 | + )); | ||
| 2527 | + } | ||
| 2528 | + if frame.width != self.cfg.width || frame.height != self.cfg.height { | ||
| 2529 | + return Err(Error::corrupt(format!( | ||
| 2530 | + "HEVC encode: frame is {}x{}, encoder configured for {}x{}", | ||
| 2531 | + frame.width, frame.height, self.cfg.width, self.cfg.height | ||
| 2532 | + ))); | ||
| 2533 | + } | ||
| 2534 | + let sixteen = self.cfg.bit_depth == 10; | ||
| 2535 | + let (y, ys) = plane_samples(&frame.planes[0], sixteen); | ||
| 2536 | + let (cb, cbs) = plane_samples(&frame.planes[1], sixteen); | ||
| 2537 | + let (cr, crs) = plane_samples(&frame.planes[2], sixteen); | ||
| 2538 | + let padded = self.pad_source(&y, ys, &cb, cbs, &cr, crs)?; | ||
| 2539 | + let poc = if force_idr { 0 } else { st.poc as i32 }; | ||
| 2540 | + st.poc = (poc as usize + 1) % keyint; | ||
| 2541 | + let idr = poc == 0; | ||
| 2542 | + let qp = match (rc.as_ref(), fixed_qp) { | ||
| 2543 | + (Some(model), _) => model.frame_qp(idr), | ||
| 2544 | + (None, Some(q)) if idr => q, | ||
| 2545 | + (None, Some(q)) => (q + P_QP_DELTA).clamp(self.qp_min(), 51), | ||
| 2546 | + (None, None) => 27, | ||
| 2547 | + }; | ||
| 2548 | + if idr { | ||
| 2549 | + let (coded, y, cb, cr) = self.code_picture_planes(&padded, qp)?; | ||
| 2550 | + if let Some(model) = rc.as_mut() { | ||
| 2551 | + model.update(true, qp, coded.au.len() as u64 * 8); | ||
| 2552 | + } | ||
| 2553 | + st.prev = Some(PRecon { y, cb, cr }); | ||
| 2554 | + st.prev_pic = None; | ||
| 2555 | + return Ok(coded); | ||
| 2556 | + } | ||
| 2557 | + let refp = st.prev.take().ok_or_else(|| { | ||
| 2558 | + Error::corrupt("HEVC P encode: no reference picture before a P picture") | ||
| 2559 | + })?; | ||
| 2560 | + let col = st.prev_pic.take(); | ||
| 2561 | + let (au, recon, pp) = code_p_picture( | ||
| 2562 | + self, | ||
| 2563 | + &padded, | ||
| 2564 | + &refp, | ||
| 2565 | + &mut st.ref_planes, | ||
| 2566 | + poc - 1, | ||
| 2567 | + poc, | ||
| 2568 | + qp, | ||
| 2569 | + col, | ||
| 2570 | + )?; | ||
| 2571 | + if let Some(model) = rc.as_mut() { | ||
| 2572 | + model.update(false, qp, au.len() as u64 * 8); | ||
| 2573 | + } | ||
| 2574 | + st.prev_pic = Some(pp); | ||
| 2575 | + let recon_frame = self | ||
| 2576 | + .cfg | ||
| 2577 | + .keep_recon | ||
| 2578 | + .then(|| self.crop_recon(&recon.y, &recon.cb, &recon.cr)); | ||
| 2579 | + st.prev = Some(recon); | ||
| 2580 | + Ok(EncodedPicture { | ||
| 2581 | + au, | ||
| 2582 | + qp, | ||
| 2583 | + recon: recon_frame, | ||
| 2584 | + }) | ||
| 2585 | + } | ||
| 2586 | +} | ||
| 2587 | + | ||
| 2588 | +struct SeqState { | ||
| 2589 | + prev: Option<PRecon>, | ||
| 2590 | + prev_pic: Option<PrevPic>, | ||
| 2591 | + ref_planes: RefPlanes, | ||
| 2592 | + poc: usize, | ||
| 2593 | +} | ||
| 2594 | + | ||
| 2595 | +/// A push-style IDR + P encoder: one frame in, one access unit out, with an | ||
| 2596 | +/// IDR every `keyint` frames or on request. | ||
| 2597 | +pub struct SequenceEncoder { | ||
| 2598 | + enc: Encoder, | ||
| 2599 | + keyint: usize, | ||
| 2600 | + fixed_qp: Option<i32>, | ||
| 2601 | + rc: Option<BitRateControl>, | ||
| 2602 | + st: SeqState, | ||
| 2603 | +} | ||
| 2604 | + | ||
| 2605 | +impl SequenceEncoder { | ||
| 2606 | + /// Wrap `enc`, refusing what [`Encoder::encode_sequence`] refuses. | ||
| 2607 | + pub fn new(enc: Encoder) -> Result<SequenceEncoder> { | ||
| 2608 | + let keyint = enc.cfg.keyint.max(1); | ||
| 2609 | + if keyint > 256 { | ||
| 2610 | + return Err(Error::unsupported( | ||
| 2611 | + format!("HEVC GOP of {keyint} pictures"), | ||
| 2612 | + "the picture order count is coded in 8 bits, so a GOP holds at most 256 pictures", | ||
| 2613 | + )); | ||
| 2614 | + } | ||
| 2615 | + let (fixed_qp, rc) = match enc.cfg.rate_control { | ||
| 2616 | + RateControl::ConstantQp(q) => (Some(q.clamp(enc.qp_min(), 51)), None), | ||
| 2617 | + RateControl::Bitrate { kbps, fps } => ( | ||
| 2618 | + None, | ||
| 2619 | + Some(BitRateControl::new( | ||
| 2620 | + kbps, | ||
| 2621 | + fps, | ||
| 2622 | + keyint, | ||
| 2623 | + u32::from(enc.cfg.bit_depth), | ||
| 2624 | + )), | ||
| 2625 | + ), | ||
| 2626 | + RateControl::TargetBits(_) => { | ||
| 2502 | return Err(Error::unsupported( | 2627 | return Err(Error::unsupported( |
| 2503 | - format!("HEVC encode of {:?}", frame.format), | 2628 | + "HEVC sequence encode at a per-picture bit target", |
| 2504 | - format!("this encoder codes {want:?} at {} bits", self.cfg.bit_depth), | 2629 | + "use RateControl::Bitrate for a sequence", |
| 2505 | )); | 2630 | )); |
| 2506 | } | 2631 | } |
| 2507 | - if frame.width != self.cfg.width || frame.height != self.cfg.height { | 2632 | + }; |
| 2508 | - return Err(Error::corrupt(format!( | 2633 | + let st = enc.seq_state(); |
| 2509 | - "HEVC encode: frame is {}x{}, encoder configured for {}x{}", | 2634 | + Ok(SequenceEncoder { |
| 2510 | - frame.width, frame.height, self.cfg.width, self.cfg.height | 2635 | + enc, |
| 2511 | - ))); | 2636 | + keyint, |
| 2512 | - } | 2637 | + fixed_qp, |
| 2513 | - let sixteen = self.cfg.bit_depth == 10; | 2638 | + rc, |
| 2514 | - let (y, ys) = plane_samples(&frame.planes[0], sixteen); | 2639 | + st, |
| 2515 | - let (cb, cbs) = plane_samples(&frame.planes[1], sixteen); | 2640 | + }) |
| 2516 | - let (cr, crs) = plane_samples(&frame.planes[2], sixteen); | 2641 | + } |
| 2517 | - let padded = self.pad_source(&y, ys, &cb, cbs, &cr, crs)?; | 2642 | + |
| 2518 | - let poc = (i % keyint) as i32; | 2643 | + /// Code `frame`, as an IDR when `force_keyframe` is set or the GOP is |
| 2519 | - let idr = poc == 0; | 2644 | + /// due; the GOP restarts from every IDR. |
| 2520 | - // The coded QP of this picture. A fixed QP keeps the P offset on P | 2645 | + pub fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<EncodedPicture> { |
| 2521 | - // pictures; the model's QP already carries it. | 2646 | + self.enc.code_sequence_frame( |
| 2522 | - let qp = match (rc.as_ref(), fixed_qp) { | 2647 | + &mut self.st, |
| 2523 | - (Some(model), _) => model.frame_qp(idr), | 2648 | + self.keyint, |
| 2524 | - (None, Some(q)) if idr => q, | 2649 | + self.fixed_qp, |
| 2525 | - (None, Some(q)) => (q + P_QP_DELTA).clamp(self.qp_min(), 51), | 2650 | + &mut self.rc, |
| 2526 | - (None, None) => 27, | 2651 | + frame, |
| 2527 | - }; | 2652 | + force_keyframe, |
| 2528 | - if idr { | 2653 | + ) |
| 2529 | - let (coded, y, cb, cr) = self.code_picture_planes(&padded, qp)?; | ||
| 2530 | - if let Some(model) = rc.as_mut() { | ||
| 2531 | - model.update(true, qp, coded.au.len() as u64 * 8); | ||
| 2532 | - } | ||
| 2533 | - prev = Some(PRecon { y, cb, cr }); | ||
| 2534 | - prev_pic = None; | ||
| 2535 | - sink(coded)?; | ||
| 2536 | - } else { | ||
| 2537 | - let refp = prev.take().ok_or_else(|| { | ||
| 2538 | - Error::corrupt("HEVC P encode: no reference picture before a P picture") | ||
| 2539 | - })?; | ||
| 2540 | - let col = prev_pic.take(); | ||
| 2541 | - let (au, recon, pp) = | ||
| 2542 | - code_p_picture(self, &padded, &refp, &mut ref_planes, poc - 1, poc, qp, col)?; | ||
| 2543 | - if let Some(model) = rc.as_mut() { | ||
| 2544 | - model.update(false, qp, au.len() as u64 * 8); | ||
| 2545 | - } | ||
| 2546 | - prev_pic = Some(pp); | ||
| 2547 | - let recon_frame = self | ||
| 2548 | - .cfg | ||
| 2549 | - .keep_recon | ||
| 2550 | - .then(|| self.crop_recon(&recon.y, &recon.cb, &recon.cr)); | ||
| 2551 | - prev = Some(recon); | ||
| 2552 | - sink(EncodedPicture { | ||
| 2553 | - au, | ||
| 2554 | - qp, | ||
| 2555 | - recon: recon_frame, | ||
| 2556 | - })?; | ||
| 2557 | - } | ||
| 2558 | - } | ||
| 2559 | - Ok(()) | ||
| 2560 | } | 2654 | } |
| 2561 | } | 2655 | } |
crates/ec-h265/src/lib.rsmodified+1 -0
| @@ -18,3 +18,4 @@ mod simd_tx; | |||
| 18 | pub mod transform; | 18 | pub mod transform; |
| 19 | 19 | ||
| 20 | pub use dec::{Decoder, Frame, NalOutcome}; | 20 | pub use dec::{Decoder, Frame, NalOutcome}; |
| 21 | +pub use enc_p::SequenceEncoder; | ||
crates/ec-h265/tests/it/encode_threads.rsmodified+46 -0
| @@ -128,3 +128,49 @@ fn wavefront_p_stream_decodes_to_the_encoder_reconstruction() { | |||
| 128 | "decoder output differs from the encoder reconstruction" | 128 | "decoder output differs from the encoder reconstruction" |
| 129 | ); | 129 | ); |
| 130 | } | 130 | } |
| 131 | + | ||
| 132 | +#[test] | ||
| 133 | +fn sequence_encoder_matches_encode_sequence_and_forces_idrs() { | ||
| 134 | + let frames = moving_clip(9, 320, 240); | ||
| 135 | + let (want, _) = encode_at(&frames, 4, 1); | ||
| 136 | + let make = || { | ||
| 137 | + let mut cfg = EncoderConfig::new(320, 240); | ||
| 138 | + cfg.rate_control = RateControl::ConstantQp(30); | ||
| 139 | + cfg.keyint = 4; | ||
| 140 | + cfg.keep_recon = true; | ||
| 141 | + cfg.threads = 1; | ||
| 142 | + ec_h265::SequenceEncoder::new(Encoder::new(cfg).expect("encoder")).expect("sequence") | ||
| 143 | + }; | ||
| 144 | + let mut seq = make(); | ||
| 145 | + let got: Vec<u8> = frames | ||
| 146 | + .iter() | ||
| 147 | + .flat_map(|f| seq.encode(f, false).expect("encode").au) | ||
| 148 | + .collect(); | ||
| 149 | + assert!( | ||
| 150 | + got == want, | ||
| 151 | + "push-style stream differs from encode_sequence" | ||
| 152 | + ); | ||
| 153 | + let mut seq = make(); | ||
| 154 | + let mut stream = Vec::new(); | ||
| 155 | + let mut recon = Vec::new(); | ||
| 156 | + for (t, f) in frames.iter().enumerate() { | ||
| 157 | + let pic = seq.encode(f, t == 2).expect("encode"); | ||
| 158 | + stream.extend_from_slice(&pic.au); | ||
| 159 | + for p in &pic.recon.expect("recon").planes { | ||
| 160 | + recon.extend_from_slice(&p.data); | ||
| 161 | + } | ||
| 162 | + } | ||
| 163 | + let mut dec = Decoder::new(); | ||
| 164 | + dec.decode_annex_b(&stream).expect("the stream decodes"); | ||
| 165 | + dec.flush().expect("the stream flushes"); | ||
| 166 | + let mut decoded = Vec::new(); | ||
| 167 | + while let Some(frame) = dec.next_frame() { | ||
| 168 | + for plane in [&frame.picture.y, &frame.picture.cb, &frame.picture.cr] { | ||
| 169 | + decoded.extend(plane.iter().map(|&v| v as u8)); | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | + assert!( | ||
| 173 | + decoded == recon, | ||
| 174 | + "forced-IDR stream does not decode to the reconstruction" | ||
| 175 | + ); | ||
| 176 | +} | ||