alpha2_host_core/rate_control.rs
1//! Rate-control vocabulary shared by every encoder backend.
2
3/// The largest quantizer a request may name, the top of AV1's scale on NVENC and Vulkan.
4pub const MAX_QUANTIZER: u32 = 255;
5
6/// A way of controlling an encoder's rate, independent of family spelling.
7#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
8pub enum RateControlMechanism {
9 /// Constant bitrate.
10 ConstantBitrate,
11 /// Variable (average) bitrate.
12 VariableBitrate,
13 /// Constant quantizer: `FFmpeg`'s `cqp`/`constqp`, the family of `crf`.
14 ConstantQuantizer,
15}
16
17impl RateControlMechanism {
18 /// Every mechanism, in the order the probe reports them.
19 pub const ALL: [Self; 3] = [
20 Self::ConstantBitrate,
21 Self::VariableBitrate,
22 Self::ConstantQuantizer,
23 ];
24
25 /// Stable identifier for diagnostics.
26 #[must_use]
27 pub const fn as_str(self) -> &'static str {
28 match self {
29 Self::ConstantBitrate => "cbr",
30 Self::VariableBitrate => "vbr",
31 Self::ConstantQuantizer => "cqp",
32 }
33 }
34}
35
36/// Which form of a resolved rate control an encoder actually ran.
37#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
38pub enum AppliedRateControl {
39 /// The constant quantizer.
40 Quantizer,
41 /// The quantizer mapped onto the encoder's own quality scale (`VideoToolbox`'s 0-1 `Quality`).
42 Quality,
43 /// The bitrate: none was asked for, or the encoder refused the quantizer.
44 Bitrate,
45}
46
47impl AppliedRateControl {
48 /// Stable identifier for the export result.
49 #[must_use]
50 pub const fn as_str(self) -> &'static str {
51 match self {
52 Self::Quantizer => "quantizer",
53 Self::Quality => "quality",
54 Self::Bitrate => "bitrate",
55 }
56 }
57}
58
59/// `VideoToolbox` quality (`kVTCompressionPropertyKey_Quality`, 0-1, higher better) per H.264
60/// quantizer at the levels' quantizers (`alpha2_media::level_quantizer`).
61///
62/// Each point holds `h264_videotoolbox` on Apple silicon within 0.5 dB PSNR-Y of `OpenH264` at the
63/// same level on a complex 1080p30 project (40.6 to 52.0 dB), at 0.66x-0.85x its bitrate. Grainy
64/// content needs about 0.05-0.10 more for the same match.
65const VIDEOTOOLBOX_QUALITY: [(u32, f64); 5] =
66 [(23, 0.65), (27, 0.57), (31, 0.50), (35, 0.40), (41, 0.25)];
67
68/// The `VideoToolbox` quality for an H.264 `quantizer`: a measured table interpolated,
69/// extrapolated along its end segments, rounded to hundredths and clamped to 0.01-1.
70#[must_use]
71pub fn videotoolbox_quality(quantizer: u32) -> f64 {
72 let table = &VIDEOTOOLBOX_QUALITY;
73 let segment = table
74 .windows(2)
75 .find(|pair| quantizer <= pair[1].0)
76 .unwrap_or(&table[table.len() - 2..]);
77 let ((q0, v0), (q1, v1)) = (segment[0], segment[1]);
78 let position = (f64::from(quantizer) - f64::from(q0)) / (f64::from(q1) - f64::from(q0));
79 let quality = v0 + (v1 - v0) * position;
80 (quality * 100.0).round().clamp(1.0, 100.0) / 100.0
81}