forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

enc_rc.rs240 lines, 10.1 KiBHistoryRawDownload
1//! Rate control for the sequence encoder: one QP per picture from a bit model,
2//! with a leaky bucket that pulls the stream back to its budget.
3//!
4//! This is the frame-level loop of the H.264 encoder's `rc.rs`, adapted to
5//! HEVC: QPs run 0..=51, and the QP a P picture is coded at includes the
6//! encoder's fixed P offset ([`crate::enc_p`]'s `P_QP_DELTA`). The model is the
7//! classic one: at a fixed complexity a picture's size scales as `2^(-QP/6)`, so
8//! `complexity = bits * 2^(QP/6)` measured on the last picture of the same type
9//! predicts the QP that hits the next target.
10
11use crate::enc_p::P_QP_DELTA;
12
13/// Frame-level rate control state for one sequence.
14#[derive(Debug, Clone)]
15pub(crate) struct BitRateControl {
16 /// Bits per picture at the configured bitrate and frame rate.
17 base: f64,
18 /// Virtual buffer occupancy in bits, positive when the stream is ahead of
19 /// its budget.
20 buffer: f64,
21 /// `bits * 2^(qp / 6)` of the last coded picture, per kind (0 = I, 1 = P).
22 complexity: [f64; 2],
23 /// The coded QP the last picture of each kind was coded at.
24 last_qp: [f64; 2],
25 /// Extra share of the group of pictures an IDR may borrow, as a multiple of
26 /// one picture's budget.
27 i_share: f64,
28 /// Pictures per group, over which that share is repaid.
29 gop: f64,
30 /// QP shift added to every picture, set per batch of GOPs by
31 /// [`offset_after_batch`] when GOPs run in parallel and cannot see each other's bits.
32 qp_offset: f64,
33 /// Bits of the last P picture coded at each QP, with the P-picture count it was seen at
34 /// (`None` when never seen). Content whose cost is a cliff in QP (near-black with
35 /// temporal noise) breaks the `2^(QP/6)` model; these observations bound it.
36 seen: [Option<(u64, u64)>; SEEN_QPS],
37 /// Lowest QP the model may pick: `-QpBdOffset` (0 at 8 bits).
38 qp_min: i32,
39 /// P pictures recorded so far.
40 p_count: u64,
41}
42
43/// A QP whose P picture cost more than this multiple of the picture target is a known
44/// overspend: the next pictures do not go to that QP or below while the observation is fresh.
45const CLIFF_RATIO: f64 = 1.5;
46/// Share of the bucket's credit (bits saved against the budget) that a single picture may
47/// spend above its cliff allowance, so saved bits can still pay for one expensive picture.
48const CREDIT_SHARE: f64 = 0.8;
49/// Most QP steps a P picture may drop below the previous P picture, bucket included.
50const MAX_DESCENT: i32 = 4;
51/// How many P pictures an observation stays valid for. Long enough to span the hunt back up
52/// from a cliff (+2 QP per picture), short enough that a scene change releases the floor.
53const CLIFF_AGE: u64 = 120;
54/// Table slots for the QPs -12..=51 (the 10-bit range), `SEEN_OFFSET` slots below 0.
55const SEEN_QPS: usize = 64;
56const SEEN_OFFSET: i32 = 12;
57
58impl BitRateControl {
59 /// Control for `kbps` kilobits per second at `fps` frames per second, with an
60 /// IDR every `gop` pictures.
61 pub(crate) fn new(kbps: u32, fps: f64, gop: usize, bit_depth: u32) -> BitRateControl {
62 let base = if kbps == 0 || fps <= 0.0 {
63 1.0
64 } else {
65 f64::from(kbps) * 1000.0 / fps
66 };
67 // An IDR costs many times a predicted picture and every picture of the
68 // group predicts from it, so it borrows a slice of each of them. Without
69 // this the bucket saturates on the IDR alone.
70 let gop = gop.max(1);
71 let i_share = (0.15 * (gop - 1) as f64).clamp(0.0, 8.0);
72 BitRateControl {
73 base,
74 buffer: 0.0,
75 complexity: [0.0; 2],
76 last_qp: [0.0; 2],
77 i_share,
78 gop: gop as f64,
79 qp_offset: 0.0,
80 seen: [None; SEEN_QPS],
81 qp_min: -6 * (bit_depth as i32 - 8),
82 p_count: 0,
83 }
84 }
85
86 /// Take over the complexity model and last QPs of `prev` (the rate model at the end of
87 /// the previous GOP) and the batch QP offset, with an empty bucket: this GOP's own pictures
88 /// are the only debt it corrects.
89 pub(crate) fn continue_from(&mut self, prev: &BitRateControl, offset: f64) {
90 self.complexity = prev.complexity;
91 self.last_qp = prev.last_qp;
92 self.qp_offset = offset;
93 self.seen = prev.seen;
94 self.p_count = prev.p_count;
95 }
96
97 /// Lowest coded QP a P picture may use: one above the highest QP that recently cost more
98 /// than [`CLIFF_RATIO`] times the target.
99 fn cliff_floor(&self, target: f64) -> i32 {
100 let mut floor = self.qp_min;
101 for (q, s) in self.seen.iter().enumerate() {
102 if let Some((bits, at)) = s
103 && self.p_count - *at <= CLIFF_AGE
104 && *bits as f64 > CLIFF_RATIO * target + CREDIT_SHARE * (-self.buffer).max(0.0)
105 {
106 floor = q as i32 - SEEN_OFFSET + 1;
107 }
108 }
109 floor
110 }
111
112 /// Coded QP for the next picture. An IDR is `idr == true`; a P picture's
113 /// result already includes the P offset.
114 pub(crate) fn frame_qp(&self, idr: bool) -> i32 {
115 let kind = usize::from(!idr);
116 let target = self.frame_target(idr);
117 let (mut qp, modelled) = if self.complexity[kind] > 0.0 {
118 (6.0 * (self.complexity[kind] / target).log2(), true)
119 } else if idr {
120 (27.0, false)
121 } else {
122 // First P picture: start from the IDR's coded quantiser.
123 (self.last_qp[0] + f64::from(P_QP_DELTA), false)
124 };
125 if modelled {
126 // Never move far in one step; a jumpy quantiser looks worse than a
127 // slightly wrong one. Asymmetric, as in the H.264 loop: a picture
128 // that undershoots reaches the QP it can afford quickly, one that
129 // overspends is pulled back gently.
130 let (down, up) = if idr { (6.0, 6.0) } else { (4.0, 2.0) };
131 qp = qp.clamp(self.last_qp[kind] - down, self.last_qp[kind] + up);
132 }
133 qp += self.qp_offset;
134 // Leaky bucket: two QP steps of correction per four pictures of debt, so
135 // a sustained overshoot is paid back within the clip.
136 qp += (self.buffer / (self.base.max(1.0) * 4.0) * 2.0).clamp(-12.0, 12.0);
137 let mut qp = qp.round().clamp(f64::from(self.qp_min), 51.0) as i32;
138 if !idr {
139 if self.complexity[kind] > 0.0 {
140 // The bucket's credit must not turn into a dive: descend at most
141 // `MAX_DESCENT` below the last P picture, so a cliff is met one observed step
142 // at a time.
143 qp = qp.max(self.last_qp[kind] as i32 - MAX_DESCENT);
144 }
145 qp = qp.max(self.cliff_floor(target).min(51));
146 }
147 qp
148 }
149
150 /// Record what a picture of kind `idr` coded at `qp` actually cost.
151 pub(crate) fn update(&mut self, idr: bool, qp: i32, bits: u64) {
152 let kind = usize::from(!idr);
153 let bits = bits as f64;
154 let c = bits * (f64::from(qp) / 6.0).exp2();
155 self.complexity[kind] = if self.complexity[kind] == 0.0 {
156 c
157 } else {
158 // Smoothed: one anomalous picture must not whipsaw the next.
159 0.7 * self.complexity[kind] + 0.3 * c
160 };
161 self.last_qp[kind] = f64::from(qp);
162 if !idr {
163 self.p_count += 1;
164 self.seen[(qp.clamp(-SEEN_OFFSET, 51) + SEEN_OFFSET) as usize] =
165 Some((bits as u64, self.p_count));
166 }
167 // Against the budget the picture was given, not the flat average, so an
168 // IDR that lands on its large target does not push the bucket.
169 let target = self.frame_target(idr);
170 // Wide enough that the integral keeps its memory: a clamp near one GOP of
171 // debt lets a sustained overshoot saturate the bucket and go uncorrected.
172 self.buffer = (self.buffer + bits - target).clamp(-64.0 * self.base, 64.0 * self.base);
173 }
174
175 /// Bits the picture is aiming for.
176 pub(crate) fn frame_target(&self, idr: bool) -> f64 {
177 if idr {
178 self.base * (1.0 + self.i_share)
179 } else {
180 // What each predicted picture of the group gives back to the IDR, so
181 // that the group as a whole still costs `gop * base`.
182 self.base * (1.0 - self.i_share / (self.gop - 1.0).max(1.0)).max(0.3)
183 }
184 }
185}
186
187/// Share of a batch's measured rate error (in QP steps) that the next batch's offset corrects.
188const BATCH_GAIN: f64 = 0.7;
189
190/// The QP offset for the next batch of GOPs, from the bits the last batch spent against its
191/// budget. Six QP steps is a factor of two in rate, as in the picture model.
192pub(crate) fn offset_after_batch(offset: f64, bits: f64, budget: f64) -> f64 {
193 if bits <= 0.0 || budget <= 0.0 {
194 return offset;
195 }
196 (offset + BATCH_GAIN * 6.0 * (bits / budget).log2()).clamp(-12.0, 12.0)
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 /// Fed pictures that always cost what the model says, the QP settles and the
204 /// bucket does not run away.
205 #[test]
206 fn converges_to_the_target() {
207 let mut rc = BitRateControl::new(4000, 25.0, 25, 8);
208 let complexity = 8.0e6;
209 let mut qps = Vec::new();
210 for f in 0..60 {
211 let idr = f % 25 == 0;
212 let qp = rc.frame_qp(idr);
213 let bits = (complexity * (-f64::from(qp) / 6.0).exp2()) as u64;
214 rc.update(idr, qp, bits);
215 qps.push(qp);
216 }
217 // Predicted pictures only: an IDR is meant to sit lower, since its
218 // budget is several times a predicted picture's.
219 let tail: Vec<i32> = (40..60).filter(|f| f % 25 != 0).map(|f| qps[f]).collect();
220 let spread = tail.iter().max().unwrap() - tail.iter().min().unwrap();
221 assert!(spread <= 3, "quantiser still hunting: {tail:?}");
222 assert!(
223 rc.buffer.abs() < 64.0 * rc.base,
224 "buffer ran away: {}",
225 rc.buffer
226 );
227 }
228
229 /// QP stays inside the HEVC range whatever the model is fed.
230 #[test]
231 fn qp_stays_in_range() {
232 let mut rc = BitRateControl::new(1, 30.0, 8, 8);
233 for f in 0..40 {
234 let idr = f % 8 == 0;
235 let qp = rc.frame_qp(idr);
236 assert!((0..=51).contains(&qp));
237 rc.update(idr, qp, 50_000_000);
238 }
239 }
240}