M10: render queue + export
- crates/export (effectcraft-export): render a comp's span to H.264 MP4 (+AAC), ProRes 422/4444 MOV (+PCM, alpha), PNG/JPEG/TIFF/EXR sequences and animated GIF via FilmCraft's pure-Rust encoders and MP4/MOV muxer; parallel batched frame rendering, progress callback with cancellation. - project: Render Queue model (Render Settings, Output Module, output path templates, status) saved with the project. - render: FootageSource::audio hook + comp audio mixdown (levels, in/out, solo, precomps); media implements it. - engine: Exporter hook, background/blocking render job, renderQueue.* commands (add Cmd+M, remove, setRender, setRenderSettings, setOutputModule, setOutput, move, duplicate, render, stop, list, formats). - host wires the exporter; CLI `render` subcommand. - ui-egui: After Effects-style Render Queue panel with automation ids. - tests: encode/decode round trips for every format (FilmCraft decoders, ffmpeg/ffprobe oracle when installed), audio, cancel, engine commands. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
dee16181fe
commit
7f9c3a85c0
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "effectcraft-export"
|
||||
description = "Render Queue jobs and output modules: H.264 MP4 (+AAC) and ProRes MOV (+PCM) via FilmCraft's pure-Rust encoders, PNG/JPEG/TIFF/EXR sequences, animated GIF"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
effectcraft-time = { workspace = true }
|
||||
effectcraft-project = { workspace = true }
|
||||
effectcraft-raster = { workspace = true }
|
||||
effectcraft-render = { workspace = true }
|
||||
filmcraft-h264enc = { workspace = true }
|
||||
filmcraft-prores = { workspace = true }
|
||||
filmcraft-aac = { workspace = true }
|
||||
filmcraft-isobmff = { workspace = true }
|
||||
image = { workspace = true, features = ["png", "jpeg", "tiff", "exr"] }
|
||||
gif = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
effectcraft-media = { workspace = true }
|
||||
effectcraft-color = { workspace = true }
|
||||
@@ -0,0 +1,362 @@
|
||||
//! Movie export: FilmCraft H.264 → MP4 (+ AAC) and ProRes → MOV (+ PCM), muxed by
|
||||
//! FilmCraft's ISO BMFF / QuickTime writer.
|
||||
|
||||
use std::io::{BufWriter, Write};
|
||||
|
||||
use effectcraft_project::Comp;
|
||||
use effectcraft_project::render_queue::{Channels, OutputFormat, ProResProfile};
|
||||
use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
|
||||
use filmcraft_isobmff::{Brand, FourCc, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::{ExportError, Job, Report, Result, State, batch_size, render_frame, rgba8, wants_audio};
|
||||
|
||||
fn enc(e: impl std::fmt::Display) -> ExportError {
|
||||
ExportError::Encode(e.to_string())
|
||||
}
|
||||
fn mux_err(e: impl std::fmt::Display) -> ExportError {
|
||||
ExportError::Io(e.to_string())
|
||||
}
|
||||
|
||||
struct Packet {
|
||||
data: Vec<u8>,
|
||||
key: bool,
|
||||
/// pts − dts in the track timescale.
|
||||
cto: i32,
|
||||
}
|
||||
|
||||
trait VideoEncoder {
|
||||
fn sample_entry(&self) -> SampleEntry;
|
||||
fn encode(&mut self, rgba: &[u8], index: u64) -> Result<Vec<Packet>>;
|
||||
fn flush(&mut self) -> Result<Vec<Packet>>;
|
||||
/// Edit-list media start (B-frame delay) in the track timescale.
|
||||
fn media_start(&self) -> Option<i64> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- H.264
|
||||
|
||||
struct H264 {
|
||||
enc: filmcraft_h264enc::Encoder,
|
||||
w: u32,
|
||||
h: u32,
|
||||
rate: FrameRate,
|
||||
y: Vec<u8>,
|
||||
u: Vec<u8>,
|
||||
v: Vec<u8>,
|
||||
}
|
||||
|
||||
impl H264 {
|
||||
fn new(w: u32, h: u32, rate: FrameRate, kbps: u32) -> Result<H264> {
|
||||
let mut cfg = filmcraft_h264enc::EncoderConfig::new(w, h, rate.num as u32, rate.den as u32);
|
||||
cfg.format = filmcraft_h264enc::PacketFormat::LengthPrefixed;
|
||||
cfg.aud = false;
|
||||
cfg.keyint = (rate.as_f64() * 2.0).round().max(1.0) as u32;
|
||||
let kbps = kbps.max(100);
|
||||
cfg.rate = filmcraft_h264enc::RateControl::Vbr { target_kbps: kbps, max_kbps: kbps * 3 / 2 };
|
||||
let enc = filmcraft_h264enc::Encoder::new(cfg).map_err(enc)?;
|
||||
Ok(H264 { enc, w, h, rate, y: vec![], u: vec![], v: vec![] })
|
||||
}
|
||||
fn packets(&self, ps: Vec<filmcraft_h264enc::Packet>) -> Vec<Packet> {
|
||||
ps.into_iter().map(|p| Packet { data: p.data, key: p.keyframe, cto: (p.pts - p.dts) as i32 }).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoEncoder for H264 {
|
||||
fn sample_entry(&self) -> SampleEntry {
|
||||
let cfg = filmcraft_isobmff::AvcConfig::parse(&self.enc.avcc()).unwrap_or_else(|_| {
|
||||
let (sps, pps) = self.enc.sps_pps();
|
||||
filmcraft_isobmff::AvcConfig::new(vec![sps], vec![pps], 4)
|
||||
});
|
||||
SampleEntry::avc(cfg, self.w as u16, self.h as u16)
|
||||
}
|
||||
fn encode(&mut self, rgba: &[u8], index: u64) -> Result<Vec<Packet>> {
|
||||
rgba_to_yuv420(rgba, self.w as usize, self.h as usize, &mut self.y, &mut self.u, &mut self.v);
|
||||
let cw = (self.w as usize).div_ceil(2);
|
||||
let frame = filmcraft_h264enc::YuvFrame { y: &self.y, u: &self.u, v: &self.v, y_stride: self.w as usize, uv_stride: cw };
|
||||
let ps = self.enc.try_encode(&frame, index as i64 * self.rate.den).map_err(enc)?;
|
||||
Ok(self.packets(ps))
|
||||
}
|
||||
fn flush(&mut self) -> Result<Vec<Packet>> {
|
||||
let ps = self.enc.flush();
|
||||
Ok(self.packets(ps))
|
||||
}
|
||||
fn media_start(&self) -> Option<i64> {
|
||||
(self.enc.delay() > 0).then_some(self.rate.den)
|
||||
}
|
||||
}
|
||||
|
||||
/// BT.709 limited-range 8-bit 4:2:0 from RGBA8 (2×2 chroma average; alpha ignored).
|
||||
pub(crate) fn rgba_to_yuv420(rgba: &[u8], w: usize, h: usize, y: &mut Vec<u8>, u: &mut Vec<u8>, v: &mut Vec<u8>) {
|
||||
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
|
||||
y.resize(w * h, 0);
|
||||
u.resize(cw * ch, 0);
|
||||
v.resize(cw * ch, 0);
|
||||
y.par_chunks_mut(w * 2).zip(u.par_chunks_mut(cw).zip(v.par_chunks_mut(cw))).enumerate().for_each(|(cy, (yr, (ur, vr)))| {
|
||||
let rows = yr.len() / w;
|
||||
let mut acc = vec![(0f32, 0f32, 0f32); cw];
|
||||
for dy in 0..rows {
|
||||
let src = &rgba[(cy * 2 + dy) * w * 4..][..w * 4];
|
||||
for x in 0..w {
|
||||
let (r, g, b) = (src[x * 4] as f32 / 255.0, src[x * 4 + 1] as f32 / 255.0, src[x * 4 + 2] as f32 / 255.0);
|
||||
let l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
yr[dy * w + x] = (16.0 + 219.0 * l).round().clamp(1.0, 254.0) as u8;
|
||||
let a = &mut acc[x / 2];
|
||||
a.0 += (b - l) / 1.8556;
|
||||
a.1 += (r - l) / 1.5748;
|
||||
a.2 += 1.0;
|
||||
}
|
||||
}
|
||||
for (cx, a) in acc.iter().enumerate() {
|
||||
ur[cx] = (128.0 + 224.0 * a.0 / a.2).round().clamp(1.0, 254.0) as u8;
|
||||
vr[cx] = (128.0 + 224.0 * a.1 / a.2).round().clamp(1.0, 254.0) as u8;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- ProRes
|
||||
|
||||
struct ProRes {
|
||||
enc: filmcraft_prores::Encoder,
|
||||
profile: filmcraft_prores::Profile,
|
||||
w: u32,
|
||||
h: u32,
|
||||
alpha: bool,
|
||||
}
|
||||
|
||||
fn prores_profile(p: ProResProfile) -> filmcraft_prores::Profile {
|
||||
use filmcraft_prores::Profile;
|
||||
match p {
|
||||
ProResProfile::Proxy => Profile::Proxy,
|
||||
ProResProfile::Lt => Profile::Lt,
|
||||
ProResProfile::Standard => Profile::Standard,
|
||||
ProResProfile::Hq => Profile::Hq,
|
||||
ProResProfile::P4444 => Profile::P4444,
|
||||
ProResProfile::P4444Xq => Profile::P4444Xq,
|
||||
}
|
||||
}
|
||||
|
||||
impl ProRes {
|
||||
fn new(w: u32, h: u32, profile: ProResProfile, channels: Channels) -> ProRes {
|
||||
// Alpha needs a 4444 flavour.
|
||||
let profile = if channels == Channels::Rgba && !profile.is_4444() { ProResProfile::P4444 } else { profile };
|
||||
let profile = prores_profile(profile);
|
||||
let alpha = channels == Channels::Rgba;
|
||||
let mut cfg = filmcraft_prores::EncoderConfig::new(profile, w, h);
|
||||
cfg.encode_alpha = alpha;
|
||||
ProRes { enc: filmcraft_prores::Encoder::with_config(cfg), profile, w, h, alpha }
|
||||
}
|
||||
fn is_444(&self) -> bool {
|
||||
matches!(self.profile, filmcraft_prores::Profile::P4444 | filmcraft_prores::Profile::P4444Xq)
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoEncoder for ProRes {
|
||||
fn sample_entry(&self) -> SampleEntry {
|
||||
SampleEntry::prores(FourCc(self.profile.fourcc()), self.w as u16, self.h as u16)
|
||||
}
|
||||
fn encode(&mut self, rgba: &[u8], _index: u64) -> Result<Vec<Packet>> {
|
||||
let chroma = if self.is_444() { filmcraft_prores::ChromaFormat::Yuv444 } else { filmcraft_prores::ChromaFormat::Yuv422 };
|
||||
let mut fr = filmcraft_prores::Frame::new(self.w, self.h, chroma, 10, self.alpha);
|
||||
rgba_to_yuv_10(rgba, self.w as usize, self.h as usize, self.is_444(), &mut fr.y, &mut fr.cb, &mut fr.cr);
|
||||
if let Some(a) = fr.alpha.as_mut() {
|
||||
for (d, s) in a.iter_mut().zip(rgba.chunks_exact(4)) {
|
||||
*d = ((s[3] as u32 * 1023 + 127) / 255) as u16;
|
||||
}
|
||||
}
|
||||
let data = self.enc.encode(&fr).map_err(enc)?;
|
||||
Ok(vec![Packet { data, key: true, cto: 0 }])
|
||||
}
|
||||
fn flush(&mut self) -> Result<Vec<Packet>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
/// BT.709 limited-range 10-bit 4:2:2 (horizontal chroma average) or 4:4:4 from RGBA8.
|
||||
fn rgba_to_yuv_10(rgba: &[u8], w: usize, h: usize, full_chroma: bool, y: &mut [u16], cb: &mut [u16], cr: &mut [u16]) {
|
||||
let cw = if full_chroma { w } else { w.div_ceil(2) };
|
||||
debug_assert!(y.len() >= w * h && rgba.len() >= w * h * 4);
|
||||
y.par_chunks_mut(w).zip(cb.par_chunks_mut(cw).zip(cr.par_chunks_mut(cw))).enumerate().for_each(|(row, (yr, (cbr, crr)))| {
|
||||
let src = &rgba[row * w * 4..(row + 1) * w * 4];
|
||||
let mut us = vec![0f32; w];
|
||||
let mut vs = vec![0f32; w];
|
||||
for x in 0..w {
|
||||
let (r, g, b) = (src[x * 4] as f32 / 255.0, src[x * 4 + 1] as f32 / 255.0, src[x * 4 + 2] as f32 / 255.0);
|
||||
let l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
yr[x] = (64.0 + 876.0 * l).round().clamp(4.0, 1019.0) as u16;
|
||||
us[x] = (b - l) / 1.8556;
|
||||
vs[x] = (r - l) / 1.5748;
|
||||
}
|
||||
for cx in 0..cw {
|
||||
let (u, v) = if full_chroma {
|
||||
(us[cx], vs[cx])
|
||||
} else {
|
||||
let (a, b2) = (cx * 2, (cx * 2 + 1).min(w - 1));
|
||||
((us[a] + us[b2]) * 0.5, (vs[a] + vs[b2]) * 0.5)
|
||||
};
|
||||
cbr[cx] = (512.0 + 896.0 * u).round().clamp(4.0, 1019.0) as u16;
|
||||
crr[cx] = (512.0 + 896.0 * v).round().clamp(4.0, 1019.0) as u16;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- audio
|
||||
|
||||
enum Audio {
|
||||
Aac(Box<filmcraft_aac::Encoder>),
|
||||
Pcm,
|
||||
}
|
||||
|
||||
const AUDIO_CHANNELS: u32 = 2;
|
||||
|
||||
fn deinterleave(buf: &[f32]) -> [Vec<f32>; 2] {
|
||||
let l = buf.chunks_exact(2).map(|p| p[0]).collect();
|
||||
let r = buf.chunks_exact(2).map(|p| p[1]).collect();
|
||||
[l, r]
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the movie
|
||||
|
||||
type Writer = Mp4Writer<BufWriter<std::fs::File>>;
|
||||
|
||||
pub(crate) fn movie(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
|
||||
let rate = job.settings.rate(comp);
|
||||
let fmt = job.output.format;
|
||||
let channels = if fmt == OutputFormat::ProRes { job.output.channels } else { Channels::Rgb };
|
||||
let mut venc: Box<dyn VideoEncoder> = match fmt {
|
||||
OutputFormat::H264 => Box::new(H264::new(w, h, rate, job.output.bitrate_kbps)?),
|
||||
_ => Box::new(ProRes::new(w, h, job.output.prores_profile, channels)),
|
||||
};
|
||||
let brand = if fmt == OutputFormat::H264 { Brand::Mp4 } else { Brand::Mov };
|
||||
let batch = batch_size();
|
||||
let render = |k: u64| -> Vec<u8> { rgba8(&render_frame(job, comp, k), comp, channels, w, h) };
|
||||
|
||||
// Encode the first batch before creating tracks: encoders finalise their config on frame 1.
|
||||
let first_end = batch.min(st.total);
|
||||
let first: Vec<Vec<u8>> = (0..first_end).into_par_iter().map(render).collect();
|
||||
let mut pending = Vec::new();
|
||||
for (k, px) in first.iter().enumerate() {
|
||||
pending.extend(venc.encode(px, k as u64)?);
|
||||
}
|
||||
drop(first);
|
||||
st.advance(first_end)?;
|
||||
|
||||
let file = std::fs::File::create(job.path).map_err(mux_err)?;
|
||||
let opts = WriterOptions::new(brand);
|
||||
let movie_ts = opts.movie_timescale.max(1) as i128;
|
||||
let mut mux: Writer = Mp4Writer::new(BufWriter::new(file), opts).map_err(mux_err)?;
|
||||
let mut vcfg = TrackConfig::new(venc.sample_entry(), rate.num as u32);
|
||||
if let Some(start) = venc.media_start() {
|
||||
// An explicit edit: the convenience `media_start` edit would subtract the B-frame delay
|
||||
// from the media duration and drop the last frame.
|
||||
let frames_ts = st.total as i128 * rate.den as i128;
|
||||
let seg = (frames_ts * movie_ts + rate.num as i128 / 2) / rate.num as i128;
|
||||
vcfg.edits = vec![filmcraft_isobmff::Edit { segment_duration: seg as u64, media_time: start, media_rate: 0x10000 }];
|
||||
}
|
||||
let vt = mux.add_track(vcfg).map_err(mux_err)?;
|
||||
let sr = job.output.audio_sample_rate.clamp(8_000, 192_000);
|
||||
let with_audio = wants_audio(job);
|
||||
let mut audio = None;
|
||||
if with_audio {
|
||||
let (a, entry, start) = if brand == Brand::Mp4 {
|
||||
let e = filmcraft_aac::Encoder::new(filmcraft_aac::EncoderConfig::cbr(sr, AUDIO_CHANNELS as usize, 320_000)).map_err(enc)?;
|
||||
let entry = SampleEntry::aac(e.audio_specific_config(), AUDIO_CHANNELS, sr);
|
||||
let priming = e.priming_samples() as i64;
|
||||
(Audio::Aac(Box::new(e)), entry, Some(priming))
|
||||
} else {
|
||||
let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: AUDIO_CHANNELS, sample_rate: sr as f64 };
|
||||
(Audio::Pcm, SampleEntry::pcm(pcm), None)
|
||||
};
|
||||
let mut c = TrackConfig::new(entry, sr);
|
||||
c.media_start = start;
|
||||
let at = mux.add_track(c).map_err(mux_err)?;
|
||||
audio = Some((a, at));
|
||||
}
|
||||
let (span_start, span_end) = job.settings.span(comp);
|
||||
let mut cursor = span_start.to_units_floor(sr as i64);
|
||||
|
||||
let write_video = |mux: &mut Writer, ps: Vec<Packet>| -> Result<()> {
|
||||
for p in ps {
|
||||
mux.write_sample(vt, WriteSample { data: &p.data, duration: rate.den as u32, composition_offset: p.cto, is_sync: p.key }).map_err(mux_err)?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let mut write_audio_until = |mux: &mut Writer, until: Tick, cursor: &mut i64| -> Result<()> {
|
||||
let Some((a, at)) = audio.as_mut() else { return Ok(()) };
|
||||
let end = until.to_units_floor(sr as i64);
|
||||
if end <= *cursor {
|
||||
return Ok(());
|
||||
}
|
||||
let n = (end - *cursor) as usize;
|
||||
let start = Tick(((*cursor as i128 * TICKS_PER_SECOND as i128) / sr as i128) as i64);
|
||||
let buf = effectcraft_render::audio::mix_comp(job.project, job.footage, job.expr, job.comp, start, n, sr);
|
||||
*cursor = end;
|
||||
match a {
|
||||
Audio::Aac(e) => {
|
||||
let planar = deinterleave(&buf);
|
||||
let refs: Vec<&[f32]> = planar.iter().map(Vec::as_slice).collect();
|
||||
for au in e.encode(&refs) {
|
||||
mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?;
|
||||
}
|
||||
}
|
||||
Audio::Pcm => {
|
||||
let mut pcm = Vec::with_capacity(n * 4);
|
||||
for s in buf {
|
||||
pcm.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes());
|
||||
}
|
||||
mux.write_sample(*at, WriteSample { data: &pcm, duration: n as u32, composition_offset: 0, is_sync: true }).map_err(mux_err)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let total = st.total;
|
||||
let frame_end_time = |k: u64| -> Tick { if k >= total { span_end } else { job.settings.frame_time(comp, k) } };
|
||||
write_video(&mut mux, pending)?;
|
||||
write_audio_until(&mut mux, frame_end_time(first_end), &mut cursor)?;
|
||||
let mut i = first_end;
|
||||
while i < total {
|
||||
let end = (i + batch).min(total);
|
||||
let frames: Vec<Vec<u8>> = (i..end).into_par_iter().map(render).collect();
|
||||
for (k, px) in frames.iter().enumerate() {
|
||||
let ps = venc.encode(px, i + k as u64)?;
|
||||
write_video(&mut mux, ps)?;
|
||||
}
|
||||
write_audio_until(&mut mux, frame_end_time(end), &mut cursor)?;
|
||||
st.advance(end - i)?;
|
||||
i = end;
|
||||
}
|
||||
write_video(&mut mux, venc.flush()?)?;
|
||||
write_audio_until(&mut mux, span_end, &mut cursor)?;
|
||||
if let Some((Audio::Aac(e), at)) = audio.as_mut() {
|
||||
for au in e.flush() {
|
||||
mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?;
|
||||
}
|
||||
}
|
||||
let mut out = mux.finish().map_err(mux_err)?;
|
||||
out.flush().map_err(mux_err)?;
|
||||
drop(out);
|
||||
let bytes = std::fs::metadata(job.path).map(|m| m.len()).unwrap_or(0);
|
||||
Ok(Report { path: job.path.to_string(), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn yuv_of_primaries() {
|
||||
let rgba = [255u8, 255, 255, 255, 0, 0, 0, 255, 255, 0, 0, 255, 0, 255, 0, 255];
|
||||
let (mut y, mut u, mut v) = (vec![], vec![], vec![]);
|
||||
rgba_to_yuv420(&rgba, 2, 2, &mut y, &mut u, &mut v);
|
||||
assert_eq!(y[0], 235);
|
||||
assert_eq!(y[1], 16);
|
||||
assert_eq!((u.len(), v.len()), (1, 1));
|
||||
let (mut y10, mut cb, mut cr) = (vec![0u16; 4], vec![0u16; 4], vec![0u16; 4]);
|
||||
rgba_to_yuv_10(&rgba, 2, 2, true, &mut y10, &mut cb, &mut cr);
|
||||
assert_eq!(y10[0], 940);
|
||||
assert_eq!(y10[1], 64);
|
||||
assert_eq!(cb[0], 512);
|
||||
assert!(cr[2] > 900, "red has high Cr: {}", cr[2]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
//! Render Queue jobs: render a composition's time span and write it through an output module.
|
||||
//!
|
||||
//! | Format | Container / files | Video | Alpha | Audio |
|
||||
//! |---|---|---|---|---|
|
||||
//! | H.264 | MP4 | FilmCraft H.264 High, 8-bit 4:2:0 BT.709 limited, VBR | no | AAC-LC (FilmCraft), stereo |
|
||||
//! | ProRes | QuickTime MOV | FilmCraft ProRes 422 Proxy/LT/422/HQ, 10-bit; 4444/4444 XQ 4:4:4 | 4444 (16-bit alpha coding) | 16-bit PCM, stereo |
|
||||
//! | PNG / JPEG / TIFF sequence | one file per frame | 8-bit | PNG, TIFF | — |
|
||||
//! | OpenEXR sequence | one file per frame | 32-bit float, linear light, premultiplied | yes | — |
|
||||
//! | Animated GIF | GIF89a | 256-colour palette per frame (NeuQuant) | 1-bit | — |
|
||||
//!
|
||||
//! Frames are rendered in parallel batches (rayon; one batch ≈ one frame per core) and handed to
|
||||
//! the encoder in order. Progress is reported after each batch through a callback that can cancel
|
||||
//! the job by returning `false`. Codecs and the MP4/MOV muxer are FilmCraft's pure-Rust crates
|
||||
//! (plan ADR 0001); nothing outside this crate touches them.
|
||||
//!
|
||||
//! H.264 requires even dimensions: odd output sizes are cropped by one pixel (padded when the
|
||||
//! output is a single pixel wide/high).
|
||||
|
||||
mod encode;
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Instant;
|
||||
|
||||
use effectcraft_project::render_queue::{AudioOutput, Channels, OutputFormat, OutputModule, RenderQuality, RenderSettings, sequence_path};
|
||||
use effectcraft_project::{Comp, ItemId, Project};
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_render::{ExprHost, FootageSource, RenderOpts, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use rayon::prelude::*;
|
||||
|
||||
pub use effectcraft_project::render_queue;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ExportError {
|
||||
#[error("composition not found")]
|
||||
NoComp,
|
||||
#[error("cancelled")]
|
||||
Cancelled,
|
||||
#[error("i/o: {0}")]
|
||||
Io(String),
|
||||
#[error("encode: {0}")]
|
||||
Encode(String),
|
||||
#[error("{0}")]
|
||||
Unsupported(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, ExportError>;
|
||||
|
||||
fn io(e: impl std::fmt::Display) -> ExportError {
|
||||
ExportError::Io(e.to_string())
|
||||
}
|
||||
|
||||
/// One export: a comp, its Render Settings and Output Module, and the resolved output path.
|
||||
pub struct Job<'a> {
|
||||
pub project: &'a Project,
|
||||
pub footage: &'a dyn FootageSource,
|
||||
pub expr: Option<&'a dyn ExprHost>,
|
||||
pub comp: ItemId,
|
||||
pub settings: &'a RenderSettings,
|
||||
pub output: &'a OutputModule,
|
||||
/// Output file. For image sequences a run of `#` (or `[#####]`) becomes the frame number; a
|
||||
/// path without one gets `_NNNNN` before the extension.
|
||||
pub path: &'a str,
|
||||
}
|
||||
|
||||
/// Progress after a batch of frames.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Progress {
|
||||
pub done: u64,
|
||||
pub total: u64,
|
||||
pub elapsed: f64,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
pub fn fraction(&self) -> f64 {
|
||||
if self.total == 0 { 0.0 } else { self.done as f64 / self.total as f64 }
|
||||
}
|
||||
/// Estimated seconds remaining.
|
||||
pub fn remaining(&self) -> Option<f64> {
|
||||
(self.done > 0).then(|| self.elapsed / self.done as f64 * self.total.saturating_sub(self.done) as f64)
|
||||
}
|
||||
}
|
||||
|
||||
/// What an export produced.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Report {
|
||||
/// The movie file, or the first file of a sequence.
|
||||
pub path: String,
|
||||
pub frames: u64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub seconds: f64,
|
||||
pub bytes: u64,
|
||||
pub audio: bool,
|
||||
}
|
||||
|
||||
/// Formats this build can write (all of them; kept as the hook for optional encoders).
|
||||
pub fn available_formats() -> Vec<OutputFormat> {
|
||||
OutputFormat::ALL.to_vec()
|
||||
}
|
||||
|
||||
/// The size of the written frames for a job (H.264 rounds to even).
|
||||
pub fn output_size(comp: &Comp, settings: &RenderSettings, output: &OutputModule) -> (u32, u32) {
|
||||
let (w, h) = settings.output_size(comp);
|
||||
output.format.coded_size(w, h)
|
||||
}
|
||||
|
||||
/// Whether the job writes an audio track.
|
||||
pub fn wants_audio(job: &Job) -> bool {
|
||||
job.output.format.supports_audio()
|
||||
&& match job.output.audio {
|
||||
AudioOutput::On => true,
|
||||
AudioOutput::Off => false,
|
||||
AudioOutput::Auto => effectcraft_render::audio::comp_has_audio(job.project, job.comp),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the export (blocking). `progress` is called after every batch; returning `false` cancels.
|
||||
pub fn export(job: &Job, progress: &mut dyn FnMut(&Progress) -> bool) -> Result<Report> {
|
||||
let comp = job.project.comp(job.comp).ok_or(ExportError::NoComp)?;
|
||||
let t0 = Instant::now();
|
||||
let total = job.settings.frame_count(comp);
|
||||
let mut st = State { t0, total, done: 0, progress };
|
||||
st.advance(0)?;
|
||||
if let Some(dir) = Path::new(job.path).parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(dir).map_err(io)?;
|
||||
}
|
||||
let (w, h) = output_size(comp, job.settings, job.output);
|
||||
let mut report = match job.output.format {
|
||||
OutputFormat::H264 | OutputFormat::ProRes => encode::movie(job, comp, w, h, &mut st)?,
|
||||
OutputFormat::Gif => gif_export(job, comp, w, h, &mut st)?,
|
||||
f if f.is_sequence() => sequence(job, comp, w, h, &mut st)?,
|
||||
f => return Err(ExportError::Unsupported(f.label().into())),
|
||||
};
|
||||
report.seconds = t0.elapsed().as_secs_f64();
|
||||
report.frames = total;
|
||||
(report.width, report.height) = (w, h);
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
pub(crate) struct State<'p> {
|
||||
t0: Instant,
|
||||
total: u64,
|
||||
done: u64,
|
||||
progress: &'p mut dyn FnMut(&Progress) -> bool,
|
||||
}
|
||||
|
||||
impl State<'_> {
|
||||
fn snapshot(&self) -> Progress {
|
||||
Progress { done: self.done, total: self.total, elapsed: self.t0.elapsed().as_secs_f64() }
|
||||
}
|
||||
/// Count `n` more frames; `Err(Cancelled)` when the callback says stop.
|
||||
pub(crate) fn advance(&mut self, n: u64) -> Result<()> {
|
||||
self.done += n;
|
||||
let p = self.snapshot();
|
||||
if (self.progress)(&p) { Ok(()) } else { Err(ExportError::Cancelled) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames per parallel batch.
|
||||
pub(crate) fn batch_size() -> u64 {
|
||||
rayon::current_num_threads().clamp(2, 16) as u64
|
||||
}
|
||||
|
||||
/// Render output frame `i` of the job at the settings' resolution.
|
||||
pub(crate) fn render_frame(job: &Job, comp: &Comp, i: u64) -> Image {
|
||||
let t: Tick = job.settings.frame_time(comp, i);
|
||||
let opts = RenderOpts {
|
||||
scale: job.settings.resolution.clamp(0.01, 4.0),
|
||||
motion_blur: job.settings.motion_blur,
|
||||
guides: false,
|
||||
draft: job.settings.quality == RenderQuality::Draft,
|
||||
};
|
||||
let mut r = Renderer::new(job.project, job.footage, opts);
|
||||
r.expr = job.expr;
|
||||
r.comp_frame(job.comp, t)
|
||||
}
|
||||
|
||||
/// 8-bit RGBA of the requested channels (RGB: over the comp background, opaque; RGBA: straight),
|
||||
/// cropped/padded to `w`×`h`.
|
||||
pub(crate) fn rgba8(img: &Image, comp: &Comp, channels: Channels, w: u32, h: u32) -> Vec<u8> {
|
||||
let px = match channels {
|
||||
Channels::Rgb => img.to_rgba8_over(comp.background),
|
||||
Channels::Rgba => img.to_rgba8(),
|
||||
};
|
||||
fit(px, img.width, img.height, w, h)
|
||||
}
|
||||
|
||||
fn fit(px: Vec<u8>, iw: u32, ih: u32, w: u32, h: u32) -> Vec<u8> {
|
||||
if iw == w && ih == h {
|
||||
return px;
|
||||
}
|
||||
let mut out = vec![0u8; (w * h * 4) as usize];
|
||||
for y in 0..h.min(ih) as usize {
|
||||
let n = w.min(iw) as usize * 4;
|
||||
out[y * w as usize * 4..y * w as usize * 4 + n].copy_from_slice(&px[y * iw as usize * 4..y * iw as usize * 4 + n]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The comp frame number of output frame 0 (sequence numbering follows comp frames, like AE).
|
||||
fn first_frame_number(job: &Job, comp: &Comp) -> i64 {
|
||||
job.settings.first_frame(comp)
|
||||
}
|
||||
|
||||
fn sequence(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
|
||||
let f0 = first_frame_number(job, comp);
|
||||
let fmt = job.output.format;
|
||||
let channels = if fmt.supports_alpha() { job.output.channels } else { Channels::Rgb };
|
||||
let batch = batch_size();
|
||||
let mut bytes = 0u64;
|
||||
let mut i = 0;
|
||||
while i < st.total {
|
||||
let end = (i + batch).min(st.total);
|
||||
let written: Vec<Result<u64>> = (i..end)
|
||||
.into_par_iter()
|
||||
.map(|k| {
|
||||
let path = sequence_path(job.path, f0 + k as i64);
|
||||
if job.settings.skip_existing && Path::new(&path).exists() {
|
||||
return Ok(0);
|
||||
}
|
||||
let img = render_frame(job, comp, k);
|
||||
write_still(&path, fmt, &img, comp, channels, w, h, job.output.quality)?;
|
||||
Ok(std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0))
|
||||
})
|
||||
.collect();
|
||||
for r in written {
|
||||
bytes += r?;
|
||||
}
|
||||
st.advance(end - i)?;
|
||||
i = end;
|
||||
}
|
||||
Ok(Report { path: sequence_path(job.path, f0), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false })
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn write_still(path: &str, fmt: OutputFormat, img: &Image, comp: &Comp, channels: Channels, w: u32, h: u32, quality: u8) -> Result<()> {
|
||||
use image::{ExtendedColorType, ImageEncoder, ImageFormat};
|
||||
let file = || std::fs::File::create(path).map(std::io::BufWriter::new).map_err(io);
|
||||
match fmt {
|
||||
OutputFormat::ExrSequence => {
|
||||
// Linear light, premultiplied (the EXR convention); RGB keeps alpha = 1 over the background.
|
||||
let lin = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
|
||||
let mut data = Vec::with_capacity((w * h * 4) as usize);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let p = if x < img.width && y < img.height { img.data[img.idx(x, y)] } else { [0.0; 4] };
|
||||
let (c, a) = match channels {
|
||||
Channels::Rgba => {
|
||||
let a = p[3].clamp(0.0, 1.0);
|
||||
let s = |c: f32| if a > 0.0 { lin((c / a).clamp(0.0, 1.0)) * a } else { 0.0 };
|
||||
([s(p[0]), s(p[1]), s(p[2])], a)
|
||||
}
|
||||
Channels::Rgb => {
|
||||
let k = 1.0 - p[3].clamp(0.0, 1.0);
|
||||
let c = |i: usize| lin((p[i] + comp.background[i] * k).clamp(0.0, 1.0));
|
||||
([c(0), c(1), c(2)], 1.0)
|
||||
}
|
||||
};
|
||||
data.extend_from_slice(&[c[0], c[1], c[2], a]);
|
||||
}
|
||||
}
|
||||
let buf = image::Rgba32FImage::from_raw(w, h, data).ok_or_else(|| ExportError::Encode("exr buffer".into()))?;
|
||||
image::DynamicImage::ImageRgba32F(buf).save_with_format(path, ImageFormat::OpenExr).map_err(|e| ExportError::Encode(e.to_string()))
|
||||
}
|
||||
OutputFormat::JpegSequence => {
|
||||
let px = rgba8(img, comp, Channels::Rgb, w, h);
|
||||
let rgb: Vec<u8> = px.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect();
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(file()?, quality.clamp(1, 100))
|
||||
.write_image(&rgb, w, h, ExtendedColorType::Rgb8)
|
||||
.map_err(|e| ExportError::Encode(e.to_string()))
|
||||
}
|
||||
OutputFormat::PngSequence | OutputFormat::TiffSequence => {
|
||||
let px = rgba8(img, comp, channels, w, h);
|
||||
let (data, ct) = match channels {
|
||||
Channels::Rgba => (px, ExtendedColorType::Rgba8),
|
||||
Channels::Rgb => (px.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect(), ExtendedColorType::Rgb8),
|
||||
};
|
||||
if fmt == OutputFormat::PngSequence {
|
||||
image::codecs::png::PngEncoder::new(file()?).write_image(&data, w, h, ct).map_err(|e| ExportError::Encode(e.to_string()))
|
||||
} else {
|
||||
// The TIFF encoder needs Seek.
|
||||
let f = std::fs::File::create(path).map_err(io)?;
|
||||
image::codecs::tiff::TiffEncoder::new(std::io::BufWriter::new(f)).write_image(&data, w, h, ct).map_err(|e| ExportError::Encode(e.to_string()))
|
||||
}
|
||||
}
|
||||
f => Err(ExportError::Unsupported(format!("{} is not a still format", f.label()))),
|
||||
}
|
||||
}
|
||||
|
||||
fn gif_export(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
|
||||
if w > u16::MAX as u32 || h > u16::MAX as u32 {
|
||||
return Err(ExportError::Unsupported("GIF frames are limited to 65535 px".into()));
|
||||
}
|
||||
let file = std::fs::File::create(job.path).map_err(io)?;
|
||||
let mut enc = gif::Encoder::new(std::io::BufWriter::new(file), w as u16, h as u16, &[]).map_err(|e| ExportError::Encode(e.to_string()))?;
|
||||
enc.set_repeat(if job.output.gif_loop { gif::Repeat::Infinite } else { gif::Repeat::Finite(0) }).map_err(|e| ExportError::Encode(e.to_string()))?;
|
||||
let rate = job.settings.rate(comp);
|
||||
// GIF delays are in 1/100 s: carry the rounding error so long animations keep their timing.
|
||||
let cs_per_frame = 100.0 * rate.den as f64 / rate.num as f64;
|
||||
let mut clock = 0.0f64;
|
||||
let mut emitted = 0u64;
|
||||
let batch = batch_size();
|
||||
let mut i = 0;
|
||||
while i < st.total {
|
||||
let end = (i + batch).min(st.total);
|
||||
let frames: Vec<gif::Frame<'static>> = (i..end)
|
||||
.into_par_iter()
|
||||
.map(|k| {
|
||||
let img = render_frame(job, comp, k);
|
||||
let mut px = rgba8(&img, comp, job.output.channels, w, h);
|
||||
gif::Frame::from_rgba_speed(w as u16, h as u16, &mut px, 10)
|
||||
})
|
||||
.collect();
|
||||
for mut f in frames {
|
||||
clock += cs_per_frame;
|
||||
let d = (clock.round() as u64).saturating_sub(emitted).max(1);
|
||||
emitted += d;
|
||||
f.delay = d.min(u16::MAX as u64) as u16;
|
||||
if job.output.channels == Channels::Rgba {
|
||||
f.dispose = gif::DisposalMethod::Background;
|
||||
}
|
||||
enc.write_frame(&f).map_err(|e| ExportError::Encode(e.to_string()))?;
|
||||
}
|
||||
st.advance(end - i)?;
|
||||
i = end;
|
||||
}
|
||||
drop(enc);
|
||||
let bytes = std::fs::metadata(job.path).map(|m| m.len()).unwrap_or(0);
|
||||
Ok(Report { path: job.path.to_string(), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fit_crops_and_pads() {
|
||||
let px: Vec<u8> = (0..3 * 3 * 4).map(|v| v as u8).collect();
|
||||
let c = fit(px.clone(), 3, 3, 2, 2);
|
||||
assert_eq!(c.len(), 16);
|
||||
assert_eq!(&c[0..8], &px[0..8]);
|
||||
assert_eq!(&c[8..16], &px[12..20]);
|
||||
let p = fit(px, 3, 3, 4, 4);
|
||||
assert_eq!(p.len(), 64);
|
||||
assert_eq!(&p[12..16], &[0, 0, 0, 0]);
|
||||
assert_eq!(OutputFormat::H264.coded_size(1, 101), (2, 100));
|
||||
assert_eq!(OutputFormat::Gif.coded_size(1, 101), (1, 101));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
//! Encode a short comp to every output format and decode it back: through EffectCraft's own
|
||||
//! media layer (FilmCraft decoders) for MP4/MOV, the `image`/`gif` crates for stills and GIF,
|
||||
//! and — when installed — ffprobe as an external oracle (skipped otherwise).
|
||||
//!
|
||||
//! The comp: 64×48 @ 10 fps, 1.2 s (12 frames), dark-blue background, a red solid of 32×48
|
||||
//! centred, starting at frame 5. So frame < 5 is background everywhere; from frame 5 the centre
|
||||
//! is red and the corners stay background.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_export::render_queue::{AudioOutput, Channels, OutputFormat, OutputModule, ProResProfile, RenderSettings, TimeSpan, sequence_path};
|
||||
use effectcraft_export::{Job, Progress, export};
|
||||
use effectcraft_media::MediaPool;
|
||||
use effectcraft_project::{Comp, ItemId, ItemKind, LayerSource, Project, Solid, build};
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_render::{FootageSource, NoFootage};
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
|
||||
const W: u32 = 64;
|
||||
const H: u32 = 48;
|
||||
const BG: [f32; 3] = [0.1, 0.1, 0.4];
|
||||
const FRAMES: u64 = 12;
|
||||
|
||||
fn out_dir(name: &str) -> PathBuf {
|
||||
let d = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out/export").join(name);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).expect("mkdir");
|
||||
d
|
||||
}
|
||||
|
||||
fn project(audio: Option<&Path>) -> (Project, ItemId) {
|
||||
let mut p = Project::default();
|
||||
let mut comp = Comp::new(W, H, FrameRate::new(10, 1), Tick::from_seconds_f64(1.2));
|
||||
comp.background = BG;
|
||||
let sid = p.add_item("Red", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 32, height: H, pixel_aspect: 1.0 }));
|
||||
let mut l = build::layer(&mut p, &comp, "Red", LayerSource::Solid { item: sid }, (32, H), None);
|
||||
l.in_point = comp.frame_rate.tick_of(5);
|
||||
comp.layers.push(l);
|
||||
if let Some(path) = audio {
|
||||
let f = effectcraft_media::probe(path).expect("probe wav");
|
||||
let fid = p.add_item("tone.wav", Label::SeaFoam, None, ItemKind::Footage(f));
|
||||
let l = build::layer(&mut p, &comp, "tone", LayerSource::Footage { item: fid }, (0, 0), None);
|
||||
comp.layers.push(l);
|
||||
}
|
||||
let cid = p.add_item("Comp 1", Label::Sandstone, None, ItemKind::Comp(comp.into()));
|
||||
(p, cid)
|
||||
}
|
||||
|
||||
fn settings() -> RenderSettings {
|
||||
RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }
|
||||
}
|
||||
|
||||
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, comp: cid, settings: &s, output: om, path: &path };
|
||||
let mut last = Progress::default();
|
||||
let mut calls = 0;
|
||||
let r = export(&job, &mut |pr| {
|
||||
assert!(pr.done >= last.done, "progress is monotonic");
|
||||
last = *pr;
|
||||
calls += 1;
|
||||
true
|
||||
})
|
||||
.expect("export");
|
||||
assert_eq!(last.done, FRAMES);
|
||||
assert_eq!(last.total, FRAMES);
|
||||
assert!(calls >= 2);
|
||||
assert_eq!(r.frames, FRAMES);
|
||||
r
|
||||
}
|
||||
|
||||
fn px(img: &Image, x: u32, y: u32) -> [f32; 4] {
|
||||
img.data[img.idx(x, y)]
|
||||
}
|
||||
|
||||
fn near(a: [f32; 3], b: [f32; 3], tol: f32) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol)
|
||||
}
|
||||
|
||||
/// Check a decoded (premultiplied, opaque) frame `k`.
|
||||
fn check_frame(img: &Image, k: u64, tol: f32) {
|
||||
let corner = px(img, 2, 2);
|
||||
assert!(near([corner[0], corner[1], corner[2]], BG, tol), "frame {k} corner {corner:?}");
|
||||
let c = px(img, img.width / 2, img.height / 2);
|
||||
let want = if k >= 5 { [1.0, 0.0, 0.0] } else { BG };
|
||||
assert!(near([c[0], c[1], c[2]], want, tol), "frame {k} centre {c:?} want {want:?}");
|
||||
}
|
||||
|
||||
fn decode_movie(path: &Path, frames: u64, tol: f32) -> effectcraft_project::Footage {
|
||||
let f = effectcraft_media::probe(path).expect("probe our output");
|
||||
assert_eq!((f.width, f.height), (W, H));
|
||||
assert!(f.has_video);
|
||||
let n = f.frame_rate.frame_at(f.duration - Tick(1)) + 1;
|
||||
assert_eq!(n as u64, frames, "frame count from duration {:?} @ {:?}", f.duration, f.frame_rate);
|
||||
let pool = MediaPool::new();
|
||||
for k in 0..frames {
|
||||
let img = pool.frame_at(&f, f.frame_rate.tick_of(k as i64)).expect("decode");
|
||||
check_frame(&img, k, tol);
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
fn ffprobe(path: &Path) -> Option<String> {
|
||||
let out = Command::new("ffprobe")
|
||||
.args(["-v", "error", "-count_frames", "-show_entries", "stream=codec_name,width,height,nb_read_frames,pix_fmt", "-of", "compact=p=0:nk=1"])
|
||||
.arg(path)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
panic!("ffprobe rejected {}: {}", path.display(), String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
Some(String::from_utf8_lossy(&out.stdout).to_string())
|
||||
}
|
||||
|
||||
/// Frame `k` decoded by ffmpeg (external oracle) as RGBA, or `None` without ffmpeg.
|
||||
fn ffmpeg_frame(path: &Path, k: u64) -> Option<Image> {
|
||||
let png = path.with_extension(format!("ffmpeg-{k}.png"));
|
||||
let st = Command::new("ffmpeg")
|
||||
.args(["-hide_banner", "-loglevel", "error", "-y", "-i"])
|
||||
.arg(path)
|
||||
.args(["-vf", &format!("select=eq(n\\,{k})"), "-frames:v", "1", "-pix_fmt", "rgba"])
|
||||
.arg(&png)
|
||||
.status()
|
||||
.ok()?;
|
||||
assert!(st.success(), "ffmpeg failed to decode {}", path.display());
|
||||
let img = image::open(&png).expect("ffmpeg png").to_rgba8();
|
||||
Some(Image::from_rgba8(img.width(), img.height(), img.as_raw()))
|
||||
}
|
||||
|
||||
fn ffmpeg_check(path: &Path, tol: f32) {
|
||||
for k in [0, 4, 5, FRAMES - 1] {
|
||||
match ffmpeg_frame(path, k) {
|
||||
Some(img) => check_frame(&img, k, tol),
|
||||
None => {
|
||||
eprintln!("ffmpeg not found: skipping oracle decode");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn h264_mp4_roundtrip() {
|
||||
let d = out_dir("h264");
|
||||
let (p, cid) = project(None);
|
||||
let om = OutputModule { bitrate_kbps: 4000, ..OutputModule::for_format(OutputFormat::H264) };
|
||||
let path = d.join("comp.mp4");
|
||||
let r = run(&p, cid, &NoFootage, &om, &path);
|
||||
assert!(r.bytes > 100 && !r.audio);
|
||||
decode_movie(&path, FRAMES, 0.08);
|
||||
ffmpeg_check(&path, 0.08);
|
||||
if let Some(s) = ffprobe(&path) {
|
||||
assert!(s.contains("h264|64|48|yuv420p"), "{s}");
|
||||
assert!(s.lines().next().unwrap_or("").ends_with("|12"), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn h264_odd_size_is_cropped_even() {
|
||||
let d = out_dir("h264-odd");
|
||||
let (p, cid) = project(None);
|
||||
let om = OutputModule::for_format(OutputFormat::H264);
|
||||
let s = RenderSettings { resolution: 31.0 / 64.0, ..settings() };
|
||||
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, comp: cid, settings: &s, output: &om, path: &path };
|
||||
let r = export(&job, &mut |_| true).expect("export");
|
||||
assert_eq!((r.width % 2, r.height % 2), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prores_mov_roundtrip() {
|
||||
let d = out_dir("prores");
|
||||
let (p, cid) = project(None);
|
||||
let om = OutputModule::for_format(OutputFormat::ProRes);
|
||||
let path = d.join("comp.mov");
|
||||
run(&p, cid, &NoFootage, &om, &path);
|
||||
decode_movie(&path, FRAMES, 0.03);
|
||||
ffmpeg_check(&path, 0.03);
|
||||
if let Some(s) = ffprobe(&path) {
|
||||
assert!(s.starts_with("prores|64|48"), "{s}");
|
||||
assert!(s.lines().next().unwrap_or("").ends_with("|12"), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prores_4444_with_alpha() {
|
||||
let d = out_dir("prores4444");
|
||||
let (p, cid) = project(None);
|
||||
let om = OutputModule { channels: Channels::Rgba, prores_profile: ProResProfile::Hq, ..OutputModule::for_format(OutputFormat::ProRes) };
|
||||
let path = d.join("alpha.mov");
|
||||
run(&p, cid, &NoFootage, &om, &path);
|
||||
let f = effectcraft_media::probe(&path).expect("probe");
|
||||
let img = MediaPool::new().frame_at(&f, f.frame_rate.tick_of(7)).expect("decode");
|
||||
assert!(px(&img, 2, 2)[3] < 0.02, "corner transparent: {:?}", px(&img, 2, 2));
|
||||
let c = px(&img, W / 2, H / 2);
|
||||
assert!(c[3] > 0.98 && c[0] > 0.95 && c[1] < 0.05, "centre opaque red: {c:?}");
|
||||
if let Some(s) = ffprobe(&path) {
|
||||
assert!(s.starts_with("prores|64|48|yuva444"), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
fn check_still_dir(dir: &Path, ext: &str, tol: f32, alpha: bool) {
|
||||
for k in 0..FRAMES {
|
||||
let path = sequence_path(&dir.join(format!("f_[#####].{ext}")).to_string_lossy(), k as i64);
|
||||
let img = image::open(&path).unwrap_or_else(|e| panic!("{path}: {e}")).to_rgba8();
|
||||
assert_eq!(img.dimensions(), (W, H));
|
||||
let img = Image::from_rgba8(W, H, img.as_raw());
|
||||
if alpha {
|
||||
let corner = px(&img, 2, 2);
|
||||
assert!(corner[3] < 0.01, "{path}: corner {corner:?}");
|
||||
let c = px(&img, W / 2, H / 2);
|
||||
assert_eq!(c[3] > 0.99, k >= 5, "{path}: centre {c:?}");
|
||||
} else {
|
||||
check_frame(&img, k, tol);
|
||||
}
|
||||
}
|
||||
assert!(!dir.join(format!("f_{:05}.{ext}", FRAMES)).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_sequences_roundtrip() {
|
||||
let (p, cid) = project(None);
|
||||
for (fmt, ext, tol, ch) in [
|
||||
(OutputFormat::PngSequence, "png", 0.01, Channels::Rgb),
|
||||
(OutputFormat::PngSequence, "png", 0.01, Channels::Rgba),
|
||||
(OutputFormat::JpegSequence, "jpg", 0.06, Channels::Rgb),
|
||||
(OutputFormat::TiffSequence, "tif", 0.01, Channels::Rgb),
|
||||
(OutputFormat::TiffSequence, "tif", 0.01, Channels::Rgba),
|
||||
] {
|
||||
let d = out_dir(&format!("seq-{ext}-{ch:?}"));
|
||||
let om = OutputModule { channels: ch, ..OutputModule::for_format(fmt) };
|
||||
let r = run(&p, cid, &NoFootage, &om, &d.join(format!("f_[#####].{ext}")));
|
||||
assert!(r.path.ends_with(&format!("f_00000.{ext}")), "{}", r.path);
|
||||
check_still_dir(&d, ext, tol, ch == Channels::Rgba);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exr_sequence_is_linear() {
|
||||
let (p, cid) = project(None);
|
||||
let d = out_dir("seq-exr");
|
||||
let om = OutputModule::for_format(OutputFormat::ExrSequence);
|
||||
run(&p, cid, &NoFootage, &om, &d.join("f_[#####].exr"));
|
||||
let img = image::open(d.join("f_00000.exr")).expect("exr").to_rgba32f();
|
||||
assert_eq!(img.dimensions(), (W, H));
|
||||
let c = img.get_pixel(2, 2).0;
|
||||
// sRGB 0.4 → linear ≈ 0.133
|
||||
assert!((c[2] - 0.1329).abs() < 0.01 && (c[3] - 1.0).abs() < 1e-6, "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_roundtrip() {
|
||||
let (p, cid) = project(None);
|
||||
let d = out_dir("gif");
|
||||
let om = OutputModule::for_format(OutputFormat::Gif);
|
||||
let path = d.join("anim.gif");
|
||||
run(&p, cid, &NoFootage, &om, &path);
|
||||
let mut opts = gif::DecodeOptions::new();
|
||||
opts.set_color_output(gif::ColorOutput::RGBA);
|
||||
let mut dec = opts.read_info(std::fs::File::open(&path).expect("open")).expect("gif header");
|
||||
assert_eq!((dec.width() as u32, dec.height() as u32), (W, H));
|
||||
let mut k = 0;
|
||||
let mut total_delay = 0u32;
|
||||
while let Some(f) = dec.read_next_frame().expect("frame") {
|
||||
assert_eq!((f.width as u32, f.height as u32), (W, H));
|
||||
total_delay += f.delay as u32;
|
||||
let img = Image::from_rgba8(W, H, &f.buffer);
|
||||
check_frame(&img, k, 0.06);
|
||||
k += 1;
|
||||
}
|
||||
assert_eq!(k, FRAMES);
|
||||
assert_eq!(total_delay, 120, "1.2 s in centiseconds");
|
||||
if let Some(s) = ffprobe(&path) {
|
||||
assert!(s.starts_with("gif|64|48"), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_stops_early() {
|
||||
let (p, cid) = project(None);
|
||||
let d = out_dir("cancel");
|
||||
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, comp: cid, settings: &s, output: &om, path: &path };
|
||||
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);
|
||||
assert_eq!(written, 0, "cancelled before the first batch");
|
||||
}
|
||||
|
||||
/// 16-bit stereo WAV with a 440 Hz sine at amplitude 0.5 (left) and silence (right).
|
||||
fn write_tone(path: &Path, secs: f64) {
|
||||
let sr = 48_000u32;
|
||||
let n = (secs * sr as f64) as usize;
|
||||
let mut data = Vec::with_capacity(n * 4);
|
||||
for i in 0..n {
|
||||
let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * i as f64 / sr as f64).sin() * 32767.0).round() as i16;
|
||||
data.extend_from_slice(&s.to_le_bytes());
|
||||
data.extend_from_slice(&0i16.to_le_bytes());
|
||||
}
|
||||
let mut w = Vec::new();
|
||||
w.extend_from_slice(b"RIFF");
|
||||
w.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
|
||||
w.extend_from_slice(b"WAVEfmt ");
|
||||
w.extend_from_slice(&16u32.to_le_bytes());
|
||||
w.extend_from_slice(&1u16.to_le_bytes());
|
||||
w.extend_from_slice(&2u16.to_le_bytes());
|
||||
w.extend_from_slice(&sr.to_le_bytes());
|
||||
w.extend_from_slice(&(sr * 4).to_le_bytes());
|
||||
w.extend_from_slice(&4u16.to_le_bytes());
|
||||
w.extend_from_slice(&16u16.to_le_bytes());
|
||||
w.extend_from_slice(b"data");
|
||||
w.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
w.extend_from_slice(&data);
|
||||
std::fs::write(path, w).expect("write wav");
|
||||
}
|
||||
|
||||
fn rms(v: impl Iterator<Item = f32>) -> f32 {
|
||||
let (s, n) = v.fold((0.0f64, 0usize), |(s, n), x| (s + (x as f64) * (x as f64), n + 1));
|
||||
(s / n.max(1) as f64).sqrt() as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn movies_carry_audio() {
|
||||
let d = out_dir("audio");
|
||||
let wav = d.join("tone.wav");
|
||||
write_tone(&wav, 2.0);
|
||||
let (p, cid) = project(Some(&wav));
|
||||
let pool = MediaPool::new();
|
||||
for (fmt, name) in [(OutputFormat::H264, "a.mp4"), (OutputFormat::ProRes, "a.mov")] {
|
||||
let om = OutputModule { audio: AudioOutput::Auto, ..OutputModule::for_format(fmt) };
|
||||
let path = d.join(name);
|
||||
let r = run(&p, cid, &pool, &om, &path);
|
||||
assert!(r.audio, "{name}: auto audio is on for a comp with a sound layer");
|
||||
let f = effectcraft_media::probe(&path).expect("probe");
|
||||
assert!(f.has_audio, "{name}");
|
||||
let dec = MediaPool::new();
|
||||
let s = dec.audio_samples(&f, Tick::from_seconds_f64(0.3), 24_000, 48_000);
|
||||
let (l, r) = (rms(s.iter().step_by(2).copied()), rms(s.iter().skip(1).step_by(2).copied()));
|
||||
// sine of amplitude 0.5 → RMS ≈ 0.354
|
||||
assert!((l - 0.3536).abs() < 0.03, "{name}: left RMS {l}");
|
||||
assert!(r < 0.01, "{name}: right RMS {r}");
|
||||
if Command::new("ffprobe").arg("-version").output().is_ok() {
|
||||
let out = Command::new("ffprobe")
|
||||
.args(["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=codec_name,channels,sample_rate", "-of", "compact=p=0:nk=1"])
|
||||
.arg(&path)
|
||||
.output()
|
||||
.expect("ffprobe");
|
||||
let s = String::from_utf8_lossy(&out.stdout);
|
||||
let want = if fmt == OutputFormat::H264 { "aac|48000|2" } else { "pcm_s16le|48000|2" };
|
||||
assert!(s.trim() == want, "{name}: {s}");
|
||||
}
|
||||
// Audio off.
|
||||
let om = OutputModule { audio: AudioOutput::Off, ..om };
|
||||
let path = d.join(format!("silent-{name}"));
|
||||
assert!(!run(&p, cid, &pool, &om, &path).audio);
|
||||
assert!(!effectcraft_media::probe(&path).expect("probe").has_audio);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user