Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

openh264 takes the fixed quantiser it's asked for (part of #28). With rate control off it ignored the QP range and wrote QP 26: the optimized copy's QP 16 and a GOP's QP gave the same bytes as any other. fixed_qp now uses its Quality mode with the range pinned. That mode needs a bitrate other than 0 (it moves nothing once the QP is pinned), and it refuses a QP under 14, so a lower one is raised to 14. A frame too detailed for openh264's buffer at QP 16 (some 1.6 MB a 1080p frame, noise rather than footage) fails with Native:3, so the copy is made again at QP 26, as every copy was before. io/soft/tests/qp.rs: QP 16 writes over twice QP 40's bytes for the copy and a GOP, a GOP is the same bytes each time, and QP 4 is QP 14; before, 12 and 40 were identical

shinyobjectz0c419d8164db
diff --git a/io/media/src/mezz.rs b/io/media/src/mezz.rs
index e5347b28..ab5da807 100644
--- a/io/media/src/mezz.rs
+++ b/io/media/src/mezz.rs
@@ -72,6 +72,13 @@ const INTRA_QP: u8 = 16;
/// all-intra H.264 at `part`: the copy's frame k is the source's frame at the range's start + k / fps.
#[cfg(all(feature = "h264", not(target_vendor = "apple")))]
fn encode(src: &Path, part: &Path, range: Option<(usize, usize)>, p: &Probe) -> R<()> {
+ // a frame too detailed for openh264's buffer at INTRA_QP (Native:3: noise, some 1.6 MB a 1080p frame) is made
+ // again at QP 26, which every copy had until openh264 took the quantiser asked for (#28)
+ encode_at(src, part, range, p, INTRA_QP).or_else(|e| if e.contains("Native:3") { encode_at(src, part, range, p, 26) } else { Err(e) })
+}
+
+#[cfg(all(feature = "h264", not(target_vendor = "apple")))]
+fn encode_at(src: &Path, part: &Path, range: Option<(usize, usize)>, p: &Probe, qp: u8) -> R<()> {
let (t0, t1) = match range {
Some((a, b)) => (a as f64 * p.frame_secs(), (b + 1) as f64 * p.frame_secs()),
None => (0.0, p.secs),
@@ -94,7 +101,7 @@ fn encode(src: &Path, part: &Path, range: Option<(usize, usize)>, p: &Probe) ->
}
let fps = if info.fps > 0.0 { info.fps } else { p.fps };
let opts = crate::EncodeOpts { width: info.width, height: info.height, fps, kbps: 0, quality: None, nv12: false, realtime: false };
- let mut enc = crate::soft::h264_encoder(part, &opts, Some(INTRA_QP))?;
+ let mut enc = crate::soft::h264_encoder(part, &opts, Some(qp))?;
let n = ((t1 - t0) * fps).round().max(1.0) as usize;
for k in 0..n {
enc.push(&dec.frame_at(t0 + k as f64 / fps)?.rgba)?;
diff --git a/io/soft/src/h264.rs b/io/soft/src/h264.rs
index ec08bab0..047d7b50 100644
--- a/io/soft/src/h264.rs
+++ b/io/soft/src/h264.rs
@@ -224,9 +224,9 @@ pub fn mux_h264(
})
}
-/// An encoder for one GOP that depends on nothing before it: fixed quantiser (no rate control state carried
-/// between frames), the first frame an IDR with its SPS/PPS, no other keyframes. Two GOPs made from the same frames
-/// are the same bytes, so an export can be stitched from GOPs made at different times.
+/// An encoder for one GOP that depends on nothing before it: fixed quantiser (fixed_qp: the rate control can't move
+/// it, so no state is carried between frames), the first frame an IDR with its SPS/PPS, no other keyframes. Two GOPs
+/// made from the same frames are the same bytes, so an export can be stitched from GOPs made at different times.
#[cfg(feature = "h264")]
pub struct GopEncoder {
pub(crate) enc: H264Encoder,
@@ -239,8 +239,6 @@ impl GopEncoder {
pub fn new(w: u32, h: u32, fps: f64, qp: u8) -> R<GopEncoder> {
let config = EncoderConfig::new()
.max_frame_rate(FrameRate::from_hz(fps as f32))
- .rate_control_mode(RateControlMode::Off)
- .qp(openh264::encoder::QpRange::new(qp, qp))
.skip_frames(false)
.scene_change_detect(false)
.adaptive_quantization(false)
@@ -251,7 +249,7 @@ impl GopEncoder {
.num_threads(1)
// BT.709 limited range, as h264_encoder tags its stream
.vui(openh264::encoder::VuiConfig::bt709());
- let enc = H264Encoder::with_api_config(OpenH264API::from_source(), config)
+ let enc = H264Encoder::with_api_config(OpenH264API::from_source(), crate::fixed_qp(config, qp))
.map_err(|e| format!("openh264: {e}"))?;
Ok(GopEncoder {
enc,
diff --git a/io/soft/src/lib.rs b/io/soft/src/lib.rs
index ad817e8c..b1e84b56 100644
--- a/io/soft/src/lib.rs
+++ b/io/soft/src/lib.rs
@@ -259,6 +259,16 @@ pub fn quality_kbps(o: &EncodeOpts) -> u32 {
}
}
+/// openh264 at a fixed quantiser `qp`: its Quality mode with the QP range pinned (#28, tests/qp.rs). With rate control
+/// off it encodes at its default QP 26 whatever the range says (the crate never sets the layer's iDLayerQp). With it
+/// on, it refuses a bitrate of 0 and a pinned QP below 14 (Native:3; 13 passes all-intra but not with P-frames), and
+/// the bitrate moves nothing once the QP is pinned. A frame too big for its buffer at that QP is Native:3 too.
+#[cfg(feature = "h264")]
+pub(crate) fn fixed_qp(config: EncoderConfig, qp: u8) -> EncoderConfig {
+ let qp = qp.clamp(14, 51);
+ config.rate_control_mode(RateControlMode::Quality).bitrate(BitRate::from_bps(50_000_000)).qp(openh264::encoder::QpRange::new(qp, qp))
+}
+
/// openh264's encoder at the options' bitrate (quality_kbps), or all-intra at a fixed quantiser when `intra_qp` is set (every frame an IDR: an optimized copy, raea_io_media::mezz).
#[cfg(feature = "h264")]
pub fn h264_encoder(out: &Path, o: &EncodeOpts, intra_qp: Option<u8>) -> R<Box<dyn VideoEncoder>> {
@@ -272,7 +282,7 @@ pub fn h264_encoder(out: &Path, o: &EncodeOpts, intra_qp: Option<u8>) -> R<Box<d
// untagged, ffmpeg and other players read it as BT.601 and shift reds and greens
.vui(openh264::encoder::VuiConfig::bt709());
let config = match intra_qp {
- Some(qp) => config.rate_control_mode(RateControlMode::Off).qp(openh264::encoder::QpRange::new(qp, qp)).intra_frame_period(openh264::encoder::IntraFramePeriod::from_num_frames(1)),
+ Some(qp) => fixed_qp(config, qp).intra_frame_period(openh264::encoder::IntraFramePeriod::from_num_frames(1)),
None => config,
};
let enc = H264Encoder::with_api_config(OpenH264API::from_source(), config).map_err(|e| format!("openh264: {e}"))?;
diff --git a/io/soft/tests/qp.rs b/io/soft/tests/qp.rs
new file mode 100644
index 00000000..f1042d06
--- /dev/null
+++ b/io/soft/tests/qp.rs
@@ -0,0 +1,58 @@
+//! #28 (2): a fixed quantiser reaches openh264: the mezz copy's all-intra QP (h264_encoder's `intra_qp`) and a GOP's
+//! (GopEncoder) each change what it writes. With rate control off, as both were, openh264 wrote QP 26 whatever was
+//! asked: QP 12 and QP 40 gave the same bytes.
+#![cfg(feature = "h264")]
+
+use raea_io_codec::EncodeOpts;
+use raea_io_soft::{GopEncoder, h264_encoder};
+
+const W: u32 = 320;
+const H: u32 = 192;
+
+/// soft rings moving across: detail every quantiser keeps a different amount of
+fn frame(k: u32) -> Vec<u8> {
+ (0..W * H).flat_map(|i| {
+ let (x, y) = (i % W, i / W);
+ let (dx, dy) = (x as i64 - 160 + k as i64 * 4, y as i64 - 96);
+ let v = ((dx * dx + dy * dy) / 13 % 256) as u8;
+ [v, v.wrapping_mul(3), 255 - v, 255]
+ }).collect()
+}
+
+fn intra(qp: u8) -> u64 {
+ let out = std::env::temp_dir().join(format!("raea-soft-qp-{}-{qp}.mp4", std::process::id()));
+ let opts = EncodeOpts { width: W, height: H, fps: 30.0, kbps: 0, quality: None, nv12: false, realtime: false };
+ let mut enc = h264_encoder(&out, &opts, Some(qp)).unwrap();
+ for k in 0..6 {
+ enc.push(&frame(k)).unwrap();
+ }
+ enc.finish(None).unwrap();
+ let n = std::fs::metadata(&out).unwrap().len();
+ let _ = std::fs::remove_file(&out);
+ n
+}
+
+fn gop(qp: u8) -> Vec<u8> {
+ let mut enc = GopEncoder::new(W, H, 30.0, qp).unwrap();
+ (0..6).flat_map(|k| enc.push(&frame(k)).unwrap().0).collect()
+}
+
+#[test]
+fn the_mezz_copys_quantiser_changes_what_openh264_writes() {
+ let (fine, coarse) = (intra(16), intra(40));
+ assert!(coarse * 2 < fine, "QP 16 {fine} bytes, QP 40 {coarse}: a finer quantiser spends more");
+}
+
+#[test]
+fn a_gops_quantiser_changes_what_openh264_writes() {
+ let (fine, coarse) = (gop(16).len(), gop(40).len());
+ assert!(coarse * 2 < fine, "QP 16 {fine} bytes, QP 40 {coarse}: a finer quantiser spends more");
+ // and a GOP is still the same bytes each time it's made (an export stitched from GOPs made at different times)
+ assert!(gop(16) == gop(16));
+}
+
+#[test]
+fn a_quantiser_below_openh264s_floor_is_its_floor() {
+ // openh264 refuses a pinned QP under 14 with rate control on (Native:3); asked for less, it gets 14
+ assert!(gop(4) == gop(14));
+}