Merge pull request #2708 from dotCooCoo/feat/video-h264-semi-planar-input

craft-video: H.264 encoder takes NV12 and P010 pictures
This commit is contained in:
BFlat authored and GitHub committed 2026-11-28 11:42:12 +07:00
commit 834e8ba776
4 files changed
+242 -4

No files matched your search

+4 -1
View File
@@ -29,7 +29,10 @@ for p in enc.flush() { /* ... */ }
- Input: planar 4:2:0 8-bit (`YuvFrame` with strides); any even size, non-multiple-of-16 sizes are
cropped via the SPS frame cropping. `encode` returns an error (`Error::BadFrame`) instead of panicking on short or
inconsistent planes, including strides whose size arithmetic would overflow.
- High 10: `cfg.profile = Profile::High10; cfg.bit_depth = 10;` (8 to 10) and `enc.encode16(&YuvFrame16 { … })`
- Semi-planar input: `enc.encode_nv12(&Nv12Frame { y, uv, y_stride, uv_stride }, pts)` takes NV12 (one plane of
interleaved Cb/Cr pairs) and `enc.encode_p010(&P010Frame { … }, pts)` takes P010 (the same arrangement with the value
in the high bits of each `u16`, for a High 10 encoder). Each codes the same stream as the planar picture.
- High 10: `cfg.profile = Profile::High10; cfg.bit_depth = 10;` (8 to 10) and `enc.encode16(&YuvFrame16 { … }, pts)`
with samples in the low bits of each `u16` (values above the bit depth are clipped); 8-bit `YuvFrame`s are
also taken and scaled up exactly. `cfg.intra_only = true` codes every picture as an IDR without reference
frames (High 10 Intra with constraint_set3 for High 10).
+162 -3
View File
@@ -355,11 +355,35 @@ pub struct YuvFrame16<'a> {
pub uv_stride: usize,
}
/// A semi-planar 4:2:0 8-bit input picture (NV12) of the configured size: a luma plane and one chroma
/// plane of interleaved pairs, Cb first. A chroma row holds `width` bytes (`width / 2` pairs). Strides
/// are in bytes.
#[derive(Clone, Copy, Debug)]
pub struct Nv12Frame<'a> {
pub y: &'a [u8],
pub uv: &'a [u8],
pub y_stride: usize,
pub uv_stride: usize,
}
/// A semi-planar 4:2:0 input picture in the P010 layout: the arrangement of [`Nv12Frame`] with 16-bit
/// samples whose value is in the high bits (a 10-bit sample `v` is stored as `v << 6`). The encoder keeps
/// the top [`EncoderConfig::bit_depth`] bits of each sample and ignores the rest. Strides are in samples.
#[derive(Clone, Copy, Debug)]
pub struct P010Frame<'a> {
pub y: &'a [u16],
pub uv: &'a [u16],
pub y_stride: usize,
pub uv_stride: usize,
}
/// The planes of one input picture.
#[derive(Clone, Copy)]
enum Source<'a> {
Eight(&'a YuvFrame<'a>),
Deep(&'a YuvFrame16<'a>),
Nv12(&'a Nv12Frame<'a>),
P010(&'a P010Frame<'a>),
}
/// One input row, 8- or 16-bit.
@@ -367,6 +391,11 @@ enum Source<'a> {
enum Row<'a> {
Eight(&'a [u8]),
Deep(&'a [u16]),
/// Interleaved chroma pairs and the index of the component in each pair (0 for Cb, 1 for Cr).
EightPairs(&'a [u8], usize),
/// P010 samples, with the value in the high bits.
High(&'a [u16]),
HighPairs(&'a [u16], usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -862,27 +891,35 @@ impl<P: Pixel> Core<P> {
fn import(&mut self, f: Source) -> Result<Frame<P>, Error> {
let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
let (cw, ch) = (w / 2, h / 2);
// A semi-planar chroma row holds both components, so it is twice as wide in samples.
let semi = matches!(f, Source::Nv12(_) | Source::P010(_));
let (lens, ys, cs) = match f {
Source::Eight(f) => ([f.y.len(), f.u.len(), f.v.len()], f.y_stride, f.uv_stride),
Source::Deep(f) => ([f.y.len(), f.u.len(), f.v.len()], f.y_stride, f.uv_stride),
Source::Nv12(f) => ([f.y.len(), f.uv.len(), f.uv.len()], f.y_stride, f.uv_stride),
Source::P010(f) => ([f.y.len(), f.uv.len(), f.uv.len()], f.y_stride, f.uv_stride),
};
let crow = if semi { 2 * cw } else { cw };
let fits = |len: usize, stride: usize, pw: usize, ph: usize| {
stride >= pw && stride.checked_mul(ph - 1).and_then(|n| n.checked_add(pw)).is_some_and(|n| len >= n)
};
if !(fits(lens[0], ys, w, h) && fits(lens[1], cs, cw, ch) && fits(lens[2], cs, cw, ch)) {
if !(fits(lens[0], ys, w, h) && fits(lens[1], cs, crow, ch) && fits(lens[2], cs, crow, ch)) {
return Err(Error::BadFrame);
}
if matches!(f, Source::Deep(_)) && self.depth.bits == 8 {
if matches!(f, Source::Deep(_) | Source::P010(_)) && self.depth.bits == 8 {
return Err(Error::DeepInput);
}
let depth = self.depth;
// P010 keeps the value in the high bits of each sample: the top BitDepth bits are the sample.
let down = 16 - u32::from(depth.bits);
let mut fr = self.new_frame();
for (k, (pl, stride, pw, ph)) in [(&mut fr.y, ys, w, h), (&mut fr.u, cs, cw, ch), (&mut fr.v, cs, cw, ch)].into_iter().enumerate() {
let aw = pl.w;
let n = if semi && k > 0 { 2 * pw } else { pw };
for y in 0..pl.h {
let sy = y.min(ph - 1);
let o = pl.idx(0, y as isize);
let (a, b) = (sy * stride, sy * stride + pw);
let (a, b) = (sy * stride, sy * stride + n);
let row = match (f, k) {
(Source::Eight(f), 0) => Row::Eight(&f.y[a..b]),
(Source::Eight(f), 1) => Row::Eight(&f.u[a..b]),
@@ -890,12 +927,19 @@ impl<P: Pixel> Core<P> {
(Source::Deep(f), 0) => Row::Deep(&f.y[a..b]),
(Source::Deep(f), 1) => Row::Deep(&f.u[a..b]),
(Source::Deep(f), _) => Row::Deep(&f.v[a..b]),
(Source::Nv12(f), 0) => Row::Eight(&f.y[a..b]),
(Source::Nv12(f), c) => Row::EightPairs(&f.uv[a..b], c - 1),
(Source::P010(f), 0) => Row::High(&f.y[a..b]),
(Source::P010(f), c) => Row::HighPairs(&f.uv[a..b], c - 1),
};
let dst = &mut pl.data[o..o + pw];
match row {
// 8-bit samples scale up exactly: v << (BitDepth - 8).
Row::Eight(r) => P::from_u8(dst, r, depth.shift),
Row::Deep(r) => dst.iter_mut().zip(r).for_each(|(d, &s)| *d = P::of((s as i32).min(depth.max))),
Row::EightPairs(r, c) => dst.iter_mut().zip(r[c..].iter().step_by(2)).for_each(|(d, &s)| *d = P::of(i32::from(s) << depth.shift)),
Row::High(r) => dst.iter_mut().zip(r).for_each(|(d, &s)| *d = P::of(i32::from(s >> down))),
Row::HighPairs(r, c) => dst.iter_mut().zip(r[c..].iter().step_by(2)).for_each(|(d, &s)| *d = P::of(i32::from(s >> down))),
}
let last = pl.data[o + pw - 1];
pl.data[o + pw..o + aw].fill(last);
@@ -1352,6 +1396,17 @@ impl Encoder {
core!(&mut self.core, c => c.try_encode(Source::Deep(frame), pts))
}
/// Encode one NV12 picture, with the results and errors of [`Encoder::encode`].
pub fn encode_nv12(&mut self, frame: &Nv12Frame, pts: i64) -> Result<Vec<Packet>, Error> {
core!(&mut self.core, c => c.try_encode(Source::Nv12(frame), pts))
}
/// Encode one P010 picture, with the results and errors of [`Encoder::encode16`]: [`Error::DeepInput`]
/// for an 8-bit encoder.
pub fn encode_p010(&mut self, frame: &P010Frame, pts: i64) -> Result<Vec<Packet>, Error> {
core!(&mut self.core, c => c.try_encode(Source::P010(frame), pts))
}
/// Encode all buffered pictures.
pub fn flush(&mut self) -> Vec<Packet> {
core!(&mut self.core, c => c.flush())
@@ -1413,6 +1468,110 @@ mod tests {
assert!(matches!(enc.encode(&f, 0), Err(Error::BadFrame)));
}
/// Planar 8-bit picture `t` with different content in each plane.
fn ramp(w: usize, h: usize, t: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
let plane = |pw: usize, ph: usize, k: usize| (0..pw * ph).map(|i| ((i % pw) * (3 + k) + (i / pw) * (5 + 2 * k) + 7 * t) as u8).collect();
(plane(w, h, 0), plane(w / 2, h / 2, 1), plane(w / 2, h / 2, 2))
}
/// `u` and `v` interleaved into rows of `stride` samples, Cb first, the rest of each row `pad`.
fn interleave<T: Copy>(u: &[T], v: &[T], cw: usize, stride: usize, pad: T) -> Vec<T> {
let mut uv = Vec::new();
for (ru, rv) in u.chunks(cw).zip(v.chunks(cw)) {
ru.iter().zip(rv).for_each(|(&a, &b)| uv.extend([a, b]));
uv.resize(uv.len() + stride - 2 * cw, pad);
}
uv
}
/// `p` in rows of `stride` samples, the rest of each row `pad`.
fn padded<T: Copy>(p: &[T], pw: usize, stride: usize, pad: T) -> Vec<T> {
p.chunks(pw).flat_map(|r| r.iter().copied().chain(std::iter::repeat_n(pad, stride - pw))).collect()
}
fn streams(cfg: &EncoderConfig, mut encode: impl FnMut(&mut Encoder, usize) -> Vec<Packet>) -> Vec<Vec<u8>> {
let mut enc = Encoder::new(cfg.clone()).unwrap();
let mut packets: Vec<Packet> = (0..4).flat_map(|t| encode(&mut enc, t)).collect();
packets.extend(enc.flush());
packets.into_iter().map(|p| p.data).collect()
}
#[test]
fn nv12_input_codes_the_same_stream_as_planar_input() {
// 40x24 is not a multiple of 16, so the last macroblock column and row are padded from the edge.
let (w, h) = (40, 24);
let cfg = EncoderConfig::new(w as u32, h as u32, 30, 1);
let planar = streams(&cfg, |enc, t| {
let (y, u, v) = ramp(w, h, t);
enc.encode(&YuvFrame { y: &y, u: &u, v: &v, y_stride: w, uv_stride: w / 2 }, t as i64).unwrap()
});
let semi = streams(&cfg, |enc, t| {
let (y, u, v) = ramp(w, h, t);
let (y, uv) = (padded(&y, w, w + 8, 0xee), interleave(&u, &v, w / 2, w + 6, 0xee));
enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: w + 8, uv_stride: w + 6 }, t as i64).unwrap()
});
assert_eq!(planar.len(), 4);
assert_eq!(planar, semi);
}
#[test]
fn p010_input_codes_the_same_stream_as_16_bit_input() {
let (w, h) = (32, 16);
for bits in [9, 10] {
let mut cfg = EncoderConfig::new(w as u32, h as u32, 30, 1);
cfg.profile = Profile::High10;
cfg.bit_depth = bits;
// 10-bit samples: the 8-bit ramp with two more bits of detail.
let ten = |t: usize| {
let (y, u, v) = ramp(w, h, t);
let up = |p: Vec<u8>| p.iter().enumerate().map(|(i, &s)| (u16::from(s) << 2) | (i % 4) as u16).collect::<Vec<u16>>();
(up(y), up(u), up(v))
};
let deep = streams(&cfg, |enc, t| {
let (y, u, v) = ten(t);
let keep = |p: Vec<u16>| p.iter().map(|&s| s >> (10 - bits)).collect::<Vec<u16>>();
let (y, u, v) = (keep(y), keep(u), keep(v));
enc.encode16(&YuvFrame16 { y: &y, u: &u, v: &v, y_stride: w, uv_stride: w / 2 }, t as i64).unwrap()
});
let semi = streams(&cfg, |enc, t| {
let (y, u, v) = ten(t);
// the six low bits P010 leaves unused carry noise, which the encoder ignores
let p010 = |p: Vec<u16>| p.iter().enumerate().map(|(i, &s)| (s << 6) | ((i as u16 * 13) & 0x3f)).collect::<Vec<u16>>();
let (y, u, v) = (p010(y), p010(u), p010(v));
let (y, uv) = (padded(&y, w, w + 2, u16::MAX), interleave(&u, &v, w / 2, w, u16::MAX));
enc.encode_p010(&P010Frame { y: &y, uv: &uv, y_stride: w + 2, uv_stride: w }, t as i64).unwrap()
});
assert_eq!(deep.len(), 4);
assert_eq!(deep, semi, "bit depth {bits}");
}
}
#[test]
fn short_or_overflowing_semi_planar_frames_are_bad_frames() {
let mut enc = Encoder::new(EncoderConfig::new(4, 4, 30, 1)).unwrap();
let y = vec![128u8; 16];
// A chroma plane sized for one planar component holds only half of each interleaved row.
let uv = vec![128u8; 4];
assert!(matches!(enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: 4, uv_stride: 2 }, 0), Err(Error::BadFrame)));
let uv = vec![128u8; 7];
assert!(matches!(enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: 4, uv_stride: 4 }, 0), Err(Error::BadFrame)));
let uv = vec![128u8; 8];
assert!(matches!(enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: 4, uv_stride: usize::MAX }, 0), Err(Error::BadFrame)));
assert!(matches!(enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: usize::MAX / 3, uv_stride: 4 }, 0), Err(Error::BadFrame)));
assert!(enc.encode_nv12(&Nv12Frame { y: &y, uv: &uv, y_stride: 4, uv_stride: 4 }, 0).is_ok());
let (y, uv) = (vec![0u16; 16], vec![0u16; 8]);
let p010 = P010Frame { y: &y, uv: &uv, y_stride: 4, uv_stride: 4 };
assert!(matches!(enc.encode_p010(&p010, 1), Err(Error::DeepInput)));
let mut cfg = EncoderConfig::new(4, 4, 30, 1);
cfg.profile = Profile::High10;
cfg.bit_depth = 10;
let mut enc = Encoder::new(cfg).unwrap();
let short = vec![0u16; 7];
assert!(matches!(enc.encode_p010(&P010Frame { y: &y, uv: &short, y_stride: 4, uv_stride: 4 }, 0), Err(Error::BadFrame)));
assert!(enc.encode_p010(&p010, 0).is_ok());
}
fn b_frame_encoder() -> Encoder {
let mut cfg = EncoderConfig::new(16, 16, 30, 1);
cfg.bframes = 2;
@@ -8,5 +8,6 @@ mod crf_level_and_note;
mod ffmpeg_oracle;
mod high10_oracle;
mod pinned_decisions;
mod semi_planar_oracle;
mod thread_count;
mod vbr_overshoot;
@@ -0,0 +1,75 @@
//! NV12 and P010 input against ffmpeg's `nv12` and `p010le` layouts (skipped when ffmpeg is absent):
//! pictures ffmpeg converts from planar 4:2:0 code the same stream as the planar pictures.
use super::common;
use common::{Yuv, Yuv16, ffmpeg, le16, synth, synth10};
use craft_video::h264::*;
use std::process::Command;
/// `raw` (frames of `from`) converted by ffmpeg to frames of `to`.
fn convert(raw: &[u8], w: usize, h: usize, from: &str, to: &str) -> Vec<u8> {
let dir = common::out_dir("semi_planar");
let src = dir.join(format!("{from}.raw"));
std::fs::write(&src, raw).unwrap();
let out = Command::new(ffmpeg().unwrap())
.args(["-nostdin", "-v", "error", "-f", "rawvideo", "-pix_fmt", from, "-s", &format!("{w}x{h}"), "-i"])
.arg(&src)
.args(["-f", "rawvideo", "-pix_fmt", to, "-"])
.output()
.expect("run ffmpeg");
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
out.stdout
}
fn stream(cfg: &EncoderConfig, frames: usize, mut encode: impl FnMut(&mut Encoder, usize) -> Vec<Packet>) -> Vec<u8> {
let mut enc = Encoder::new(cfg.clone()).unwrap();
let mut packets: Vec<Packet> = (0..frames).flat_map(|i| encode(&mut enc, i)).collect();
packets.extend(enc.flush());
assert_eq!(packets.len(), frames);
packets.iter().flat_map(|p| p.data.iter().copied()).collect()
}
#[test]
fn ffmpeg_nv12_pictures_code_the_same_stream_as_planar_pictures() {
if ffmpeg().is_none() {
return;
}
let (w, h, n) = (96, 64, 5);
let frames: Vec<Yuv> = (0..n).map(|t| synth(w, h, t)).collect();
let raw: Vec<u8> = frames.iter().flat_map(Yuv::bytes).collect();
let nv12 = convert(&raw, w, h, "yuv420p", "nv12");
let size = w * h * 3 / 2;
assert_eq!(nv12.len(), size * n);
let cfg = EncoderConfig::new(w as u32, h as u32, 30, 1);
let planar = stream(&cfg, n, |enc, i| enc.encode(&frames[i].frame(), i as i64).unwrap());
let semi = stream(&cfg, n, |enc, i| {
let pic = &nv12[i * size..(i + 1) * size];
let (y, uv) = pic.split_at(w * h);
enc.encode_nv12(&Nv12Frame { y, uv, y_stride: w, uv_stride: w }, i as i64).unwrap()
});
assert!(planar == semi, "the NV12 stream differs from the planar one");
}
#[test]
fn ffmpeg_p010_pictures_code_the_same_stream_as_16_bit_pictures() {
if ffmpeg().is_none() {
return;
}
let (w, h, n) = (96, 64, 5);
let frames: Vec<Yuv16> = (0..n).map(|t| synth10(w, h, t)).collect();
let raw: Vec<u8> = frames.iter().flat_map(Yuv16::bytes).collect();
let p010 = le16(&convert(&raw, w, h, "yuv420p10le", "p010le"));
let size = w * h * 3 / 2;
assert_eq!(p010.len(), size * n);
let mut cfg = EncoderConfig::new(w as u32, h as u32, 30, 1);
cfg.profile = Profile::High10;
cfg.bit_depth = 10;
let deep = stream(&cfg, n, |enc, i| enc.encode16(&frames[i].frame(), i as i64).unwrap());
let semi = stream(&cfg, n, |enc, i| {
let pic = &p010[i * size..(i + 1) * size];
let (y, uv) = pic.split_at(w * h);
enc.encode_p010(&P010Frame { y, uv, y_stride: w, uv_stride: w }, i as i64).unwrap()
});
assert!(deep == semi, "the P010 stream differs from the 16-bit one");
}