Merge main into M7 3D branch
Resolve conflicts with perf (layer cache / Arc<Buf>), export (RenderOpts.view: None for output), timeline (separate dimensions + one-node POI visibility), mask/pen viewer gestures (alongside camera tools and view-aware layer matrices), key dialogs (alongside Camera/Light Settings), render queue + MCP command modules. 3D path tangent honours separated position; DOF blurs a per-frame copy so cached layer buffers stay shared. New test: cached renders match uncached after camera, focus, light and 3D view changes. Fix a clone-on-copy lint from main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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,352 @@
|
||||
//! 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,
|
||||
// Output renders always look through the comp's active camera.
|
||||
view: None,
|
||||
};
|
||||
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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user