CBR, VBR and QVBR rate control for hardware encode
Browse files at this commit5fcd26f8c3a493d6f9ea266e8ed5eca5a6c38cb3Parent: 98dcdcf- feat
- CBR, VBR and QVBR rate control for hardware encode
2 changed files +142 -2
- crates/ec-hw/src/enc/mod.rs +6 -2
- crates/ec-hw/tests/gpu.rs +136 -0
crates/ec-hw/src/enc/mod.rsmodified+6 -2
| @@ -761,9 +761,13 @@ impl Encoder { | ||
| 761 | 761 | &misc_bytes(MISC_FRAME_RATE, &fr.words()), |
| 762 | 762 | )?); |
| 763 | 763 | if bits > 0 { |
| 764 | + // One rate window of buffer, three quarters full to start, which | |
| 765 | + // is what ffmpeg's vaapi encoder asks for: a two-window buffer | |
| 766 | + // let radeonsi's AV1 CBR undershoot the ask by 20% where ffmpeg's | |
| 767 | + // own av1_vaapi undershot by 8% on the same clip (measured). | |
| 764 | 768 | let hrd = crate::params::enc::Hrd { |
| 765 | - initial_buffer_fullness: bits, | |
| 766 | - buffer_size: bits * 2, | |
| 769 | + initial_buffer_fullness: bits / 4 * 3, | |
| 770 | + buffer_size: bits, | |
| 767 | 771 | }; |
| 768 | 772 | out.push(Buffer::from_bytes( |
| 769 | 773 | &self.context, |
crates/ec-hw/tests/gpu.rsmodified+136 -0
| @@ -1188,6 +1188,142 @@ fn av1_10bit_encode_agrees_between_two_decoders() { | ||
| 1188 | 1188 | ); |
| 1189 | 1189 | } |
| 1190 | 1190 | |
| 1191 | +/// Rate control: does an asked-for bitrate come back? | |
| 1192 | +/// | |
| 1193 | +/// CQP was the only mode the AV1 path had ever measured, because the config | |
| 1194 | +/// was created without a `VAConfigAttribRateControl` at all — a driver | |
| 1195 | +/// configured for CQP ignores a bitrate handed to it later. With the attribute | |
| 1196 | +/// set, three targets are encoded in each of CBR and VBR on his own 1080p | |
| 1197 | +/// content and the delivered rate is compared with the ask; the table is | |
| 1198 | +/// printed either way, including the pixel format and the mode, so the row | |
| 1199 | +/// says what it exercised. | |
| 1200 | +#[test] | |
| 1201 | +fn av1_encode_rate_control_lands() { | |
| 1202 | + let Some(display) = display() else { return }; | |
| 1203 | + let clips = real_clips(); | |
| 1204 | + let Some((label, source)) = clips.into_iter().next() else { | |
| 1205 | + eprintln!("skipped: no real-library manifest"); | |
| 1206 | + return; | |
| 1207 | + }; | |
| 1208 | + let dir = std::env::temp_dir().join("ec-hw-av1-rc"); | |
| 1209 | + let _ = std::fs::create_dir_all(&dir); | |
| 1210 | + let (width, height, frames, fps) = (1920u32, 1080u32, 60u32, 30u32); | |
| 1211 | + let y4m = dir.join("rc-source.y4m"); | |
| 1212 | + if !extract_y4m(&source, &y4m, width, height, frames) { | |
| 1213 | + eprintln!("skipped {label}: extraction failed"); | |
| 1214 | + return; | |
| 1215 | + } | |
| 1216 | + let Some(planes) = raw_frames(&y4m, width, height, frames) else { | |
| 1217 | + eprintln!("skipped {label}: no frames extracted"); | |
| 1218 | + return; | |
| 1219 | + }; | |
| 1220 | + | |
| 1221 | + println!("AV1 rate control on {label}, {width}x{height} yuv420p, {} frames at {fps} fps:", planes.len()); | |
| 1222 | + // QVBR is quality-defined: `bitrate` is a ceiling it may not exceed, not | |
| 1223 | + // a target it must reach, so asking it to land on the number would be | |
| 1224 | + // asking for the wrong thing. | |
| 1225 | + enum Ask { | |
| 1226 | + Within(f64), | |
| 1227 | + Ceiling, | |
| 1228 | + } | |
| 1229 | + for (mode_name, mode, ask) in [ | |
| 1230 | + ("CBR", RateControlMode::ConstantBitrate, Ask::Within(0.15)), | |
| 1231 | + ("VBR", RateControlMode::VariableBitrate, Ask::Within(0.25)), | |
| 1232 | + ("QVBR", RateControlMode::Qvbr { quality: 100 }, Ask::Ceiling), | |
| 1233 | + ] { | |
| 1234 | + let mut table: Vec<(u32, f64, f64)> = Vec::new(); | |
| 1235 | + for target in [2_000_000u32, 6_000_000, 12_000_000] { | |
| 1236 | + let mut config = EncoderConfig::new(EncCodec::Av1, width, height); | |
| 1237 | + config.framerate = (fps, 1); | |
| 1238 | + config.gop_size = 60; | |
| 1239 | + config.bitrate = target; | |
| 1240 | + config.rate_control = mode; | |
| 1241 | + let mut encoder = match Encoder::new(&display, config) { | |
| 1242 | + Ok(encoder) => encoder, | |
| 1243 | + Err(e) => { | |
| 1244 | + // A mode the driver does not advertise refuses at config | |
| 1245 | + // creation; that is the driver's answer, printed as one. | |
| 1246 | + eprintln!(" {mode_name}: refused by the driver ({e})"); | |
| 1247 | + break; | |
| 1248 | + } | |
| 1249 | + }; | |
| 1250 | + let mut bytes = Vec::new(); | |
| 1251 | + for (i, frame) in planes.iter().enumerate() { | |
| 1252 | + match encoder.encode( | |
| 1253 | + frame, | |
| 1254 | + FrameMetadata { timestamp: i as i64, force_keyframe: false }, | |
| 1255 | + ) { | |
| 1256 | + Ok(coded) => bytes.extend_from_slice(&coded.data), | |
| 1257 | + Err(e) => panic!("{mode_name} at {target} bps: encode failed ({e})"), | |
| 1258 | + } | |
| 1259 | + } | |
| 1260 | + let path = dir.join(format!("{mode_name}-{target}.obu")); | |
| 1261 | + std::fs::write(&path, &bytes).expect("write"); | |
| 1262 | + let delivered = | |
| 1263 | + bytes.len() as f64 * 8.0 * f64::from(fps) / f64::from(planes.len() as u32); | |
| 1264 | + let db = ffmpeg_psnr_at(&path, &y4m, fps).unwrap_or(f64::NAN); | |
| 1265 | + println!( | |
| 1266 | + " {mode_name} target {:>5} kbps -> delivered {:>6.0} kbps ({:+.1}%), {db:.2} dB", | |
| 1267 | + target / 1000, | |
| 1268 | + delivered / 1000.0, | |
| 1269 | + (delivered / f64::from(target) - 1.0) * 100.0 | |
| 1270 | + ); | |
| 1271 | + table.push((target, delivered, db)); | |
| 1272 | + } | |
| 1273 | + if table.len() < 3 { | |
| 1274 | + continue; | |
| 1275 | + } | |
| 1276 | + match ask { | |
| 1277 | + Ask::Within(tolerance) => { | |
| 1278 | + for &(target, delivered, _) in &table { | |
| 1279 | + let error = delivered / f64::from(target) - 1.0; | |
| 1280 | + assert!( | |
| 1281 | + error.abs() <= tolerance, | |
| 1282 | + "{mode_name} at {target} bps delivered {delivered:.0} bps ({:+.1}%), \ | |
| 1283 | + outside +/-{:.0}%", | |
| 1284 | + error * 100.0, | |
| 1285 | + tolerance * 100.0 | |
| 1286 | + ); | |
| 1287 | + } | |
| 1288 | + for pair in table.windows(2) { | |
| 1289 | + assert!( | |
| 1290 | + pair[1].2 > pair[0].2, | |
| 1291 | + "{mode_name}: PSNR is not monotone in the target ({:?} then {:?})", | |
| 1292 | + pair[0], | |
| 1293 | + pair[1] | |
| 1294 | + ); | |
| 1295 | + } | |
| 1296 | + } | |
| 1297 | + Ask::Ceiling => { | |
| 1298 | + for &(target, delivered, _) in &table { | |
| 1299 | + assert!( | |
| 1300 | + delivered <= f64::from(target) * 1.1, | |
| 1301 | + "{mode_name} at a {target} bps ceiling delivered {delivered:.0} bps" | |
| 1302 | + ); | |
| 1303 | + } | |
| 1304 | + } | |
| 1305 | + } | |
| 1306 | + } | |
| 1307 | +} | |
| 1308 | + | |
| 1309 | +/// [`ffmpeg_psnr`] with the rate pinned to `fps` on both inputs. | |
| 1310 | +fn ffmpeg_psnr_at(coded: &Path, source: &Path, fps: u32) -> Option<f64> { | |
| 1311 | + let rate = fps.to_string(); | |
| 1312 | + let out = Command::new("ffmpeg") | |
| 1313 | + .args(["-nostdin", "-v", "info", "-f", "obu", "-r", &rate]) | |
| 1314 | + .arg("-i") | |
| 1315 | + .arg(coded) | |
| 1316 | + .args(["-r", &rate]) | |
| 1317 | + .arg("-i") | |
| 1318 | + .arg(source) | |
| 1319 | + .args(["-lavfi", "psnr", "-f", "null", "-"]) | |
| 1320 | + .output() | |
| 1321 | + .ok()?; | |
| 1322 | + let text = String::from_utf8_lossy(&out.stderr); | |
| 1323 | + let field = text.split("average:").nth(1)?; | |
| 1324 | + field.split_whitespace().next()?.parse::<f64>().ok().filter(|v| v.is_finite()) | |
| 1325 | +} | |
| 1326 | + | |
| 1191 | 1327 | /// What the GPU's AV1 costs against software, on his own content. |
| 1192 | 1328 | /// |
| 1193 | 1329 | /// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen |