edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 1 | //! Rate control: one QP per picture from a bit model, refined per macroblock |
| 2 | //! row inside each slice. |
| 3 | //! |
| 4 | //! The model is the classic one: at a fixed complexity a picture's size scales |
| 5 | //! as `2^(-QP/6)`, so `complexity = bits * 2^(QP/6)` measured on the last |
| 6 | //! picture of the same type predicts the QP that hits the next target. A |
| 7 | //! leaky-bucket term pulls the stream back when the model is wrong, which is |
| 8 | //! what makes the average bitrate hold over a clip rather than per picture. |
| 9 | |
| 10 | /// Constant-quantiser mode is a bitrate of zero: nothing to control. |
| 11 | #[derive(Debug, Clone)] |
| 12 | pub(crate) struct RateControl { |
| 13 | /// Bits per picture at the configured bitrate and frame rate. |
| 14 | base: f64, |
| 15 | /// Virtual buffer occupancy in bits, positive when the stream is ahead of |
| 16 | /// its budget. |
| 17 | buffer: f64, |
| 18 | /// `bits * 2^(qp / 6)` of the last coded picture, per type (0 = I, 1 = P). |
| 19 | complexity: [f64; 2], |
| 20 | /// The QP the last picture of each type was coded at. |
| 21 | last_qp: [f64; 2], |
| 22 | /// Extra share of the group of pictures an IDR is allowed to borrow, as a |
| 23 | /// multiple of one picture's budget. |
| 24 | i_share: f64, |
| 25 | /// Pictures per group, over which that share is repaid. |
| 26 | gop: f64, |
| 27 | fixed: Option<i32>, |
| 28 | } |
| 29 | |
| 30 | impl RateControl { |
| 31 | pub(crate) fn new(bitrate: u32, fps: f64, gop: u32, fixed_qp: Option<i32>) -> RateControl { |
| 32 | let base = if bitrate == 0 || fps <= 0.0 { |
| 33 | 0.0 |
| 34 | } else { |
| 35 | f64::from(bitrate) / fps |
| 36 | }; |
| 37 | // An intra picture costs many times a predicted one and every picture |
| 38 | // of the group predicts from it, so it borrows a slice of each of them |
| 39 | // — without this the bucket saturates on the IDR alone and the next |
| 40 | // half second is coded at a quantiser nothing justifies. |
| 41 | let i_share = (0.15 * f64::from(gop.saturating_sub(1))).clamp(0.0, 8.0); |
| 42 | RateControl { |
| 43 | base, |
| 44 | i_share, |
| 45 | gop: f64::from(gop.max(1)), |
| 46 | buffer: 0.0, |
| 47 | complexity: [0.0; 2], |
| 48 | last_qp: [26.0; 2], |
| 49 | fixed: fixed_qp.or(if base == 0.0 { Some(26) } else { None }), |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /// QP for the next picture. |
| 54 | pub(crate) fn frame_qp(&self, idr: bool) -> i32 { |
| 55 | if let Some(qp) = self.fixed { |
| 56 | return qp; |
| 57 | } |
| 58 | let kind = usize::from(!idr); |
| 59 | let target = self.frame_target(idr); |
| 60 | let mut qp = if self.complexity[kind] > 0.0 { |
| 61 | 6.0 * (self.complexity[kind] / target).log2() |
| 62 | } else if idr { |
| 63 | self.last_qp[1] |
| 64 | } else { |
| 65 | // First P picture: start from the I picture's quantiser. |
| 66 | self.last_qp[0] + 2.0 |
| 67 | }; |
| 68 | // Never move far in one step; a jumpy quantiser looks worse than a |
| 69 | // slightly wrong one. |
| 70 | // Asymmetric: a picture that costs less than its budget should reach |
| 71 | // the quantiser it can afford quickly (on static content that is where |
| 72 | // all the quality comes from), while a picture that overspends is |
| 73 | // pulled back gently, because a visible quantiser jump costs more than |
| 74 | // a few frames of debt. |
| 75 | let (down, up) = if idr { (6.0, 6.0) } else { (4.0, 2.0) }; |
| 76 | qp = qp.clamp(self.last_qp[kind] - down, self.last_qp[kind] + up); |
| 77 | // Leaky bucket: 1 QP per picture-budget of debt. The correction may |
| 78 | // reach 6 QP: a model that is biased by a few QP (an IDR that costs |
| 79 | // twice its share, every picture of the group under its target) must |
| 80 | // be pulled back by the bucket, and a 2 QP cap left a 7 % overshoot. |
| 81 | qp += (self.buffer / (self.base.max(1.0) * 4.0) * 4.0).clamp(-6.0, 6.0); |
| 82 | // The quantiser floor is a measured choice, not a spec limit: below QP 10 |
| 83 | // this encoder spends large numbers of bits on differences a viewer |
| 84 | // cannot see, and on static content it spends them re-coding pictures |
| 85 | // that were already right. Asking for a bitrate that QP 10 cannot fill |
| 86 | // therefore returns a smaller file rather than a wasteful one. |
| 87 | qp.round().clamp(10.0, 51.0) as i32 |
| 88 | } |
| 89 | |
| 90 | /// Record what the picture actually cost. |
| 91 | pub(crate) fn update(&mut self, idr: bool, qp: i32, bits: u64) { |
| 92 | if self.fixed.is_some() { |
| 93 | return; |
| 94 | } |
| 95 | let kind = usize::from(!idr); |
| 96 | let bits = bits as f64; |
| 97 | let c = bits * (f64::from(qp) / 6.0).exp2(); |
| 98 | // An IDR is taken as measured. Smoothing it made the IDR QP lag several |
| 99 | // GOPs behind the picture it was measured on (1080p at 1 Mb/s: the QP |
| 100 | // stepped up by the full clamp at every IDR). |
| 101 | self.complexity[kind] = if self.complexity[kind] == 0.0 || idr { |
| 102 | c |
| 103 | } else { |
| 104 | // Smoothed: one anomalous picture must not whipsaw the next. |
| 105 | 0.7 * self.complexity[kind] + 0.3 * c |
| 106 | }; |
| 107 | self.last_qp[kind] = f64::from(qp); |
| 108 | // The budget a picture of this type was given, not the flat average: |
| 109 | // an IDR that lands on its (large) target must not push the bucket. |
| 110 | let target = self.frame_target(idr); |
| 111 | self.buffer = (self.buffer + bits - target).clamp(-4.0 * self.base, 16.0 * self.base); |
| 112 | } |
| 113 | |
| 114 | /// Per-macroblock-row correction inside a slice: `spent` and `expected` are |
| 115 | /// bits so far and the pro-rata budget. |
| 116 | /// |
| 117 | /// This is the *fast* loop, and it has to be: on content whose bit cost |
| 118 | /// falls off a cliff with the quantiser — a screen capture, where dropping |
| 119 | /// one QP step re-codes half the picture — the picture-level model can |
| 120 | /// mispredict by an order of magnitude, and only a correction inside the |
| 121 | /// picture keeps that from blowing the budget and whipsawing the next |
| 122 | /// second of video. Asymmetric on purpose: overspending is capped hard, |
| 123 | /// underspending is given back gently. |
| 124 | pub(crate) fn row_delta(&self, spent: u64, expected: f64) -> i32 { |
| 125 | if self.fixed.is_some() || expected <= 0.0 { |
| 126 | return 0; |
| 127 | } |
| 128 | let ratio = (spent as f64 / expected).max(1e-3); |
| 129 | let delta = 6.0 * ratio.log2(); |
| 130 | delta.round().clamp(-2.0, 6.0) as i32 |
| 131 | } |
| 132 | |
| 133 | /// Bits the picture is aiming for, for the per-row budget. |
| 134 | pub(crate) fn frame_target(&self, idr: bool) -> f64 { |
| 135 | if idr { |
| 136 | self.base * (1.0 + self.i_share) |
| 137 | } else { |
| 138 | // What each predicted picture of the group gives back to the IDR, |
| 139 | // so that the group as a whole still costs `gop * base`. |
| 140 | self.base * (1.0 - self.i_share / (self.gop - 1.0).max(1.0)).max(0.3) |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | #[cfg(test)] |
| 146 | mod tests { |
| 147 | use super::*; |
| 148 | |
| 149 | /// A constant-bitrate run converges: fed pictures that always cost what the |
| 150 | /// model says, the quantiser settles and the buffer does not run away. |
| 151 | #[test] |
| 152 | fn converges_to_the_target() { |
| 153 | let mut rc = RateControl::new(4_000_000, 25.0, 25, None); |
| 154 | // A synthetic source whose complexity is fixed. |
| 155 | let complexity = 8.0e6; |
| 156 | let mut qps = Vec::new(); |
| 157 | for f in 0..60 { |
| 158 | let idr = f == 0; |
| 159 | let qp = rc.frame_qp(idr); |
| 160 | let bits = (complexity * (-f64::from(qp) / 6.0).exp2()) as u64; |
| 161 | rc.update(idr, qp, bits); |
| 162 | qps.push(qp); |
| 163 | } |
| 164 | let tail = &qps[40..]; |
| 165 | let spread = tail.iter().max().unwrap() - tail.iter().min().unwrap(); |
| 166 | assert!(spread <= 2, "quantiser still hunting: {tail:?}"); |
| 167 | assert!( |
| 168 | rc.buffer.abs() < 2.0 * rc.base, |
| 169 | "buffer ran away: {}", |
| 170 | rc.buffer |
| 171 | ); |
| 172 | } |
| 173 | |
| 174 | /// A bitrate of zero is constant-QP mode, and nothing moves it. |
| 175 | #[test] |
| 176 | fn zero_bitrate_is_constant_qp() { |
| 177 | let mut rc = RateControl::new(0, 25.0, 25, Some(31)); |
| 178 | assert_eq!(rc.frame_qp(true), 31); |
| 179 | rc.update(true, 31, 10_000_000); |
| 180 | assert_eq!(rc.frame_qp(false), 31); |
| 181 | assert_eq!(rc.row_delta(1_000_000, 1.0), 0); |
| 182 | } |
| 183 | } |