Merge main into M13.4 (codec completion): HEVC/AV1 on the export pipeline (Cx), one key-frame interval for all movie codecs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -50,7 +50,19 @@ fn project(audio: Option<&Path>) -> (Project, ItemId) {
|
||||
fn run(p: &Project, cid: ItemId, footage: &dyn FootageSource, om: &OutputModule, path: &Path) -> effectcraft_export::Report {
|
||||
let s = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() };
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let job = Job { project: p, footage, expr: None, accel: None, comp: cid, settings: &s, output: om, path: &path, sink: None, nested_switches: true };
|
||||
let job = Job {
|
||||
project: p,
|
||||
footage,
|
||||
expr: None,
|
||||
accel: None,
|
||||
comp: cid,
|
||||
settings: &s,
|
||||
output: om,
|
||||
path: &path,
|
||||
sink: None,
|
||||
nested_switches: true,
|
||||
options: Default::default(),
|
||||
};
|
||||
let mut last = Progress::default();
|
||||
let r = export(&job, &mut |pr| {
|
||||
last = *pr;
|
||||
@@ -135,7 +147,7 @@ fn ffmpeg_check(path: &Path, decoder: Option<&str>, tol: f32) {
|
||||
|
||||
fn module(format: OutputFormat, keyint: u32) -> OutputModule {
|
||||
let mut om = OutputModule::for_format(format);
|
||||
om.codec.keyframe_interval = keyint;
|
||||
om.keyframe_interval = keyint;
|
||||
om.codec.rate_control = RateControlMode::Quality;
|
||||
om.codec.quality = 80;
|
||||
om.audio = AudioOutput::Off;
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
//! Render Settings and Output Module features end to end (through a [`Sink`], so nothing touches
|
||||
//! the disk): field rendering and 3:2 pulldown, crop / region of interest / resize, alpha-only
|
||||
//! and premultiplied output, the solo and guide-layer overrides, the render log, storage
|
||||
//! overflow and PCM audio formats.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_export::render_queue::*;
|
||||
use effectcraft_export::{Job, JobOptions, Report, Sink, StorageQuota, export};
|
||||
use effectcraft_keyframe::{Keyframe, Value};
|
||||
use effectcraft_project::{Comp, ItemId, ItemKind, LayerSource, Project, Solid, build};
|
||||
use effectcraft_render::NoFootage;
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
|
||||
const W: u32 = 64;
|
||||
const H: u32 = 48;
|
||||
|
||||
/// A comp at `rate`, black, with a white bar 8 px wide sweeping left to right (64 px/s) and a
|
||||
/// static red block at the bottom left; `extra` adds layers.
|
||||
fn project(rate: FrameRate, extra: impl FnOnce(&mut Project, &mut Comp)) -> (Project, ItemId) {
|
||||
let mut p = Project::default();
|
||||
let mut comp = Comp::new(W, H, rate, Tick::from_seconds_f64(2.0));
|
||||
comp.background = [0.0, 0.0, 0.0];
|
||||
let bar = p.add_item("Bar", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 1.0, 1.0], width: 8, height: 32, pixel_aspect: 1.0 }));
|
||||
let mut l = build::layer(&mut p, &comp, "Bar", LayerSource::Solid { item: bar }, (8, 32), None);
|
||||
l.props.prop_mut("transform/position").unwrap().keys =
|
||||
vec![Keyframe::new(Tick::ZERO, Value::Vec3([0.0, 16.0, 0.0])), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Vec3([64.0, 16.0, 0.0]))];
|
||||
comp.layers.push(l);
|
||||
let red = p.add_item("Block", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 16, height: 8, pixel_aspect: 1.0 }));
|
||||
let mut b = build::layer(&mut p, &comp, "Block", LayerSource::Solid { item: red }, (16, 8), None);
|
||||
b.props.prop_mut("transform/position").unwrap().value = Value::Vec3([8.0, 44.0, 0.0]);
|
||||
comp.layers.push(b);
|
||||
extra(&mut p, &mut comp);
|
||||
let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.into()));
|
||||
(p, cid)
|
||||
}
|
||||
|
||||
type Files = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
|
||||
|
||||
fn custom(start: f64, end: f64) -> RenderSettings {
|
||||
RenderSettings { time_span: TimeSpan::Custom { start: Tick::from_seconds_f64(start), end: Tick::from_seconds_f64(end) }, ..Default::default() }
|
||||
}
|
||||
|
||||
fn run_with(p: &Project, cid: ItemId, s: &RenderSettings, om: &OutputModule, path: &str, options: JobOptions, cancel: bool) -> (Result<Report, String>, Files) {
|
||||
let files: Files = Default::default();
|
||||
let f = files.clone();
|
||||
let sink: Box<Sink> = Box::new(move |path: &str, data: Vec<u8>| f.lock().unwrap().push((path.to_string(), data)));
|
||||
let job = Job {
|
||||
project: p,
|
||||
footage: &NoFootage,
|
||||
expr: None,
|
||||
accel: None,
|
||||
comp: cid,
|
||||
settings: s,
|
||||
output: om,
|
||||
path,
|
||||
sink: Some(&*sink),
|
||||
options,
|
||||
nested_switches: true,
|
||||
};
|
||||
let r = export(&job, &mut |pr| !(cancel && pr.done > 0)).map_err(|e| e.to_string());
|
||||
(r, files)
|
||||
}
|
||||
|
||||
fn run(p: &Project, cid: ItemId, s: &RenderSettings, om: &OutputModule, path: &str) -> Files {
|
||||
let (r, files) = run_with(p, cid, s, om, path, JobOptions::default(), false);
|
||||
r.expect("export");
|
||||
files
|
||||
}
|
||||
|
||||
fn png(files: &Files, i: usize) -> image::RgbaImage {
|
||||
let f = files.lock().unwrap();
|
||||
let pngs: Vec<&(String, Vec<u8>)> = f.iter().filter(|(p, _)| p.ends_with(".png")).collect();
|
||||
let mut pngs = pngs;
|
||||
pngs.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
image::load_from_memory(&pngs[i].1).expect("png").to_rgba8()
|
||||
}
|
||||
|
||||
fn row(img: &image::RgbaImage, y: u32) -> Vec<u8> {
|
||||
(0..img.width()).flat_map(|x| img.get_pixel(x, y).0).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_render_interleaves_two_times() {
|
||||
let (p, cid) = project(FrameRate::new(25, 1), |_, _| {});
|
||||
let om = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
// Frame 10 at 25 fps with fields: 0.40 s and 0.42 s.
|
||||
for (fr, upper) in [(FieldRender::UpperFirst, true), (FieldRender::LowerFirst, false)] {
|
||||
let s = RenderSettings { field_render: fr, ..custom(0.4, 0.44) };
|
||||
let fields = png(&run(&p, cid, &s, &om, "/f/field_[#####].png"), 0);
|
||||
// Progressive references at 50 fps: frames 20 (0.40 s) and 21 (0.42 s).
|
||||
let r = RenderSettings { frame_rate: Some(FrameRate::new(50, 1)), ..custom(0.4, 0.44) };
|
||||
let refs = run(&p, cid, &r, &om, "/f/ref_[#####].png");
|
||||
let (a, b) = (png(&refs, 0), png(&refs, 1));
|
||||
assert_ne!(row(&a, 10), row(&b, 10), "the bar moved between the fields");
|
||||
for y in 0..H {
|
||||
let first = (y % 2 == 0) == upper;
|
||||
assert_eq!(row(&fields, y), row(if first { &a } else { &b }, y), "{fr:?}: line {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pulldown_follows_the_cadence() {
|
||||
let ntsc = FrameRate::new(30000, 1001);
|
||||
let (p, cid) = project(ntsc, |_, _| {});
|
||||
let om = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
let five = 5.0 * 1001.0 / 30000.0;
|
||||
let s = RenderSettings { field_render: FieldRender::UpperFirst, pulldown: Pulldown::Wssww, ..custom(0.0, five) };
|
||||
let out = run(&p, cid, &s, &om, "/p/pd_[#####].png");
|
||||
assert_eq!(out.lock().unwrap().len(), 5);
|
||||
// Film frames at 23.976 fps.
|
||||
let r = RenderSettings { frame_rate: Some(FrameRate::new(24000, 1001)), ..custom(0.0, 0.2) };
|
||||
let film = run(&p, cid, &r, &om, "/p/film_[#####].png");
|
||||
let mut pattern = String::new();
|
||||
for k in 0..5 {
|
||||
let (a, b) = Pulldown::Wssww.fields(k as u64).unwrap();
|
||||
pattern.push(if a == b { 'W' } else { 'S' });
|
||||
let img = png(&out, k);
|
||||
let (fa, fb) = (png(&film, a as usize), png(&film, b as usize));
|
||||
for y in 0..H {
|
||||
assert_eq!(row(&img, y), row(if y % 2 == 0 { &fa } else { &fb }, y), "frame {k} line {y}");
|
||||
}
|
||||
}
|
||||
assert_eq!(pattern, "WSSWW");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_roi_and_resize() {
|
||||
let (p, cid) = project(FrameRate::new(25, 1), |_, _| {});
|
||||
let s = custom(0.4, 0.44);
|
||||
let full = png(&run(&p, cid, &s, &OutputModule::for_format(OutputFormat::PngSequence), "/c/full_[#####].png"), 0);
|
||||
let mut om = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
om.crop = Crop { enabled: true, top: 4, left: 10, bottom: 6, right: 2, ..Default::default() };
|
||||
let c = png(&run(&p, cid, &s, &om, "/c/crop_[#####].png"), 0);
|
||||
assert_eq!((c.width(), c.height()), (52, 38));
|
||||
for (x, y) in [(0, 0), (20, 11), (51, 37), (3, 30)] {
|
||||
assert_eq!(c.get_pixel(x, y), full.get_pixel(x + 10, y + 4), "({x}, {y})");
|
||||
}
|
||||
// Region of interest at half resolution.
|
||||
om.crop = Crop { enabled: true, use_roi: true, roi: Some([16.0, 8.0, 32.0, 32.0]), ..Default::default() };
|
||||
let half = RenderSettings { resolution: 0.5, ..s.clone() };
|
||||
let r = png(&run(&p, cid, &half, &om, "/c/roi_[#####].png"), 0);
|
||||
assert_eq!((r.width(), r.height()), (16, 16));
|
||||
// Resize (fixed size, low and high quality) after the crop.
|
||||
om.crop = Crop::default();
|
||||
for q in [ResizeQuality::Low, ResizeQuality::High] {
|
||||
om.resize = Resize { enabled: true, width: 32, height: 20, lock_aspect: false, quality: q };
|
||||
let z = png(&run(&p, cid, &s, &om, "/c/resize_[#####].png"), 0);
|
||||
assert_eq!((z.width(), z.height()), (32, 20));
|
||||
// The red block (bottom left) survives the resize.
|
||||
let px = z.get_pixel(4, 18).0;
|
||||
assert!(px[0] > 150 && px[1] < 80, "{q:?}: {px:?}");
|
||||
}
|
||||
om.resize.lock_aspect = true;
|
||||
let z = png(&run(&p, cid, &s, &om, "/c/aspect_[#####].png"), 0);
|
||||
assert_eq!((z.width(), z.height()), (32, 24));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alpha_only_and_premultiplied() {
|
||||
let (p, cid) = project(FrameRate::new(25, 1), |p, comp| {
|
||||
// A half-transparent green layer over the right half.
|
||||
let g = p.add_item("Green", Label::Green, None, ItemKind::Solid(Solid { color: [0.0, 1.0, 0.0], width: 32, height: 48, pixel_aspect: 1.0 }));
|
||||
let mut l = build::layer(p, comp, "Green", LayerSource::Solid { item: g }, (32, 48), None);
|
||||
l.props.prop_mut("transform/position").unwrap().value = Value::Vec3([48.0, 24.0, 0.0]);
|
||||
l.props.prop_mut("transform/opacity").unwrap().value = Value::Scalar(50.0);
|
||||
comp.layers.insert(0, l);
|
||||
});
|
||||
let s = custom(0.0, 0.04);
|
||||
let mut om = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
om.channels = Channels::Alpha;
|
||||
let a = png(&run(&p, cid, &s, &om, "/a/alpha_[#####].png"), 0);
|
||||
assert_eq!(a.get_pixel(60, 2).0[0], 128, "half-opaque green");
|
||||
assert_eq!(a.get_pixel(20, 2).0[0], 0, "transparent");
|
||||
assert_eq!(a.get_pixel(8, 44).0[0], 255, "opaque block");
|
||||
om.channels = Channels::Rgba;
|
||||
let straight = png(&run(&p, cid, &s, &om, "/a/s_[#####].png"), 0);
|
||||
om.alpha_mode = AlphaMode::Premultiplied;
|
||||
let premul = png(&run(&p, cid, &s, &om, "/a/p_[#####].png"), 0);
|
||||
assert_eq!(straight.get_pixel(60, 2).0, [0, 255, 0, 128]);
|
||||
assert_eq!(premul.get_pixel(60, 2).0, [0, 128, 0, 128]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solo_and_guide_layer_overrides() {
|
||||
let (p, cid) = project(FrameRate::new(25, 1), |p, comp| {
|
||||
let g = p.add_item("Guide", Label::Green, None, ItemKind::Solid(Solid { color: [0.0, 0.0, 1.0], width: 8, height: 8, pixel_aspect: 1.0 }));
|
||||
let mut l = build::layer(p, comp, "Guide", LayerSource::Solid { item: g }, (8, 8), None);
|
||||
l.props.prop_mut("transform/position").unwrap().value = Value::Vec3([56.0, 44.0, 0.0]);
|
||||
l.switches.guide = true;
|
||||
comp.layers.insert(0, l);
|
||||
// Solo the moving bar.
|
||||
comp.layers[1].switches.solo = true;
|
||||
});
|
||||
let om = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
let s = custom(0.4, 0.44);
|
||||
let cur = png(&run(&p, cid, &s, &om, "/s/cur_[#####].png"), 0);
|
||||
assert_eq!(cur.get_pixel(8, 44).0[0], 0, "solo: the red block is hidden");
|
||||
assert_eq!(cur.get_pixel(56, 44).0[2], 0, "guide layers off by default");
|
||||
let off = RenderSettings { solo: CurrentOrOff::AllOff, guide_layers: CurrentOrOff::Current, ..s.clone() };
|
||||
let all = png(&run(&p, cid, &off, &om, "/s/off_[#####].png"), 0);
|
||||
assert_eq!(all.get_pixel(8, 44).0[0], 255, "Solo Switches: All Off");
|
||||
// (with solo off the guide renders too: Guide Layers: Current Settings)
|
||||
assert_eq!(all.get_pixel(56, 44).0[2], 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_logs() {
|
||||
let (p, cid) = project(FrameRate::new(25, 1), |_, _| {});
|
||||
let om = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
let s = RenderSettings { field_render: FieldRender::UpperFirst, name: "DV-ish".into(), ..custom(0.0, 0.2) };
|
||||
let log_of = |files: &Files| {
|
||||
files.lock().unwrap().iter().find(|(p, _)| p.ends_with("_RenderLog.txt")).map(|(p, d)| (p.clone(), String::from_utf8(d.clone()).unwrap()))
|
||||
};
|
||||
// Errors Only + success: no log.
|
||||
let (r, files) = run_with(&p, cid, &s, &om, "/l/a_[#####].png", JobOptions::default(), false);
|
||||
assert!(r.unwrap().log.is_none());
|
||||
assert!(log_of(&files).is_none());
|
||||
// Plus Per Frame Info: settings and one line per frame.
|
||||
let opts = JobOptions { log: RenderLog::PlusPerFrameInfo, label: "#1 Comp".into(), ..Default::default() };
|
||||
let (r, files) = run_with(&p, cid, &s, &om, "/l/b_[#####].png", opts, false);
|
||||
let r = r.unwrap();
|
||||
let (path, text) = log_of(&files).expect("log");
|
||||
assert_eq!(r.log.as_deref(), Some(path.as_str()));
|
||||
assert_eq!(path, "/l/b_RenderLog.txt");
|
||||
assert!(text.contains("Item: #1 Comp") && text.contains("Result: Done (5 frames"), "{text}");
|
||||
assert!(text.contains("Field Render: Upper Field First") && text.contains("Template: DV-ish") && text.contains("Format: PNG Sequence"), "{text}");
|
||||
assert_eq!(text.lines().filter(|l| l.contains("rendered in")).count(), 5, "{text}");
|
||||
assert!(text.contains("Frame 0 (0.000 s): rendered in") && text.contains("Frame 4 (0.160 s)"), "{text}");
|
||||
// Plus Settings: no per-frame lines.
|
||||
let opts = JobOptions { log: RenderLog::PlusSettings, ..Default::default() };
|
||||
let (_, files) = run_with(&p, cid, &s, &om, "/l/c.gif", opts, false);
|
||||
let (_, text) = log_of(&files).expect("log");
|
||||
assert!(text.contains("Render Settings:") && !text.contains("rendered in"), "{text}");
|
||||
// Errors Only + failure (the composition is gone): the error is logged.
|
||||
let gif = OutputModule::for_format(OutputFormat::Gif);
|
||||
let (r, files) = run_with(&p, ItemId(424_242), &s, &gif, "/l/d.gif", JobOptions::default(), false);
|
||||
assert!(r.is_err());
|
||||
let (path, text) = log_of(&files).expect("error log");
|
||||
assert_eq!(path, "/l/d_RenderLog.txt");
|
||||
assert!(text.contains("Result: Failed") && text.contains("Error: composition not found") && !text.contains("Render Settings:"), "{text}");
|
||||
// A user stop is not an error: no log.
|
||||
let (r, files) = run_with(&p, cid, &s, &gif, "/l/e.gif", JobOptions::default(), true);
|
||||
assert!(r.is_err());
|
||||
assert!(log_of(&files).is_none());
|
||||
}
|
||||
|
||||
/// The primary folder holds `limit` bytes; overflow folders are unlimited.
|
||||
struct Quota {
|
||||
limit: u64,
|
||||
used: Mutex<u64>,
|
||||
}
|
||||
|
||||
impl StorageQuota for Quota {
|
||||
fn has_room(&self, path: &str, bytes: u64) -> bool {
|
||||
if !path.starts_with("/primary/") {
|
||||
return true;
|
||||
}
|
||||
let mut u = self.used.lock().unwrap();
|
||||
if *u + bytes > self.limit {
|
||||
return false;
|
||||
}
|
||||
*u += bytes;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn storage_overflow_moves_files_to_the_overflow_folder() {
|
||||
let (p, cid) = project(FrameRate::new(25, 1), |_, _| {});
|
||||
let om = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
let s = RenderSettings { skip_existing: false, ..custom(0.0, 0.4) };
|
||||
let q = Quota { limit: 1, used: Mutex::new(0) };
|
||||
let opts = JobOptions { storage: Some(&q), overflow: vec!["/overflow".into()], log: RenderLog::PlusSettings, ..Default::default() };
|
||||
let (r, files) = run_with(&p, cid, &s, &om, "/primary/seq_[#####].png", opts, false);
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r.overflow.len(), 10, "{:?}", r.overflow);
|
||||
let f = files.lock().unwrap();
|
||||
assert_eq!(f.iter().filter(|(p, _)| p.starts_with("/overflow/seq_") && p.ends_with(".png")).count(), 10);
|
||||
let log = f.iter().find(|(p, _)| p.ends_with("_RenderLog.txt")).map(|(_, d)| String::from_utf8_lossy(d).to_string()).unwrap();
|
||||
assert!(log.contains("Storage overflow: 10 file(s)"), "{log}");
|
||||
drop(f);
|
||||
// Use Storage Overflow off: everything stays in place.
|
||||
let off = RenderSettings { storage_overflow: false, ..s };
|
||||
let q = Quota { limit: 1, used: Mutex::new(0) };
|
||||
let opts = JobOptions { storage: Some(&q), overflow: vec!["/overflow".into()], ..Default::default() };
|
||||
let (r, files) = run_with(&p, cid, &off, &om, "/primary/seq_[#####].png", opts, false);
|
||||
assert!(r.unwrap().overflow.is_empty());
|
||||
assert!(files.lock().unwrap().iter().all(|(p, _)| p.starts_with("/primary/")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wav_and_aiff_channels_and_formats() {
|
||||
let (p, cid) = project(FrameRate::new(25, 1), |_, _| {});
|
||||
let s = custom(0.0, 0.5);
|
||||
let mut om = OutputModule::for_format(OutputFormat::Wav);
|
||||
om.audio_channels = 1;
|
||||
om.audio_format = AudioFormat::S24;
|
||||
om.audio_sample_rate = 44_100;
|
||||
let files = run(&p, cid, &s, &om, "/w/a.wav");
|
||||
let d = files.lock().unwrap()[0].1.clone();
|
||||
assert_eq!(&d[..4], b"RIFF");
|
||||
let u16_at = |o: usize| u16::from_le_bytes([d[o], d[o + 1]]);
|
||||
let u32_at = |o: usize| u32::from_le_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]);
|
||||
assert_eq!((u16_at(20), u16_at(22), u32_at(24), u16_at(32), u16_at(34)), (1, 1, 44_100, 3, 24));
|
||||
assert_eq!(u32_at(40), 22_050 * 3, "half a second of mono 24-bit");
|
||||
om.audio_channels = 2;
|
||||
om.audio_format = AudioFormat::F32;
|
||||
let files = run(&p, cid, &s, &om, "/w/b.wav");
|
||||
let d = files.lock().unwrap()[0].1.clone();
|
||||
let u16_at = |o: usize| u16::from_le_bytes([d[o], d[o + 1]]);
|
||||
assert_eq!((u16_at(20), u16_at(22), u16_at(32), u16_at(34)), (3, 2, 8, 32), "IEEE float stereo");
|
||||
// AIFF has no float: 24-bit.
|
||||
let mut aiff = OutputModule::for_format(OutputFormat::Aiff);
|
||||
aiff.audio_format = AudioFormat::F32;
|
||||
let files = run(&p, cid, &s, &aiff, "/w/c.aif");
|
||||
let d = files.lock().unwrap()[0].1.clone();
|
||||
assert_eq!(&d[8..12], b"AIFF");
|
||||
assert_eq!(u16::from_be_bytes([d[26], d[27]]), 24, "sample size");
|
||||
}
|
||||
@@ -55,7 +55,19 @@ fn settings() -> RenderSettings {
|
||||
fn run(p: &Project, cid: ItemId, footage: &dyn FootageSource, om: &OutputModule, path: &Path) -> effectcraft_export::Report {
|
||||
let s = settings();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let job = Job { project: p, footage, expr: None, accel: None, comp: cid, settings: &s, output: om, path: &path, sink: None, nested_switches: true };
|
||||
let job = Job {
|
||||
project: p,
|
||||
footage,
|
||||
expr: None,
|
||||
accel: None,
|
||||
comp: cid,
|
||||
settings: &s,
|
||||
output: om,
|
||||
path: &path,
|
||||
sink: None,
|
||||
options: Default::default(),
|
||||
nested_switches: true,
|
||||
};
|
||||
let mut last = Progress::default();
|
||||
let mut calls = 0;
|
||||
let r = export(&job, &mut |pr| {
|
||||
@@ -167,8 +179,19 @@ fn h264_odd_size_is_cropped_even() {
|
||||
let comp = p.comp(cid).expect("comp");
|
||||
assert_eq!(s.output_size(comp).0 % 2, 1);
|
||||
let path = d.join("odd.mp4").to_string_lossy().to_string();
|
||||
let job =
|
||||
Job { project: &p, footage: &NoFootage, expr: None, accel: None, comp: cid, settings: &s, output: &om, path: &path, sink: None, nested_switches: true };
|
||||
let job = Job {
|
||||
project: &p,
|
||||
footage: &NoFootage,
|
||||
expr: None,
|
||||
accel: None,
|
||||
comp: cid,
|
||||
settings: &s,
|
||||
output: &om,
|
||||
path: &path,
|
||||
sink: None,
|
||||
options: Default::default(),
|
||||
nested_switches: true,
|
||||
};
|
||||
let r = export(&job, &mut |_| true).expect("export");
|
||||
assert_eq!((r.width % 2, r.height % 2), (0, 0));
|
||||
}
|
||||
@@ -288,8 +311,19 @@ fn cancel_stops_early() {
|
||||
let om = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
let s = settings();
|
||||
let path = d.join("c_[#####].png").to_string_lossy().to_string();
|
||||
let job =
|
||||
Job { project: &p, footage: &NoFootage, expr: None, accel: None, comp: cid, settings: &s, output: &om, path: &path, sink: None, nested_switches: true };
|
||||
let job = Job {
|
||||
project: &p,
|
||||
footage: &NoFootage,
|
||||
expr: None,
|
||||
accel: None,
|
||||
comp: cid,
|
||||
settings: &s,
|
||||
output: &om,
|
||||
path: &path,
|
||||
sink: None,
|
||||
options: Default::default(),
|
||||
nested_switches: true,
|
||||
};
|
||||
let r = export(&job, &mut |_| false);
|
||||
assert!(matches!(r, Err(effectcraft_export::ExportError::Cancelled)));
|
||||
let written = std::fs::read_dir(&d).map(|r| r.count()).unwrap_or(0);
|
||||
|
||||
@@ -61,7 +61,7 @@ fn lossless_is_exact_for_odd_sizes() {
|
||||
for (w, h) in [(1, 1), (33, 17), (64, 64), (200, 120), (7, 70)] {
|
||||
for kind in 0..3 {
|
||||
let (y, u, v) = source(w, h, kind);
|
||||
let mut e = Vp9Encoder::new(EncoderConfig { width: w as u32, height: h as u32, quality: 100, full_range: false });
|
||||
let mut e = Vp9Encoder::new(EncoderConfig { width: w as u32, height: h as u32, quality: 100, full_range: false, ..Default::default() });
|
||||
let f = e.encode_yuv420(&y, &u, &v);
|
||||
let p = decode(&f);
|
||||
assert_eq!((p.width, p.height), (w as u32, h as u32));
|
||||
@@ -80,7 +80,7 @@ fn lossy_quality_and_size() {
|
||||
let (y, u, v) = source(w, h, kind);
|
||||
let mut last = 0usize;
|
||||
for q in [30u8, 60, 80, 95] {
|
||||
let mut e = Vp9Encoder::new(EncoderConfig { width: w as u32, height: h as u32, quality: q, full_range: false });
|
||||
let mut e = Vp9Encoder::new(EncoderConfig { width: w as u32, height: h as u32, quality: q, full_range: false, ..Default::default() });
|
||||
let f = e.encode_yuv420(&y, &u, &v);
|
||||
let p = decode(&f);
|
||||
let got = crop(&plane_u8(&p.y), p.y_stride, w, h);
|
||||
@@ -103,7 +103,7 @@ fn wide_frames_use_tile_columns() {
|
||||
// 4160 px > 64 superblocks: two tile columns are required.
|
||||
let (w, h) = (4160, 16);
|
||||
let (y, u, v) = source(w, h, 0);
|
||||
let mut e = Vp9Encoder::new(EncoderConfig { width: w as u32, height: h as u32, quality: 90, full_range: false });
|
||||
let mut e = Vp9Encoder::new(EncoderConfig { width: w as u32, height: h as u32, quality: 90, full_range: false, ..Default::default() });
|
||||
let f = e.encode_yuv420(&y, &u, &v);
|
||||
let p = decode(&f);
|
||||
assert!(psnr(&crop(&plane_u8(&p.y), p.y_stride, w, h), &y) > 35.0);
|
||||
@@ -113,7 +113,7 @@ fn wide_frames_use_tile_columns() {
|
||||
fn ffmpeg_decodes_our_stream() {
|
||||
let (w, h) = (96, 64);
|
||||
let (y, u, v) = source(w, h, 0);
|
||||
let mut e = Vp9Encoder::new(EncoderConfig { width: w as u32, height: h as u32, quality: 100, full_range: false });
|
||||
let mut e = Vp9Encoder::new(EncoderConfig { width: w as u32, height: h as u32, quality: 100, full_range: false, ..Default::default() });
|
||||
let frame = e.encode_yuv420(&y, &u, &v);
|
||||
// IVF container (one frame).
|
||||
let mut ivf = Vec::new();
|
||||
@@ -147,3 +147,176 @@ fn ffmpeg_decodes_our_stream() {
|
||||
assert_eq!(&out.stdout[..w * h], &y[..], "ffmpeg luma matches (lossless)");
|
||||
assert_eq!(&out.stdout[w * h..w * h + u.len()], &u[..]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- inter frames
|
||||
|
||||
/// Frame `t` of a moving sequence: a diagonal gradient with a sinusoidal texture and bright
|
||||
/// squares, all translating by a fractional amount per frame (`kind` 1 adds noise that changes
|
||||
/// every frame).
|
||||
fn moving(w: usize, h: usize, t: usize, kind: u32) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
|
||||
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
|
||||
let (dx, dy) = (1.75 * t as f64, 0.6 * t as f64);
|
||||
let mut s = 1234u32 + t as u32 * 77;
|
||||
let mut rnd = || {
|
||||
s = s.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
(s >> 28) as f64
|
||||
};
|
||||
let lum = |x: f64, y: f64| -> f64 {
|
||||
let g = 40.0 + 120.0 * (x / w as f64) + 50.0 * (y / h as f64);
|
||||
let tex = 18.0 * ((x * 0.31).sin() * (y * 0.23).cos());
|
||||
let sq = if (x - 20.0).rem_euclid(64.0) < 18.0 && (y - 10.0).rem_euclid(48.0) < 14.0 { 45.0 } else { 0.0 };
|
||||
g + tex + sq
|
||||
};
|
||||
let mut y = vec![0u8; w * h];
|
||||
for yy in 0..h {
|
||||
for x in 0..w {
|
||||
let n = if kind == 1 { rnd() - 7.5 } else { 0.0 };
|
||||
y[yy * w + x] = (lum(x as f64 - dx, yy as f64 - dy) + n).round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
}
|
||||
let u: Vec<u8> = (0..cw * ch).map(|i| (100.0 + 40.0 * (((i % cw) as f64 * 2.0 - dx) / w as f64)).round() as u8).collect();
|
||||
let v: Vec<u8> = (0..cw * ch).map(|i| (150.0 - 30.0 * (((i / cw) as f64 * 2.0 - dy) / h as f64)).round() as u8).collect();
|
||||
(y, u, v)
|
||||
}
|
||||
|
||||
fn planes_of(p: &filmcraft_vp9::Picture, w: usize, h: usize) -> [Vec<u8>; 3] {
|
||||
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
|
||||
[crop(&plane_u8(&p.y), p.y_stride, w, h), crop(&plane_u8(&p.u), p.uv_stride, cw, ch), crop(&plane_u8(&p.v), p.uv_stride, cw, ch)]
|
||||
}
|
||||
|
||||
/// Encode `n` frames and decode them with one decoder: every decoded frame must equal the
|
||||
/// encoder's reconstruction. Returns (total bytes, mean luma PSNR vs the source).
|
||||
fn run_sequence(cfg: EncoderConfig, n: usize, kind: u32) -> (usize, f64) {
|
||||
let (w, h) = (cfg.width as usize, cfg.height as usize);
|
||||
let mut e = Vp9Encoder::new(cfg);
|
||||
let mut d = Decoder::new();
|
||||
let (mut bytes, mut db) = (0usize, 0.0);
|
||||
for t in 0..n {
|
||||
let (y, u, v) = moving(w, h, t, kind);
|
||||
let f = e.encode_frame(&y, &u, &v, false);
|
||||
bytes += f.data.len();
|
||||
let kind_s = if f.key { "key" } else { "inter" };
|
||||
let mut pics = d.decode(&f.data, t as i64).unwrap_or_else(|err| panic!("{w}x{h} frame {t} ({kind_s}): {err:?}"));
|
||||
assert_eq!(pics.len(), 1);
|
||||
let got = planes_of(&pics.remove(0), w, h);
|
||||
let rec = e.reconstruction().expect("reconstruction");
|
||||
for k in 0..3 {
|
||||
if got[k] != rec[k] {
|
||||
let first = got[k].iter().zip(&rec[k]).position(|(a, b)| a != b).unwrap_or(0);
|
||||
let pw = if k == 0 { w } else { w.div_ceil(2) };
|
||||
panic!("{w}x{h} frame {t} ({kind_s}, q{} lf{}): plane {k} differs first at ({}, {})", f.q_idx, f.filter_level, first % pw, first / pw);
|
||||
}
|
||||
}
|
||||
db += psnr(&got[0], &y);
|
||||
}
|
||||
(bytes, db / n as f64)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inter_frames_decode_exactly() {
|
||||
for (w, h) in [(64, 64), (96, 72), (33, 17), (130, 66)] {
|
||||
for (q, kind) in [(30u8, 0u32), (70, 1), (92, 0), (100, 0)] {
|
||||
let cfg = EncoderConfig { width: w as u32, height: h as u32, quality: q, keyframe_interval: 6, ..Default::default() };
|
||||
run_sequence(cfg, 8, kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inter_frames_with_tile_columns_decode_exactly() {
|
||||
let cfg = EncoderConfig { width: 4160, height: 24, quality: 80, keyframe_interval: 0, ..Default::default() };
|
||||
run_sequence(cfg, 3, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inter_psnr_rises_with_bitrate() {
|
||||
let (w, h) = (160, 96);
|
||||
let mut last = (0usize, 0.0f64);
|
||||
let mut rows = vec![];
|
||||
for kbps in [60u32, 150, 400, 1200] {
|
||||
let cfg = EncoderConfig { width: w, height: h, quality: 60, target_kbps: Some(kbps), frame_rate: 30.0, keyframe_interval: 30, ..Default::default() };
|
||||
let (bytes, db) = run_sequence(cfg, 20, 0);
|
||||
rows.push(format!("{kbps} kbps target: {:.0} kbps actual, {db:.2} dB", bytes as f64 * 8.0 * 30.0 / 20.0 / 1000.0));
|
||||
assert!(bytes > last.0 && db > last.1, "{rows:#?}");
|
||||
last = (bytes, db);
|
||||
}
|
||||
eprintln!("{rows:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inter_frames_are_much_smaller_than_intra() {
|
||||
let (w, h) = (192u32, 108u32);
|
||||
let mut report = vec![];
|
||||
for q in [50u8, 75, 90] {
|
||||
let intra = EncoderConfig { width: w, height: h, quality: q, keyframe_interval: 1, ..Default::default() };
|
||||
let inter = EncoderConfig { keyframe_interval: 0, ..intra.clone() };
|
||||
let (bi, pi) = run_sequence(intra, 24, 0);
|
||||
let (bp, pp) = run_sequence(inter, 24, 0);
|
||||
report.push(format!("q{q}: intra {bi} B {pi:.2} dB, inter {bp} B {pp:.2} dB, ratio {:.2}", bi as f64 / bp as f64));
|
||||
assert!(pp > pi - 1.0, "{report:#?}");
|
||||
assert!(bi as f64 >= 3.0 * bp as f64, "{report:#?}");
|
||||
}
|
||||
eprintln!("{report:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ffmpeg_decodes_inter_frames_like_the_encoder() {
|
||||
let (w, h) = (96usize, 64usize);
|
||||
let mut e = Vp9Encoder::new(EncoderConfig { width: w as u32, height: h as u32, quality: 75, keyframe_interval: 5, ..Default::default() });
|
||||
let n = 7;
|
||||
let mut ivf = Vec::new();
|
||||
ivf.extend_from_slice(b"DKIF");
|
||||
ivf.extend_from_slice(&0u16.to_le_bytes());
|
||||
ivf.extend_from_slice(&32u16.to_le_bytes());
|
||||
ivf.extend_from_slice(b"VP90");
|
||||
ivf.extend_from_slice(&(w as u16).to_le_bytes());
|
||||
ivf.extend_from_slice(&(h as u16).to_le_bytes());
|
||||
ivf.extend_from_slice(&30u32.to_le_bytes());
|
||||
ivf.extend_from_slice(&1u32.to_le_bytes());
|
||||
ivf.extend_from_slice(&(n as u32).to_le_bytes());
|
||||
ivf.extend_from_slice(&0u32.to_le_bytes());
|
||||
let mut recon = vec![];
|
||||
for t in 0..n {
|
||||
let (y, u, v) = moving(w, h, t, 0);
|
||||
let f = e.encode_frame(&y, &u, &v, false);
|
||||
ivf.extend_from_slice(&(f.data.len() as u32).to_le_bytes());
|
||||
ivf.extend_from_slice(&(t as u64).to_le_bytes());
|
||||
ivf.extend_from_slice(&f.data);
|
||||
recon.push(e.reconstruction().expect("recon"));
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("effectcraft-vp9-inter-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("a.ivf");
|
||||
std::fs::write(&path, &ivf).unwrap();
|
||||
let out = std::process::Command::new("ffmpeg")
|
||||
.args(["-hide_banner", "-loglevel", "error", "-i"])
|
||||
.arg(&path)
|
||||
.args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
|
||||
.output();
|
||||
let Ok(out) = out else {
|
||||
eprintln!("ffmpeg not found: skipping oracle");
|
||||
return;
|
||||
};
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let fsz = w * h + 2 * w.div_ceil(2) * h.div_ceil(2);
|
||||
assert_eq!(out.stdout.len(), fsz * n);
|
||||
for (t, r) in recon.iter().enumerate() {
|
||||
let frame = &out.stdout[t * fsz..(t + 1) * fsz];
|
||||
assert_eq!(&frame[..w * h], &r[0][..], "ffmpeg luma of frame {t}");
|
||||
assert_eq!(&frame[w * h..w * h + r[1].len()], &r[1][..], "ffmpeg U of frame {t}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoder speed on 720p (run with `--ignored --nocapture`).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bench_720p() {
|
||||
let (w, h) = (1280usize, 720usize);
|
||||
let mut e = Vp9Encoder::new(EncoderConfig { width: w as u32, height: h as u32, quality: 80, keyframe_interval: 0, ..Default::default() });
|
||||
for t in 0..6 {
|
||||
let (y, u, v) = moving(w, h, t, 0);
|
||||
let t0 = std::time::Instant::now();
|
||||
let f = e.encode_frame(&y, &u, &v, false);
|
||||
eprintln!("frame {t} ({}): {} B in {:.0} ms", if f.key { "key" } else { "inter" }, f.data.len(), t0.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user