EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust
Merge main into M13.4 (codec completion): HEVC/AV1 on the export pipeline (Cx), one key-frame interval for all movie codecs
Brandon Thomasa30cf381804f
diff --cc Cargo.lockindex 63cd9b3c1,c3dcb41c6..fe40a0dcb--- a/Cargo.lock+++ b/Cargo.lock@@@ -1242,9 -1237,8 +1244,10 @@@ dependencies =name = "effectcraft-export"version = "0.1.0"dependencies = [+ "effectcraft-av1enc","effectcraft-color",+ "effectcraft-hevcenc",+ "effectcraft-keyframe","effectcraft-media","effectcraft-opusenc","effectcraft-project",diff --cc Cargo.tomlindex f12282d11,6641f2c4d..d5f6101a1--- a/Cargo.toml+++ b/Cargo.toml@@@ -38,8 -39,7 +39,9 @@@ effectcraft-ui-egui = { path = "crates/effectcraft-automation = { path = "crates/automation" }effectcraft-opusenc = { path = "crates/opusenc" }effectcraft-script = { path = "crates/script" }+effectcraft-hevcenc = { path = "crates/hevcenc" }+effectcraft-av1enc = { path = "crates/av1enc" }+ effectcraft-plugin = { path = "crates/plugin" }# foundationthiserror = "2"diff --cc crates/engine/src/commands/render_queue.rsindex c6f59a367,365d7e555..c0eedaec4--- a/crates/engine/src/commands/render_queue.rs+++ b/crates/engine/src/commands/render_queue.rs@@@ -131,33 -189,62 +189,63 @@@ fn apply_settings(rs: &mut RenderSettinOk(any)}- /// Apply Output Module parameters.- fn apply_output(om: &mut OutputModule, p: &Value, cmd: &str) -> Result<bool> {+ /// Apply a template to a module, keeping its output path (with the extension fixed).+ fn apply_om_template(om: &mut OutputModule, t: &OutputModule) {+ let keep = om.output.clone();+ let old = om.format;+ *om = t.clone();+ om.output = keep;+ let f = om.format;+ om.format = old;+ om.set_format(f);+ om.channels = t.channels;+ om.name = t.name.clone();+ }++ /// Apply Output Module parameters (`template` first). `roi`: the viewer's region of interest+ /// (captured by `crop.useRoi`).+ fn apply_output(om: &mut OutputModule, templates: &RenderTemplates, roi: Option<[f64; 4]>, p: &Value, cmd: &str) -> Result<bool> {let mut any = false;+ if let Some(t) = str_p(p, "template") {+ let t = templates.output_module(t).ok_or_else(|| bad(cmd, format!("no Output Module template “{t}”")))?;+ apply_om_template(om, &t);+ any = true;+ }+ let before = om.clone();if let Some(f) = str_p(p, "format") {- let f = OutputFormat::from_name(f).ok_or_else(|| bad(cmd, "format: h264|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff"))?;+ let f = OutputFormat::from_name(f).ok_or_else(|| bad(cmd, "format: h264|hevc|av1|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff"))?;om.set_format(f);- any = true;}if let Some(c) = str_p(p, "channels") {om.channels = match c.to_ascii_lowercase().replace([' ', '+'], "").as_str() {"rgb" => Channels::Rgb,"rgba" | "rgbalpha" => Channels::Rgba,- _ => return Err(bad(cmd, "channels: rgb|rgba")),+ "alpha" | "alphaonly" => Channels::Alpha,+ _ => return Err(bad(cmd, "channels: rgb|rgba|alpha")),};- if om.channels == Channels::Rgba && !om.format.supports_alpha() {+ if om.channels == Channels::Rgba && !om.supports_alpha() {return Err(bad(cmd, format!("{} has no alpha channel", om.format.label())));}- any = true;+ }+ if let Some(c) = str_p(p, "color").or(str_p(p, "alphaMode")) {+ om.alpha_mode = match c.to_ascii_lowercase().replace([' ', '(', ')'], "").as_str() {+ "straight" | "straightunmatted" => AlphaMode::Straight,+ "premultiplied" | "premultipliedmatted" | "premul" => AlphaMode::Premultiplied,+ _ => return Err(bad(cmd, "color: straight|premultiplied")),+ };}+ any |= apply_codec_options(om, p, cmd)?;if let Some(q) = f_p(p, "quality") {om.quality = q.clamp(1.0, 100.0) as u8;- any = true;}if let Some(b) = f_p(p, "bitrate") {- om.bitrate_kbps = b.clamp(100.0, 500_000.0) as u32;- any = true;+ om.bitrate_kbps = b.clamp(50.0, 500_000.0) as u32;+ }+ if let Some(b) = b_p(p, "webmBitrate") {+ om.webm_bitrate = b;+ }+ if let Some(k) = p.get("keyframeInterval").and_then(Value::as_u64) {+ om.keyframe_interval = k.min(100_000) as u32;}if let Some(pp) = str_p(p, "proresProfile") {om.prores_profile = ProResProfile::from_name(pp).ok_or_else(|| bad(cmd, "proresProfile: proxy|lt|standard|hq|4444|4444xq"))?;@@@ -200,66 -377,6 +378,62 @@@Ok(any)}+/// HEVC / AV1 codec options, the WebM video codec and the Opus audio options.+fn apply_codec_options(om: &mut OutputModule, p: &Value, cmd: &str) -> Result<bool> {+ use effectcraft_project::render_queue::{CodecProfile, OpusApplication, RateControlMode, VideoCodecOptions, WebmVideoCodec};+ let mut any = false;+ if let Some(c) = str_p(p, "webmCodec") {+ om.webm_codec = match c.to_ascii_lowercase().as_str() {+ "vp9" => WebmVideoCodec::Vp9,+ "av1" => WebmVideoCodec::Av1,+ _ => return Err(bad(cmd, "webmCodec: vp9|av1")),+ };+ if !om.supports_alpha() {+ om.channels = Channels::Rgb;+ }+ any = true;+ }+ if let Some(v) = str_p(p, "profile") {+ om.codec.profile = CodecProfile::from_name(v).ok_or_else(|| bad(cmd, "profile: main|main10"))?;+ any = true;+ }+ match p.get("level") {+ Some(Value::Null) => {+ om.codec.level = None;+ any = true;+ }+ Some(v) => {+ let s = match v {+ Value::String(s) => s.clone(),+ other => other.to_string(),+ };+ om.codec.level = VideoCodecOptions::parse_level(&s).ok_or_else(|| bad(cmd, "level: auto|null or a level like 4.1"))?;+ any = true;+ }+ None => {}+ }+ if let Some(v) = str_p(p, "rateControl") {+ om.codec.rate_control = RateControlMode::from_name(v).ok_or_else(|| bad(cmd, "rateControl: bitrate|quality"))?;+ any = true;+ }+ if let Some(q) = f_p(p, "quality") {+ om.codec.quality = q.clamp(1.0, 100.0) as u8;+ }- if let Some(k) = f_p(p, "keyframeInterval") {- om.codec.keyframe_interval = k.clamp(0.0, 100_000.0) as u32;- any = true;- }+ if let Some(b) = f_p(p, "audioBitrate") {+ om.opus_bitrate_kbps = b.clamp(6.0, 510.0) as u32;+ any = true;+ }+ if let Some(a) = str_p(p, "opusApplication") {+ om.opus_application = match a.to_ascii_lowercase().as_str() {+ "audio" | "music" => OpusApplication::Audio,+ "voip" | "voice" | "speech" => OpusApplication::Voip,+ _ => return Err(bad(cmd, "opusApplication: audio|voice")),+ };+ any = true;+ }+ Ok(any)+}+/// `module` (1-based; 1 = the first output module).fn module_p(s: &Session, i: usize, p: &Value, cmd: &str) -> Result<usize> {let n = p.get("module").and_then(Value::as_u64).unwrap_or(1) as usize;@@@ -591,7 -902,7 +969,7 @@@ pub fn specs() -> Vec<CommandSpec>"Add to Render Queue",["Composition"],Some("Cmd+M"),- "{comp?: id|name, format?: h264|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff, output?: path|template, quality?: best|draft|1-100 (jpeg, webm), resolution?: full|half|third|quarter|scale, timeSpan?: workArea|comp|custom, start?: s, end?: s, frameRate?: fps|null, motionBlur?: bool, skipExisting?: bool, proxyUse?: current|all|comp|none, channels?: rgb|rgba, bitrate?: kbps, proresProfile?: proxy|lt|standard|hq|4444|4444xq, audio?: auto|on|off, sampleRate?, loop?: bool}",- "{comp?: id|name, template?: Render Settings template, format?: h264|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff, output?: path|template, log?: errorsOnly|plusSettings|plusPerFrameInfo, quality?: best|draft|1-100 (jpeg, webm), resolution?: full|half|third|quarter|scale, proxyUse?, effects?, solo?, guideLayers?, colorDepth?, frameBlending?, fieldRender?, pulldown?, motionBlur?, timeSpan?: workArea|comp|custom, start?: s, end?: s, duration?: s, frameRate?: fps|null, skipExisting?: bool, storageOverflow?: bool, channels?: rgb|rgba|alpha, color?, bitrate?: kbps, webmBitrate?, keyframeInterval?, proresProfile?, crop?, resize?, includeProjectLink?, audio?: auto|on|off, sampleRate?, audioChannels?, audioFormat?, loop?: bool (values as in setRenderSettings / setOutputModule)}",++ "{comp?: id|name, template?: Render Settings template, format?: h264|hevc|av1|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff, output?: path|template, log?: errorsOnly|plusSettings|plusPerFrameInfo, quality?: best|draft|1-100 (jpeg, webm), resolution?: full|half|third|quarter|scale, proxyUse?, effects?, solo?, guideLayers?, colorDepth?, frameBlending?, fieldRender?, pulldown?, motionBlur?, timeSpan?: workArea|comp|custom, start?: s, end?: s, duration?: s, frameRate?: fps|null, skipExisting?: bool, storageOverflow?: bool, channels?: rgb|rgba|alpha, color?, bitrate?: kbps, webmBitrate?, keyframeInterval?, proresProfile?, profile?, level?, rateControl?, webmCodec?, audioBitrate?, opusApplication?, crop?, resize?, includeProjectLink?, audio?: auto|on|off, sampleRate?, audioChannels?, audioFormat?, loop?: bool (values as in setRenderSettings / setOutputModule)}",can_add,add),@@@ -611,7 -922,7 +989,7 @@@"Output Module Settings...",[],None,- "{item?|index?, module?: n (1 = first), format?: h264|hevc|av1|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff, channels?: rgb|rgba, quality?: 1-100, bitrate?: kbps, proresProfile?: proxy|lt|standard|hq|4444|4444xq, profile?: main|main10 (HEVC/AV1), level?: auto|4.1, rateControl?: bitrate|quality, keyframeInterval?: frames (0 = auto), webmCodec?: vp9|av1, audioBitrate?: Opus kbps, opusApplication?: audio|voice, audio?: auto|on|off, sampleRate?, loop?: bool, output?}",- "{item?|index?, module?: n (1 = first), template?: name, format?, channels?: rgb|rgba|alpha, color?: straight|premultiplied, quality?: 1-100, bitrate?: kbps, webmBitrate?: bool, keyframeInterval?: frames, proresProfile?: proxy|lt|standard|hq|4444|4444xq, crop?: bool|{useRoi?, roi?, top?, left?, bottom?, right?}, cropTop?, cropLeft?, cropBottom?, cropRight?, resize?: bool|{preset?, width?, height?, lockAspect?, quality?: low|high}, resizeWidth?, resizeHeight?, postRenderAction?: none|import|importAndReplace|setProxy, includeProjectLink?: bool, audio?: auto|on|off, sampleRate?, audioChannels?: mono|stereo, audioFormat?: 16|24|32, loop?: bool, output?}",++ "{item?|index?, module?: n (1 = first), template?: name, format?: h264|hevc|av1|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff, channels?: rgb|rgba|alpha, color?: straight|premultiplied, quality?: 1-100, bitrate?: kbps, webmBitrate?: bool, keyframeInterval?: frames (0 = auto), proresProfile?: proxy|lt|standard|hq|4444|4444xq, profile?: main|main10 (HEVC/AV1), level?: auto|4.1, rateControl?: bitrate|quality, webmCodec?: vp9|av1, audioBitrate?: Opus kbps, opusApplication?: audio|voice, crop?: bool|{useRoi?, roi?, top?, left?, bottom?, right?}, cropTop?, cropLeft?, cropBottom?, cropRight?, resize?: bool|{preset?, width?, height?, lockAspect?, quality?: low|high}, resizeWidth?, resizeHeight?, postRenderAction?: none|import|importAndReplace|setProxy, includeProjectLink?: bool, audio?: auto|on|off, sampleRate?, audioChannels?: mono|stereo, audioFormat?: 16|24|32, loop?: bool, output?}",has_items,set_output_module),diff --cc crates/engine/src/tests_codec_options.rsindex 7a42bf132,000000000..1504008f6mode 100644,000000..100644--- a/crates/engine/src/tests_codec_options.rs+++ b/crates/engine/src/tests_codec_options.rs@@@ -1,55 -1,0 +1,53 @@@+//! M13.4: HEVC / AV1 output modules and the WebM codec / Opus options over the command API.++use effectcraft_project::render_queue::{Channels, CodecProfile, OpusApplication, OutputFormat, RateControlMode, VideoCodecOptions, WebmVideoCodec};+use serde_json::json;++use crate::Session;++fn session() -> Session {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ s+}++#[test]+fn hevc_and_av1_output_module_options() {+ let mut s = session();+ let a = s+ .execute(+ "renderQueue.add",+ json!({"format": "hevc", "profile": "main10", "level": "4.1", "rateControl": "quality", "quality": 85, "keyframeInterval": 30}),+ )+ .unwrap();+ assert!(a["outputPath"].as_str().unwrap().ends_with(".mp4"), "{a}");+ let om = &s.project.render_queue[0].output;+ assert_eq!(om.format, OutputFormat::Hevc);- assert_eq!(- om.codec,- VideoCodecOptions { profile: CodecProfile::Main10, level: Some(41), rate_control: RateControlMode::Quality, quality: 85, keyframe_interval: 30 }- );++ assert_eq!(om.codec, VideoCodecOptions { profile: CodecProfile::Main10, level: Some(41), rate_control: RateControlMode::Quality, quality: 85 });++ assert_eq!(om.keyframe_interval, 30);+ assert!(a["outputModuleSummary"].as_str().unwrap_or_default().contains("Main 10"), "{a}");+ let id = a["item"].clone();+ s.execute("renderQueue.setOutputModule", json!({"item": id, "format": "av1", "level": null, "rateControl": "bitrate", "bitrate": 3000})).unwrap();+ let om = &s.project.render_queue[0].output;+ assert_eq!((om.format, om.codec.level, om.codec.rate_control, om.bitrate_kbps), (OutputFormat::Av1, None, RateControlMode::Bitrate, 3000));+ assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "channels": "rgba"})).is_err(), "AV1 MP4 has no alpha");+ assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "profile": "high"})).is_err());+ assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "level": "0.5"})).is_err());+ assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "rateControl": "cbr2"})).is_err());++ // WebM: VP9 with alpha, then AV1 (alpha dropped) with voice-tuned Opus.+ s.execute("renderQueue.setOutputModule", json!({"item": id, "format": "webm", "channels": "rgba"})).unwrap();+ assert_eq!(s.project.render_queue[0].output.channels, Channels::Rgba);+ s.execute("renderQueue.setOutputModule", json!({"item": id, "webmCodec": "av1", "audioBitrate": 24, "opusApplication": "voice"})).unwrap();+ let om = &s.project.render_queue[0].output;+ assert_eq!((om.webm_codec, om.channels, om.opus_bitrate_kbps, om.opus_application), (WebmVideoCodec::Av1, Channels::Rgb, 24, OpusApplication::Voip));+ assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "webmCodec": "theora"})).is_err());++ // The formats query lists the new formats and option values.+ let f = s.execute("renderQueue.formats", json!({})).unwrap();+ let ids: Vec<&str> = f["formats"].as_array().unwrap().iter().filter_map(|v| v["id"].as_str()).collect();+ assert!(ids.contains(&"Hevc") && ids.contains(&"Av1"), "{ids:?}");+ assert_eq!(f["codecProfiles"], json!(["Main", "Main 10"]));+ assert!(f["hevcLevels"].as_array().unwrap().contains(&json!("4.1")));+ assert_eq!(f["webmCodecs"], json!(["vp9", "av1"]));+}diff --cc crates/export/src/encode.rsindex 860baacbb,b0566d9bf..167b5f332--- a/crates/export/src/encode.rs+++ b/crates/export/src/encode.rs@@@ -221,19 -248,20 +249,22 @@@ pub(crate) fn pcm_bytes(buf: &[f32], fmtype Writer<'f, 's> = Mp4Writer<&'f mut crate::out::Out<'s>>;- pub(crate) fn movie(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {+ pub(crate) fn movie(job: &Cx, 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 channels = match job.output.channels {+ Channels::Rgba if fmt != OutputFormat::ProRes => Channels::Rgb,+ c => c,+ };let mut venc: Box<dyn VideoEncoder> = match fmt {OutputFormat::H264 => Box::new(H264::new(w, h, rate, job.output.bitrate_kbps)?),+ OutputFormat::Hevc => Box::new(crate::hevc_av1::Hevc::new(w, h, rate, job.output)?),+ OutputFormat::Av1 => Box::new(crate::hevc_av1::Av1::new(w, h, rate, job.output)?),- _ => Box::new(ProRes::new(w, h, job.output.prores_profile, channels)),+ _ => Box::new(ProRes::new(w, h, job.output.prores_profile, if channels == Channels::Alpha { Channels::Rgb } else { channels })),};- let brand = if fmt == OutputFormat::H264 { Brand::Mp4 } else { Brand::Mov };+ let brand = if fmt == OutputFormat::ProRes { Brand::Mov } else { Brand::Mp4 };let batch = batch_size();- let render = |k: u64| -> Vec<u8> { rgba8(&render_frame(job, comp, k), comp, channels, w, h) };+ let render = |k: u64| -> Vec<u8> { job.pixels(&job.frame(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);diff --cc crates/export/src/hevc_av1.rsindex ba447dba5,000000000..f42ccda24mode 100644,000000..100644--- a/crates/export/src/hevc_av1.rs+++ b/crates/export/src/hevc_av1.rs@@@ -1,203 -1,0 +1,203 @@@+//! HEVC (`effectcraft-hevcenc`) and AV1 (`effectcraft-av1enc`) video encoders for the MP4+//! movie writer (`hvc1` / `av01` sample entries) and AV1 in WebM, configured from the Output+//! Module's [`VideoCodecOptions`].++use effectcraft_project::render_queue::{CodecProfile, OutputModule, RateControlMode, VideoCodecOptions};+use effectcraft_time::FrameRate;+use filmcraft_isobmff::{Av1Config, CodecConfig, FourCc, HevcConfig, SampleEntry};+use rayon::prelude::*;++use crate::encode::{Packet, VideoEncoder};+use crate::{ExportError, Result};++fn enc_err(e: impl std::fmt::Display) -> ExportError {+ ExportError::Encode(e.to_string())+}++/// BT.709 limited-range 4:2:0 planes at `bits` (8 or 10) from RGBA8 (2×2 chroma average;+/// alpha ignored). Chroma planes are `ceil(w/2)` × `ceil(h/2)`.+pub(crate) fn rgba_to_yuv420_bits(rgba: &[u8], w: usize, h: usize, bits: u8, y: &mut Vec<u16>, u: &mut Vec<u16>, v: &mut Vec<u16>) {+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));+ let scale = (1u32 << (bits - 8)) as f32;+ let (lo, hi) = (scale, 254.0 * scale + (scale - 1.0));+ 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) * scale).round().clamp(lo, hi) as u16;+ 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) * scale).round().clamp(lo, hi) as u16;+ vr[cx] = ((128.0 + 224.0 * a.1 / a.2) * scale).round().clamp(lo, hi) as u16;+ }+ });+}++#[derive(Default)]+struct Planes {+ y: Vec<u16>,+ u: Vec<u16>,+ v: Vec<u16>,+}++// ---------------------------------------------------------------- HEVC++pub(crate) struct Hevc {+ enc: effectcraft_hevcenc::Encoder,+ w: u32,+ h: u32,+ bits: u8,+ planes: Planes,+}++/// The HEVC encoder settings for an output module.+pub(crate) fn hevc_config(w: u32, h: u32, rate: FrameRate, om: &OutputModule) -> effectcraft_hevcenc::EncoderConfig {+ use effectcraft_hevcenc as he;+ let o: &VideoCodecOptions = &om.codec;+ let mut cfg = he::EncoderConfig::new(w, h, rate.num as u32, rate.den as u32);+ cfg.profile = match o.profile {+ CodecProfile::Main => he::Profile::Main,+ CodecProfile::Main10 => he::Profile::Main10,+ };+ cfg.level_idc = o.hevc_level_idc();+ cfg.rate = match o.rate_control {+ RateControlMode::Bitrate => he::RateControl::Bitrate { kbps: om.bitrate_kbps.max(50) },+ RateControlMode::Quality => he::RateControl::ConstantQp(o.hevc_qp()),+ };- cfg.keyint = o.keyint(rate.as_f64());++ cfg.keyint = om.keyint(rate.as_f64());+ cfg+}++impl Hevc {+ pub(crate) fn new(w: u32, h: u32, rate: FrameRate, om: &OutputModule) -> Result<Hevc> {+ let cfg = hevc_config(w, h, rate, om);+ let bits = cfg.profile.bit_depth();+ let enc = effectcraft_hevcenc::Encoder::new(cfg).map_err(enc_err)?;+ Ok(Hevc { enc, w, h, bits, planes: Planes::default() })+ }+}++impl VideoEncoder for Hevc {+ fn sample_entry(&self) -> SampleEntry {+ let cfg = HevcConfig::parse(&self.enc.hvcc()).unwrap_or_default();+ SampleEntry::hevc(cfg, self.w as u16, self.h as u16)+ }+ fn encode(&mut self, rgba: &[u8], _index: u64) -> Result<Vec<Packet>> {+ let (w, h) = (self.w as usize, self.h as usize);+ let p = &mut self.planes;+ rgba_to_yuv420_bits(rgba, w, h, self.bits, &mut p.y, &mut p.u, &mut p.v);+ let frame = effectcraft_hevcenc::Frame { y: &p.y, u: &p.u, v: &p.v, y_stride: w, uv_stride: w.div_ceil(2) };+ let pk = self.enc.encode(&frame);+ Ok(vec![Packet { data: pk.data, key: pk.keyframe, cto: 0 }])+ }+ fn flush(&mut self) -> Result<Vec<Packet>> {+ Ok(vec![])+ }+}++// ---------------------------------------------------------------- AV1++pub(crate) struct Av1 {+ enc: effectcraft_av1enc::Encoder,+ w: u32,+ h: u32,+ bits: u8,+ planes: Planes,+}++/// The AV1 encoder settings for an output module.+pub(crate) fn av1_config(w: u32, h: u32, rate: FrameRate, om: &OutputModule) -> effectcraft_av1enc::EncoderConfig {+ use effectcraft_av1enc as ae;+ let o: &VideoCodecOptions = &om.codec;+ let mut cfg = ae::EncoderConfig::new(w, h, rate.num as u32, rate.den as u32);+ cfg.bit_depth = o.profile.bit_depth();+ cfg.level_idx = o.av1_level_idx();+ cfg.rate = match o.rate_control {+ RateControlMode::Bitrate => ae::RateControl::Bitrate { kbps: om.bitrate_kbps.max(50) },+ RateControlMode::Quality => ae::RateControl::ConstantQ(o.av1_qindex()),+ };- cfg.keyint = o.keyint(rate.as_f64());++ cfg.keyint = om.keyint(rate.as_f64());+ cfg+}++impl Av1 {+ pub(crate) fn new(w: u32, h: u32, rate: FrameRate, om: &OutputModule) -> Result<Av1> {+ let cfg = av1_config(w, h, rate, om);+ let bits = cfg.bit_depth;+ let enc = effectcraft_av1enc::Encoder::new(cfg).map_err(enc_err)?;+ Ok(Av1 { enc, w, h, bits, planes: Planes::default() })+ }+ /// The `av1C` record (also the WebM CodecPrivate).+ pub(crate) fn av1c(&self) -> Vec<u8> {+ self.enc.av1c()+ }+}++impl VideoEncoder for Av1 {+ fn sample_entry(&self) -> SampleEntry {+ let cfg = Av1Config::parse(&self.enc.av1c()).unwrap_or_default();+ SampleEntry::video(FourCc(*b"av01"), CodecConfig::Av1(cfg), self.w as u16, self.h as u16)+ }+ fn encode(&mut self, rgba: &[u8], _index: u64) -> Result<Vec<Packet>> {+ let (w, h) = (self.w as usize, self.h as usize);+ let p = &mut self.planes;+ rgba_to_yuv420_bits(rgba, w, h, self.bits, &mut p.y, &mut p.u, &mut p.v);+ let frame = effectcraft_av1enc::Frame { y: &p.y, u: &p.u, v: &p.v, y_stride: w, uv_stride: w.div_ceil(2) };+ let pk = self.enc.encode(&frame);+ Ok(vec![Packet { data: pk.data, key: pk.keyframe, cto: 0 }])+ }+ fn flush(&mut self) -> Result<Vec<Packet>> {+ Ok(vec![])+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ten_bit_planes_scale_eight_bit_ones() {+ 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_bits(&rgba, 2, 2, 8, &mut y, &mut u, &mut v);+ assert_eq!((y[0], y[1]), (235, 16));+ rgba_to_yuv420_bits(&rgba, 2, 2, 10, &mut y, &mut u, &mut v);+ assert_eq!((y[0], y[1]), (940, 64));+ assert_eq!(u.len(), 1);+ }++ #[test]+ fn codec_options_map_to_encoder_settings() {+ let mut om = OutputModule::for_format(effectcraft_project::render_queue::OutputFormat::Hevc);+ om.codec.profile = CodecProfile::Main10;+ om.codec.level = Some(41);+ om.codec.rate_control = RateControlMode::Quality;+ om.codec.quality = 100;- om.codec.keyframe_interval = 12;++ om.keyframe_interval = 12;+ let rate = FrameRate::new(30, 1);+ let h = hevc_config(64, 32, rate, &om);+ assert_eq!(h.profile, effectcraft_hevcenc::Profile::Main10);+ assert_eq!(h.level_idc, Some(123));+ assert_eq!(h.rate, effectcraft_hevcenc::RateControl::ConstantQp(4));+ assert_eq!(h.keyint, 12);+ let a = av1_config(64, 32, rate, &om);+ assert_eq!((a.bit_depth, a.level_idx, a.keyint), (10, Some(9), 12));+ om.codec.rate_control = RateControlMode::Bitrate;- om.codec.keyframe_interval = 0;++ om.keyframe_interval = 0;+ om.bitrate_kbps = 3000;+ let a = av1_config(64, 32, rate, &om);+ assert_eq!((a.rate, a.keyint), (effectcraft_av1enc::RateControl::Bitrate { kbps: 3000 }, 60));+ }+}diff --cc crates/export/src/lib.rsindex 1b1949964,f1e3269fd..ae889742a--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@@ -7,10 -7,16 +7,18 @@@//! | 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 | — |- //! | WebM | WebM (Matroska) | VP9 profile 0 intra frames (`effectcraft-vp9enc`), 8-bit 4:2:0 | VP9 alpha (BlockAdditional) | Opus (`effectcraft-opusenc`), 48 kHz stereo |- //! | HEVC | MP4 (`hvc1`) | `effectcraft-hevcenc` Main / Main 10 4:2:0, I + P slices, bitrate or constant quality, level, key-frame interval | no | AAC-LC (FilmCraft), stereo |- //! | AV1 | MP4 (`av01`), or WebM with the WebM format's AV1 codec | `effectcraft-av1enc` Main 8/10-bit 4:2:0, key + inter frames | no | AAC-LC in MP4, Opus in WebM |- //! | WAV / AIFF | RIFF WAVE / AIFF | — | — | 16-bit PCM stereo (audio only) |-//! | WebM | WebM (Matroska) | VP9 profile 0 (`effectcraft-vp9enc`: key + inter frames, a key frame every 2 s, loop filter), 8-bit 4:2:0 | VP9 alpha (BlockAdditional) | Opus (`effectcraft-opusenc`), 48 kHz stereo |++//! | WebM | WebM (Matroska) | VP9 profile 0 (`effectcraft-vp9enc`: key + inter frames, a key frame every 2 s, loop filter), 8-bit 4:2:0; or AV1 (`effectcraft-av1enc`) | VP9 alpha (BlockAdditional) | Opus (`effectcraft-opusenc`: SILK / hybrid / CELT by bitrate and application), 48 kHz |++//! | HEVC | MP4 (`hvc1`) | `effectcraft-hevcenc` Main / Main 10 4:2:0, I + P slices, bitrate or constant quality, level, key-frame interval | no | AAC-LC (FilmCraft) |++//! | AV1 | MP4 (`av01`) | `effectcraft-av1enc` Main 8/10-bit 4:2:0, key + inter frames | no | AAC-LC (FilmCraft) |+ //! | WAV / AIFF | RIFF WAVE / AIFF | — | — | PCM 16/24-bit (WAV also 32-bit float), mono/stereo (audio only) |+ //!+ //! Every frame goes through [`pipeline`]: the Render Settings overrides (Effects, Solo Switches,+ //! Guide Layers, Frame Blending, Motion Blur, Color Depth), field rendering (two fields half a+ //! frame apart woven line by line, with optional 3:2 pulldown from film frames at 4/5 of the+ //! rate), then the Output Module's Crop (edges or the region of interest) and Resize. Channels+ //! may be RGB, RGB + Alpha (straight or premultiplied) or the alpha matte alone. With Use Storage+ //! Overflow and a [`StorageQuota`] hook, files that don't fit go to the overflow folders. A+ //! render log (Errors Only / Plus Settings / Plus Per Frame Info) is written next to the output.//!//! 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@@@ -21,10 -27,9 +29,11 @@@//! output is a single pixel wide/high).mod encode;+mod hevc_av1;mod out;+ mod pipeline;mod webm;+mod webm_av1;use web_time::Instant;@@@ -131,19 -155,30 +159,30 @@@ pub fn wants_audio(job: &Job) -> bool/// 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 cx = Cx::new(job);+ let mut r = export_with(&cx, progress, t0);+ let log = cx.write_log(&r, t0.elapsed().as_secs_f64());+ if let Ok(rep) = &mut r {+ rep.log = log;+ rep.overflow = cx.overflowed.lock().unwrap_or_else(|e| e.into_inner()).clone();+ }+ r+ }++ fn export_with(cx: &Cx, progress: &mut dyn FnMut(&Progress) -> bool, t0: Instant) -> Result<Report> {+ let comp = cx.comp().ok_or(ExportError::NoComp)?;+ let total = cx.settings.frame_count(comp);let mut st = State { t0, total, done: 0, progress };st.advance(0)?;- let (w, h) = output_size(comp, job.settings, job.output);- let mut report = match job.output.format {- OutputFormat::H264 | OutputFormat::Hevc | OutputFormat::Av1 | OutputFormat::ProRes => encode::movie(job, comp, w, h, &mut st)?,- OutputFormat::Gif => gif_export(job, comp, w, h, &mut st)?,- OutputFormat::WebM => webm::webm(job, comp, w, h, &mut st)?,- OutputFormat::Wav => webm::audio_file(job, comp, false, &mut st)?,- OutputFormat::Aiff => webm::audio_file(job, comp, true, &mut st)?,- f if f.is_sequence() => sequence(job, comp, w, h, &mut st)?,+ let (w, h) = output_size(comp, cx.settings, cx.output);+ let mut report = match cx.output.format {- OutputFormat::H264 | OutputFormat::ProRes => encode::movie(cx, comp, w, h, &mut st)?,++ OutputFormat::H264 | OutputFormat::Hevc | OutputFormat::Av1 | OutputFormat::ProRes => encode::movie(cx, comp, w, h, &mut st)?,+ OutputFormat::Gif => gif_export(cx, comp, w, h, &mut st)?,+ OutputFormat::WebM => webm::webm(cx, comp, w, h, &mut st)?,+ OutputFormat::Wav => webm::audio_file(cx, comp, false, &mut st)?,+ OutputFormat::Aiff => webm::audio_file(cx, comp, true, &mut st)?,+ f if f.is_sequence() => sequence(cx, comp, w, h, &mut st)?,f => return Err(ExportError::Unsupported(f.label().into())),};report.seconds = t0.elapsed().as_secs_f64();diff --cc crates/export/src/webm.rsindex 4aa170fda,af38eaeb3..bb3daa039--- a/crates/export/src/webm.rs+++ b/crates/export/src/webm.rs@@@ -17,19 -19,21 +19,20 @@@ use effectcraft_project::render_queue::use effectcraft_time::{TICKS_PER_SECOND, Tick};use rayon::prelude::*;- use crate::{Job, Report, Result, State, batch_size, io, render_frame, rgba8, wants_audio};+ use crate::encode::{mix, pcm_bytes};+ use crate::{Cx, Report, Result, State, batch_size, io, wants_audio};-const OPUS_RATE: u32 = 48_000;-const OPUS_BITRATE: u32 = 192_000;+pub(crate) const OPUS_RATE: u32 = 48_000;// Element ids (with their length markers).-const EBML: u32 = 0x1A45_DFA3;-const SEGMENT: u32 = 0x1853_8067;-const INFO: u32 = 0x1549_A966;-const TRACKS: u32 = 0x1654_AE6B;-const TRACK_ENTRY: u32 = 0xAE;-const CLUSTER: u32 = 0x1F43_B675;--fn id_bytes(id: u32) -> Vec<u8> {+pub(crate) const EBML: u32 = 0x1A45_DFA3;+pub(crate) const SEGMENT: u32 = 0x1853_8067;+pub(crate) const INFO: u32 = 0x1549_A966;+pub(crate) const TRACKS: u32 = 0x1654_AE6B;+pub(crate) const TRACK_ENTRY: u32 = 0xAE;+pub(crate) const CLUSTER: u32 = 0x1F43_B675;++pub(crate) fn id_bytes(id: u32) -> Vec<u8> {let b = id.to_be_bytes();let skip = b.iter().position(|x| *x != 0).unwrap_or(3);b[skip..].to_vec()@@@ -112,22 -125,27 +124,37 @@@ fn cluster(frames: &mut [Frame]) -> Vecout}- /// The Opus encoder of a WebM output (stereo, the module's bitrate and application).- pub(crate) fn opus_encoder(job: &Job) -> effectcraft_opusenc::OpusEncoder {++/// The Opus encoder of a WebM output: the module's channel count, bitrate and application.++pub(crate) fn opus_encoder(job: &Cx) -> effectcraft_opusenc::OpusEncoder {+ // TEMP(M13.4): application mapping lands with the SILK encoder.- effectcraft_opusenc::OpusEncoder::new(2, job.output.opus_bitrate_kbps.clamp(6, 510) * 1000)++ let channels = if job.output.audio_channels == 1 { 1 } else { 2 };++ effectcraft_opusenc::OpusEncoder::new(channels, job.output.opus_bitrate_kbps.clamp(6, 510) * 1000)+}+- pub(crate) fn webm(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {+ pub(crate) fn webm(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {+ if job.output.webm_codec == effectcraft_project::render_queue::WebmVideoCodec::Av1 {+ return crate::webm_av1::webm_av1(job, comp, w, h, st);+ }let rate = job.settings.rate(comp);let alpha = job.output.channels == Channels::Rgba;+ let colour_channels = if job.output.channels == Channels::Alpha { Channels::Alpha } else { Channels::Rgb };let quality = job.output.quality.clamp(1, 100);- let cfg = effectcraft_vp9enc::EncoderConfig { width: w, height: h, quality, full_range: false };+ let fps = rate.as_f64().max(1.0);+ let cfg = effectcraft_vp9enc::EncoderConfig {+ width: w,+ height: h,+ quality,+ full_range: false,+ keyframe_interval: if job.output.keyframe_interval > 0 { job.output.keyframe_interval } else { (fps * 2.0).round().max(1.0) as u32 },+ target_kbps: job.output.webm_bitrate.then_some(job.output.bitrate_kbps.max(50)),+ frame_rate: fps,+ loop_filter: true,+ };+ let mut color_enc = effectcraft_vp9enc::Vp9Encoder::new(cfg.clone());+ let mut alpha_enc = alpha.then(|| effectcraft_vp9enc::Vp9Encoder::new(cfg.clone()));let with_audio = wants_audio(job);+ let opus_channels = if job.output.audio_channels == 1 { 1usize } else { 2 };- let mut opus = with_audio.then(|| effectcraft_opusenc::OpusEncoder::new(opus_channels as _, OPUS_BITRATE));+ let mut opus = with_audio.then(|| opus_encoder(job));let total = st.total;let frame_ms = |k: u64| -> i64 { ((k as i128 * 1000 * rate.den as i128 + rate.num as i128 / 2) / rate.num as i128) as i64 };let duration_ms = frame_ms(total) as f64;diff --cc crates/export/src/webm_av1.rsindex 5c9653251,000000000..69378e4ffmode 100644,000000..100644--- a/crates/export/src/webm_av1.rs+++ b/crates/export/src/webm_av1.rs@@@ -1,172 -1,0 +1,177 @@@+//! WebM with AV1 video (`V_AV1`, CodecPrivate = the `av1C` record, per the AV1-in-Matroska+//! codec mapping) and Opus audio. Frames are rendered in parallel batches and encoded in order+//! (AV1 inter frames reference the previous frame); each batch becomes one Cluster whose+//! SimpleBlocks carry the key-frame flag only on AV1 key frames (the Cues-less layout of the+//! VP9 writer: players seek by scanning clusters).++use std::io::{Seek, SeekFrom, Write};++use effectcraft_project::Comp;+use effectcraft_project::render_queue::Channels;+use effectcraft_time::{TICKS_PER_SECOND, Tick};+use rayon::prelude::*;++use crate::encode::VideoEncoder;++use crate::encode::mix;+use crate::webm::{CLUSTER, EBML, INFO, OPUS_RATE, SEGMENT, TRACK_ENTRY, TRACKS, el, el_float, el_str, el_uint, id_bytes, opus_encoder, vint};- use crate::{Job, Report, Result, State, batch_size, io, render_frame, rgba8, wants_audio};++use crate::{Cx, Report, Result, State, batch_size, io, wants_audio};++struct Block {+ ms: i64,+ track: u64,+ key: bool,+ data: Vec<u8>,+}++fn cluster(blocks: &mut [Block]) -> Vec<u8> {+ blocks.sort_by_key(|b| (b.ms, b.track));+ let base = blocks.first().map_or(0, |b| b.ms);+ let mut body = vec![];+ el_uint(&mut body, 0xE7, base.max(0) as u64);+ for b in blocks.iter() {+ let rel = (b.ms - base).clamp(i16::MIN as i64, i16::MAX as i64) as i16;+ let mut p = vint(b.track);+ p.extend_from_slice(&rel.to_be_bytes());+ p.push(if b.key { 0x80 } else { 0x00 });+ p.extend_from_slice(&b.data);+ el(&mut body, 0xA3, &p);+ }+ let mut out = vec![];+ el(&mut out, CLUSTER, &body);+ out+}+- pub(crate) fn webm_av1(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {++pub(crate) fn webm_av1(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {+ let rate = job.settings.rate(comp);+ let mut venc = crate::hevc_av1::Av1::new(w, h, rate, job.output)?;+ let with_audio = wants_audio(job);++ let opus_channels = if job.output.audio_channels == 1 { 1usize } else { 2 };+ let mut opus = with_audio.then(|| opus_encoder(job));+ let total = st.total;+ let frame_ms = |k: u64| -> i64 { ((k as i128 * 1000 * rate.den as i128 + rate.num as i128 / 2) / rate.num as i128) as i64 };+ let duration_ms = frame_ms(total) as f64;+- let mut file = crate::out::create(job.sink, job.path)?;++ let path = job.place(job.path, 1);++ let mut file = crate::out::create(job.sink, &path)?;+ let mut head = vec![];+ let mut eb = vec![];+ el_uint(&mut eb, 0x4286, 1);+ el_uint(&mut eb, 0x42F7, 1);+ el_uint(&mut eb, 0x42F2, 4);+ el_uint(&mut eb, 0x42F3, 8);+ el_str(&mut eb, 0x4282, "webm");+ el_uint(&mut eb, 0x4287, 4);+ el_uint(&mut eb, 0x4285, 2);+ el(&mut head, EBML, &eb);+ head.extend(id_bytes(SEGMENT));+ let size_pos = head.len() as u64;+ head.extend_from_slice(&[0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);+ let seg_start = head.len() as u64;+ let mut info = vec![];+ el_uint(&mut info, 0x2AD7B1, 1_000_000);+ el_float(&mut info, 0x4489, duration_ms);+ el_str(&mut info, 0x4D80, "EffectCraft");+ el_str(&mut info, 0x5741, "EffectCraft");+ el(&mut head, INFO, &info);+ let mut tracks = vec![];+ let mut v = vec![];+ el_uint(&mut v, 0xD7, 1);+ el_uint(&mut v, 0x73C5, 1);+ el_uint(&mut v, 0x83, 1);+ el_uint(&mut v, 0x9C, 0);+ el_str(&mut v, 0x86, "V_AV1");+ el(&mut v, 0x63A2, &venc.av1c());+ el_uint(&mut v, 0x23E383, (1_000_000_000u128 * rate.den as u128 / rate.num.max(1) as u128) as u64);+ let mut video = vec![];+ el_uint(&mut video, 0xB0, w as u64);+ el_uint(&mut video, 0xBA, h as u64);+ el(&mut v, 0xE0, &video);+ el(&mut tracks, TRACK_ENTRY, &v);+ if let Some(o) = &opus {+ let mut a = vec![];+ el_uint(&mut a, 0xD7, 2);+ el_uint(&mut a, 0x73C5, 2);+ el_uint(&mut a, 0x83, 2);+ el_uint(&mut a, 0x9C, 0);+ el_str(&mut a, 0x86, "A_OPUS");+ el(&mut a, 0x63A2, &o.opus_head());+ el_uint(&mut a, 0x56AA, o.pre_skip() as u64 * 1_000_000_000 / OPUS_RATE as u64);+ el_uint(&mut a, 0x56BB, 80_000_000);+ let mut au = vec![];+ el_float(&mut au, 0xB5, OPUS_RATE as f64);- el_uint(&mut au, 0x9F, 2);++ el_uint(&mut au, 0x9F, opus_channels as u64);+ el(&mut a, 0xE1, &au);+ el(&mut tracks, TRACK_ENTRY, &a);+ }+ el(&mut head, TRACKS, &tracks);+ file.write_all(&head).map_err(io)?;+ let mut seg_len = head.len() as u64 - seg_start;++ let (span_start, span_end) = job.settings.span(comp);+ let mut cursor = span_start.to_units_floor(OPUS_RATE as i64);+ let mut pcm_left: Vec<f32> = vec![];+ let mut packets = 0u64;+ let mut audio_until = |until: Tick, blocks: &mut Vec<Block>, finish: bool| {+ let Some(enc) = opus.as_mut() else { return };+ let end = until.to_units_floor(OPUS_RATE as i64);+ if end > cursor {+ let n = (end - cursor) as usize;+ let start = Tick(((cursor as i128 * TICKS_PER_SECOND as i128) / OPUS_RATE as i128) as i64);- pcm_left.extend(effectcraft_render::audio::mix_comp(job.project, job.footage, job.expr, job.comp, start, n, OPUS_RATE));++ pcm_left.extend(mix(job, start, n, OPUS_RATE));+ cursor = end;+ }- let fs = effectcraft_opusenc::OpusEncoder::FRAME_SIZE * 2;++ let fs = effectcraft_opusenc::OpusEncoder::FRAME_SIZE * opus_channels;+ if finish && !pcm_left.is_empty() {+ let pad = (fs - pcm_left.len() % fs) % fs + fs;+ pcm_left.extend(std::iter::repeat_n(0.0, pad));+ }+ while pcm_left.len() >= fs {+ let pkt = enc.encode_float(&pcm_left[..fs]);+ pcm_left.drain(..fs);+ blocks.push(Block { ms: packets as i64 * 20, track: 2, key: true, data: pkt });+ packets += 1;+ }+ };++ let batch = batch_size();+ let mut i = 0;+ let flush_blocks = |blocks: &mut Vec<Block>, file: &mut crate::out::Out, seg_len: &mut u64| -> Result<()> {+ if !blocks.is_empty() {+ let c = cluster(blocks);+ file.write_all(&c).map_err(io)?;+ *seg_len += c.len() as u64;+ blocks.clear();+ }+ Ok(())+ };+ let mut blocks = vec![];+ while i < total {+ let end = (i + batch).min(total);- let frames: Vec<Vec<u8>> = (i..end).into_par_iter().map(|k| rgba8(&render_frame(job, comp, k), comp, Channels::Rgb, w, h)).collect();++ // RGB, or the alpha matte alone (Channels: Alpha); AV1 in WebM carries no alpha track.++ let channels = if job.output.channels == Channels::Alpha { Channels::Alpha } else { Channels::Rgb };++ let frames: Vec<Vec<u8>> = (i..end).into_par_iter().map(|k| job.pixels(&job.frame(comp, k), comp, channels, w, h)).collect();+ for (j, px) in frames.iter().enumerate() {+ let k = i + j as u64;+ for p in venc.encode(px, k)? {+ blocks.push(Block { ms: frame_ms(k), track: 1, key: p.key, data: p.data });+ }+ }+ let t_end = if end >= total { span_end } else { job.settings.frame_time(comp, end) };+ audio_until(t_end, &mut blocks, end >= total);+ flush_blocks(&mut blocks, &mut file, &mut seg_len)?;+ st.advance(end - i)?;+ i = end;+ }+ if total == 0 {+ audio_until(span_end, &mut blocks, true);+ flush_blocks(&mut blocks, &mut file, &mut seg_len)?;+ }+ let mut size = [0u8; 8];+ size[0] = 0x01;+ size[1..].copy_from_slice(&seg_len.to_be_bytes()[1..]);+ file.seek(SeekFrom::Start(size_pos)).map_err(io)?;+ file.write_all(&size).map_err(io)?;+ file.seek(SeekFrom::End(0)).map_err(io)?;+ let bytes = file.finish()?;- Ok(Report { path: job.path.to_string(), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio })++ Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![] })+}diff --cc crates/export/tests/hevc_av1_roundtrip.rsindex d3ae02289,000000000..c56616742mode 100644,000000..100644--- a/crates/export/tests/hevc_av1_roundtrip.rs+++ b/crates/export/tests/hevc_av1_roundtrip.rs@@@ -1,271 -1,0 +1,283 @@@+//! HEVC (MP4 `hvc1`) and AV1 (MP4 `av01`, WebM `V_AV1`) export, decoded back through+//! EffectCraft's own import path (FilmCraft's demuxers and HEVC / AV1 decoders) and — when+//! installed — ffprobe / ffmpeg as external oracles (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 (inter frames code both static and changing blocks).++use std::path::{Path, PathBuf};+use std::process::Command;++use effectcraft_color::Label;+use effectcraft_export::render_queue::{AudioOutput, CodecProfile, OutputFormat, OutputModule, RateControlMode, RenderSettings, TimeSpan, WebmVideoCodec};+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-hevc-av1").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 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;+ true+ })+ .expect("export");+ assert_eq!((last.done, r.frames), (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)+}++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:?}");+}++/// Import our file through the media layer and check every frame.+fn decode_movie(path: &Path, 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 have(tool: &str) -> bool {+ Command::new(tool).arg("-version").output().map(|o| o.status.success()).unwrap_or(false)+}++/// `codec|w|h|pix_fmt|frames` of the video stream, or `None` without ffprobe.+fn ffprobe_video(path: &Path) -> Option<String> {+ if !have("ffprobe") {+ eprintln!("ffprobe not found: skipping the oracle");+ return None;+ }+ let out = Command::new("ffprobe")+ .args(["-v", "error", "-select_streams", "v:0", "-count_frames", "-show_entries", "stream=codec_name,width,height,pix_fmt,nb_read_frames"])+ .args(["-of", "compact=p=0:nk=1"])+ .arg(path)+ .output()+ .expect("ffprobe");+ assert!(out.status.success() && out.stderr.is_empty(), "ffprobe rejected {}: {}", path.display(), String::from_utf8_lossy(&out.stderr));+ Some(String::from_utf8_lossy(&out.stdout).trim().to_string())+}++/// Decode every frame with ffmpeg (no errors allowed) and check frames 0, 4, 5 and the last.+fn ffmpeg_check(path: &Path, decoder: Option<&str>, tol: f32) {+ if !have("ffmpeg") {+ eprintln!("ffmpeg not found: skipping the oracle decode");+ return;+ }+ let dir = path.with_extension("ffmpeg");+ let _ = std::fs::create_dir_all(&dir);+ let mut cmd = Command::new("ffmpeg");+ cmd.args(["-hide_banner", "-loglevel", "error", "-xerror", "-y"]);+ if let Some(d) = decoder {+ cmd.args(["-c:v", d]);+ }+ let out = cmd.arg("-i").arg(path).args(["-pix_fmt", "rgba"]).arg(dir.join("f%03d.png")).output().expect("ffmpeg");+ assert!(out.status.success() && out.stderr.is_empty(), "ffmpeg ({decoder:?}) failed on {}: {}", path.display(), String::from_utf8_lossy(&out.stderr));+ for k in [0, 4, 5, FRAMES - 1] {+ let img = image::open(dir.join(format!("f{:03}.png", k + 1))).expect("ffmpeg frame").to_rgba8();+ check_frame(&Image::from_rgba8(img.width(), img.height(), img.as_raw()), k, tol);+ }+}++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;+ om+}++/// Key-frame flags of the MP4 video samples (via ffprobe), or `None` without it.+fn ffprobe_keyframes(path: &Path) -> Option<Vec<bool>> {+ if !have("ffprobe") {+ return None;+ }+ let out = Command::new("ffprobe")+ .args(["-v", "error", "-select_streams", "v:0", "-show_entries", "packet=flags", "-of", "csv=p=0"])+ .arg(path)+ .output()+ .expect("ffprobe");+ Some(String::from_utf8_lossy(&out.stdout).lines().map(|l| l.starts_with('K')).collect())+}++#[test]+fn hevc_mp4_roundtrip() {+ let d = out_dir("hevc");+ let (p, cid) = project(None);+ let om = module(OutputFormat::Hevc, 4);+ let path = d.join("comp.mp4");+ let r = run(&p, cid, &NoFootage, &om, &path);+ assert!(r.bytes > 100 && !r.audio);+ let bytes = std::fs::read(&path).unwrap();+ assert!(bytes.windows(4).any(|w| w == b"hvc1") && bytes.windows(4).any(|w| w == b"hvcC"));+ decode_movie(&path, 0.08);+ if let Some(s) = ffprobe_video(&path) {+ assert_eq!(s, "hevc|64|48|yuv420p|12");+ }+ if let Some(k) = ffprobe_keyframes(&path) {+ assert_eq!(k, (0..FRAMES).map(|i| i % 4 == 0).collect::<Vec<_>>(), "IDR every 4 frames");+ }+ ffmpeg_check(&path, None, 0.08);+}++#[test]+fn hevc_main10_bitrate_mode() {+ let d = out_dir("hevc10");+ let (p, cid) = project(None);+ let mut om = module(OutputFormat::Hevc, 0);+ om.codec.profile = CodecProfile::Main10;+ om.codec.rate_control = RateControlMode::Bitrate;+ om.bitrate_kbps = 2_000;+ om.codec.level = Some(31);+ let path = d.join("comp10.mp4");+ run(&p, cid, &NoFootage, &om, &path);+ decode_movie(&path, 0.08);+ if let Some(s) = ffprobe_video(&path) {+ assert_eq!(s, "hevc|64|48|yuv420p10le|12");+ }+ ffmpeg_check(&path, None, 0.08);+}++#[test]+fn av1_mp4_roundtrip() {+ let d = out_dir("av1");+ let (p, cid) = project(None);+ let om = module(OutputFormat::Av1, 6);+ let path = d.join("comp.mp4");+ run(&p, cid, &NoFootage, &om, &path);+ let bytes = std::fs::read(&path).unwrap();+ assert!(bytes.windows(4).any(|w| w == b"av01") && bytes.windows(4).any(|w| w == b"av1C"));+ decode_movie(&path, 0.08);+ if let Some(s) = ffprobe_video(&path) {+ assert_eq!(s, "av1|64|48|yuv420p|12");+ }+ if let Some(k) = ffprobe_keyframes(&path) {+ assert_eq!(k, (0..FRAMES).map(|i| i % 6 == 0).collect::<Vec<_>>(), "key frame every 6 frames");+ }+ ffmpeg_check(&path, Some("libdav1d"), 0.08);+}++#[test]+fn av1_webm_with_opus() {+ let d = out_dir("av1-webm");+ let wav = d.join("tone.wav");+ write_tone(&wav, 2.0);+ let (p, cid) = project(Some(&wav));+ let pool = MediaPool::new();+ let mut om = module(OutputFormat::WebM, 0);+ om.webm_codec = WebmVideoCodec::Av1;+ om.codec.profile = CodecProfile::Main10;+ om.audio = AudioOutput::Auto;+ om.opus_bitrate_kbps = 96;+ let path = d.join("comp.webm");+ let r = run(&p, cid, &pool, &om, &path);+ assert!(r.audio);+ let f = decode_movie(&path, 0.08);+ assert!(f.has_audio);+ let s = MediaPool::new().audio_samples(&f, Tick::from_seconds_f64(0.3), 24_000, 48_000);+ let l = rms(s.iter().step_by(2).copied());+ assert!((l - 0.3536).abs() < 0.06, "left RMS {l}");+ if let Some(s) = ffprobe_video(&path) {+ assert_eq!(s, "av1|64|48|yuv420p10le|12");+ }+ ffmpeg_check(&path, Some("libdav1d"), 0.08);+}++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+}++/// 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");+}diff --cc crates/project/src/render_queue.rsindex 5e9f29496,35aed0bed..c3a5503e6--- a/crates/project/src/render_queue.rs+++ b/crates/project/src/render_queue.rs@@@ -354,184 -800,39 +816,195 @@@ impl ProResProfile}}+/// HEVC / AV1 profile: 8-bit (HEVC Main, AV1 Main 8-bit) or 10-bit (HEVC Main 10, AV1 Main 10-bit).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum CodecProfile {+ #[default]+ Main,+ Main10,+}++impl CodecProfile {+ pub const ALL: [CodecProfile; 2] = [CodecProfile::Main, CodecProfile::Main10];+ pub fn label(self) -> &'static str {+ match self {+ CodecProfile::Main => "Main",+ CodecProfile::Main10 => "Main 10",+ }+ }+ pub fn bit_depth(self) -> u8 {+ match self {+ CodecProfile::Main => 8,+ CodecProfile::Main10 => 10,+ }+ }+ pub fn from_name(s: &str) -> Option<CodecProfile> {+ match s.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() {+ "main" | "main8" | "8" | "8bit" => Some(CodecProfile::Main),+ "main10" | "10" | "10bit" => Some(CodecProfile::Main10),+ _ => None,+ }+ }+}++/// HEVC / AV1 rate control: a target bitrate ([`OutputModule::bitrate_kbps`]) or constant+/// quality ([`VideoCodecOptions::quality`], CRF-like).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum RateControlMode {+ #[default]+ Bitrate,+ Quality,+}++impl RateControlMode {+ pub fn label(self) -> &'static str {+ match self {+ RateControlMode::Bitrate => "Target Bitrate",+ RateControlMode::Quality => "Constant Quality",+ }+ }+ pub fn from_name(s: &str) -> Option<RateControlMode> {+ match s.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() {+ "bitrate" | "vbr" | "abr" | "targetbitrate" => Some(RateControlMode::Bitrate),+ "quality" | "crf" | "cq" | "constantquality" | "qp" => Some(RateControlMode::Quality),+ _ => None,+ }+ }+}++/// Video codec options of the HEVC and AV1 formats (and AV1 in WebM).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(default)]+pub struct VideoCodecOptions {+ pub profile: CodecProfile,+ /// Level × 10 (`41` = level 4.1); `None` picks the lowest level that fits the frame size and rate.+ pub level: Option<u8>,+ pub rate_control: RateControlMode,+ /// Constant-quality setting 1–100 (100 ≈ visually lossless), used with [`RateControlMode::Quality`].+ pub quality: u8,- /// Frames between key frames; 0 = automatic (about 2 seconds).- pub keyframe_interval: u32,+}++impl Default for VideoCodecOptions {+ fn default() -> Self {- VideoCodecOptions { profile: CodecProfile::Main, level: None, rate_control: RateControlMode::Bitrate, quality: 70, keyframe_interval: 0 }++ VideoCodecOptions { profile: CodecProfile::Main, level: None, rate_control: RateControlMode::Bitrate, quality: 70 }+ }+}++impl VideoCodecOptions {+ /// HEVC levels (× 10) offered in the UI (Main tier).+ pub const HEVC_LEVELS: [u8; 13] = [10, 20, 21, 30, 31, 40, 41, 50, 51, 52, 60, 61, 62];+ /// AV1 levels (× 10) offered in the UI.+ pub const AV1_LEVELS: [u8; 14] = [20, 21, 30, 31, 40, 41, 50, 51, 52, 53, 60, 61, 62, 63];- /// The key-frame interval in frames at `fps` (automatic: 2 s).- pub fn keyint(&self, fps: f64) -> u32 {- if self.keyframe_interval > 0 { self.keyframe_interval } else { (fps * 2.0).round().max(1.0) as u32 }- }+ /// HEVC QP (0–51) for the constant-quality setting.+ pub fn hevc_qp(&self) -> u8 {+ (4.0 + (100 - self.quality.clamp(1, 100)) as f64 * 0.45).round() as u8+ }+ /// AV1 `base_q_idx` (1–255) for the constant-quality setting.+ pub fn av1_qindex(&self) -> u8 {+ (4.0 + (100 - self.quality.clamp(1, 100)) as f64 * 2.4).round() as u8+ }+ /// `general_level_idc` (30 × level).+ pub fn hevc_level_idc(&self) -> Option<u8> {+ self.level.map(|l| l.saturating_mul(3))+ }+ /// AV1 `seq_level_idx`: (major − 2) × 4 + minor.+ pub fn av1_level_idx(&self) -> Option<u8> {+ self.level.map(|l| ((l / 10).clamp(2, 7) - 2) * 4 + (l % 10).min(3))+ }+ pub fn level_label(&self) -> String {+ match self.level {+ None => "Auto".into(),+ Some(l) => format!("{}.{}", l / 10, l % 10),+ }+ }+ /// Parse `"auto"`, `"4.1"`, `"41"` (level × 10). `None` when unparsable; `Some(None)` = auto.+ pub fn parse_level(s: &str) -> Option<Option<u8>> {+ let s = s.trim().to_ascii_lowercase();+ if s == "auto" || s.is_empty() {+ return Some(None);+ }+ let v: f64 = s.trim_start_matches('l').parse().ok()?;+ let l = if v >= 10.0 { v.round() } else { (v * 10.0).round() };+ (10.0..=73.0).contains(&l).then_some(Some(l as u8))+ }+}++/// The video codec of a WebM output.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum WebmVideoCodec {+ #[default]+ Vp9,+ /// AV1 (`V_AV1`) with the [`OutputModule::codec`] options; no alpha.+ Av1,+}++impl WebmVideoCodec {+ pub fn label(self) -> &'static str {+ match self {+ WebmVideoCodec::Vp9 => "VP9",+ WebmVideoCodec::Av1 => "AV1",+ }+ }+}++/// Opus coding application: general audio (music and mixed content) or voice (speech-tuned+/// SILK / hybrid coding at low bitrates).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum OpusApplication {+ #[default]+ Audio,+ Voip,+}++impl OpusApplication {+ pub fn label(self) -> &'static str {+ match self {+ OpusApplication::Audio => "Audio",+ OpusApplication::Voip => "Voice",+ }+ }+}+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]#[serde(default)]pub struct OutputModule {+ /// The template this module came from ("" or "Custom" once edited).+ #[serde(skip_serializing_if = "String::is_empty")]+ pub name: String,pub format: OutputFormat,pub channels: Channels,+ /// Color: straight or premultiplied RGB with alpha.+ pub alpha_mode: AlphaMode,/// Output path or template (see the module docs).pub output: String,- /// JPEG quality 1–100.+ /// JPEG / WebM quality 1–100.pub quality: u8,- /// H.264 target bitrate (also HEVC / AV1 with [`RateControlMode::Bitrate`]).- /// H.264 target bitrate (and WebM's when `webm_bitrate`).++ /// H.264 target bitrate (and WebM's when `webm_bitrate`; HEVC / AV1 with [`RateControlMode::Bitrate`]).pub bitrate_kbps: u32,+ /// WebM: rate control by `bitrate_kbps` instead of `quality`.+ pub webm_bitrate: bool,+ /// Movies: frames between key frames (0 = automatic, two seconds).+ pub keyframe_interval: u32,pub prores_profile: ProResProfile,+ pub crop: Crop,+ pub resize: Resize,pub audio: AudioOutput,pub audio_sample_rate: u32,+ /// 1 (mono) or 2 (stereo).+ pub audio_channels: u8,+ pub audio_format: AudioFormat,/// GIF: loop forever.pub gif_loop: bool,+ /// HEVC / AV1 options.+ pub codec: VideoCodecOptions,+ /// WebM video codec.+ pub webm_codec: WebmVideoCodec,+ /// WebM Opus audio bitrate (stereo total), kbit/s.+ pub opus_bitrate_kbps: u32,+ pub opus_application: OpusApplication,+ /// Include Project Link: kept for parity; EffectCraft's writers have no place to store a+ /// link back to the project, so it changes nothing in the file.+ pub include_project_link: bool,}impl Default for OutputModule {@@@ -542,14 -845,17 +1017,21 @@@output: DEFAULT_TEMPLATE.into(),quality: 90,bitrate_kbps: 10_000,+ webm_bitrate: false,+ keyframe_interval: 0,prores_profile: ProResProfile::Hq,+ crop: Crop::default(),+ resize: Resize::default(),audio: AudioOutput::Auto,audio_sample_rate: 48_000,+ audio_channels: 2,+ audio_format: AudioFormat::S16,gif_loop: true,+ codec: VideoCodecOptions::default(),+ webm_codec: WebmVideoCodec::Vp9,+ opus_bitrate_kbps: 192,+ opus_application: OpusApplication::Audio,+ include_project_link: true,}}}@@@ -566,7 -941,7 +1117,7 @@@ impl OutputModulepub fn set_format(&mut self, format: OutputFormat) {let old = self.format;self.format = format;- if !self.supports_alpha() {- if !format.supports_alpha() && self.channels == Channels::Rgba {++ if !self.supports_alpha() && self.channels == Channels::Rgba {self.channels = Channels::Rgb;}if self.output.contains("[fileExtension]") {@@@ -586,26 -961,12 +1137,30 @@@}self.output = format!("{stem}.{}", format.extension());}+ /// Whether this module can write alpha (the format can, and WebM uses VP9).+ pub fn supports_alpha(&self) -> bool {+ self.format.supports_alpha() && !(self.format == OutputFormat::WebM && self.webm_codec == WebmVideoCodec::Av1)+ }++ /// The key-frame interval in frames at `fps` ([`OutputModule::keyframe_interval`]; automatic: 2 s).++ pub fn keyint(&self, fps: f64) -> u32 {++ if self.keyframe_interval > 0 { self.keyframe_interval } else { (fps * 2.0).round().max(1.0) as u32 }++ }+ /// Codec options summary: `Main · 10000 kbps · Level Auto · Key every auto`.+ fn codec_summary(&self) -> String {+ let c = &self.codec;+ let rate = match c.rate_control {+ RateControlMode::Bitrate => format!("{} kbps", self.bitrate_kbps),+ RateControlMode::Quality => format!("Quality {}", c.quality),+ };- let gop = if c.keyframe_interval == 0 { "auto".to_string() } else { c.keyframe_interval.to_string() };++ let gop = if self.keyframe_interval == 0 { "auto".to_string() } else { self.keyframe_interval.to_string() };+ format!("{} · {rate} · Level {} · Key every {gop}", c.profile.label(), c.level_label())+ }/// One-line summary shown next to "Output Module:".pub fn summary(&self) -> String {- let ch = match self.channels {- Channels::Rgb => "RGB",- Channels::Rgba => "RGB + Alpha",- };+ if !self.name.is_empty() {+ return self.name.clone();+ }+ let ch = self.channels.label();match self.format {OutputFormat::H264 => format!("H.264 · {} kbps", self.bitrate_kbps),OutputFormat::ProRes => format!(@@@ -832,41 -1353,4 +1551,42 @@@ mod testsassert_eq!(s.first_frame(&c), 30);assert!(s.frame_time(&c, 0) >= Tick::from_seconds_f64(1.0));}++ #[test]+ fn hevc_av1_codec_options() {+ assert_eq!(OutputFormat::from_name("H.265"), Some(OutputFormat::Hevc));+ assert_eq!(OutputFormat::from_name("hevc"), Some(OutputFormat::Hevc));+ assert_eq!(OutputFormat::from_name("AV1"), Some(OutputFormat::Av1));+ assert_eq!(OutputFormat::Hevc.coded_size(33, 17), (32, 16));+ assert_eq!(OutputFormat::Av1.coded_size(33, 17), (33, 17));+ assert!(!OutputFormat::Hevc.supports_alpha() && OutputFormat::Av1.is_movie() && OutputFormat::Av1.supports_audio());+ assert_eq!(VideoCodecOptions::parse_level("4.1"), Some(Some(41)));+ assert_eq!(VideoCodecOptions::parse_level("51"), Some(Some(51)));+ assert_eq!(VideoCodecOptions::parse_level("auto"), Some(None));+ assert_eq!(VideoCodecOptions::parse_level("9"), None);+ let mut o = VideoCodecOptions { level: Some(41), ..Default::default() };+ assert_eq!((o.hevc_level_idc(), o.av1_level_idx()), (Some(123), Some(9)));+ o.level = Some(20);+ assert_eq!(o.av1_level_idx(), Some(0));+ o.quality = 100;+ assert_eq!((o.hevc_qp(), o.av1_qindex()), (4, 4));+ o.quality = 1;+ assert!(o.hevc_qp() <= 51 && o.av1_qindex() >= 240);- assert_eq!(o.keyint(29.97), 60);- o.keyframe_interval = 1;- assert_eq!(o.keyint(29.97), 1);+ // WebM with AV1 has no alpha; switching drops RGB + Alpha.+ let mut m = OutputModule::for_format(OutputFormat::WebM);+ m.channels = Channels::Rgba;+ assert!(m.supports_alpha());+ m.webm_codec = WebmVideoCodec::Av1;+ assert!(!m.supports_alpha());+ assert!(m.summary().starts_with("WebM (AV1 + Opus 192 kbps)"), "{}", m.summary());- let h = OutputModule::for_format(OutputFormat::Hevc);++ let mut h = OutputModule::for_format(OutputFormat::Hevc);++ assert_eq!(h.keyint(29.97), 60);++ h.keyframe_interval = 1;++ assert_eq!(h.keyint(29.97), 1);++ h.keyframe_interval = 0;+ assert_eq!(h.summary(), "HEVC (H.265) · Main · 10000 kbps · Level Auto · Key every auto");+ // Older projects (no codec fields) load with the defaults.+ let old: OutputModule = serde_json::from_str(r#"{"format":"H264","bitrate_kbps":5000}"#).unwrap();+ assert_eq!((old.codec, old.webm_codec, old.opus_bitrate_kbps), (VideoCodecOptions::default(), WebmVideoCodec::Vp9, 192));+ }}diff --cc crates/ui-egui/src/panels/render_queue.rsindex 013b8ff86,ec0853a1b..cf6c0c710--- a/crates/ui-egui/src/panels/render_queue.rs+++ b/crates/ui-egui/src/panels/render_queue.rs@@@ -4,12 -4,18 +4,18 @@@//! Output Module and Output To rows, and a status footer.//!//! Every control dispatches an engine `renderQueue.*` command (so agents can do the same) and- //! registers an automation id: `renderQueue.render`, `renderQueue.stop`,- //! `renderQueue.item.<n>.{row,twirl,render,renderSettings,outputModule,outputTo,outputPath}`.+ //! registers an automation id: `renderQueue.render`, `renderQueue.stop`, `renderQueue.notify`,+ //! `renderQueue.item.<n>.{row,twirl,render,renderSettings,outputModule,outputTo,outputPath,log}`.+ //!+ //! The Render Settings and Output Module menus list the templates first (Edit ▸ Templates), then+ //! every setting; entries needing numbers (custom time span and frame rate, crop, resize, bitrate,+ //! key frame interval, Make Template) open a form that runs the same command.use effectcraft_engine::project::render_queue::{- AudioOutput, Channels, OpusApplication, OutputFormat, ProResProfile, RenderQuality, RenderQueueItem, RenderStatus, TimeSpan, WebmVideoCodec,- AlphaMode, AudioFormat, AudioOutput, Channels, ColorDepth, CurrentOrOff, EffectsMode, FieldRender, OutputFormat, PostRenderAction, ProResProfile, Pulldown,- RESIZE_PRESETS, RenderLog, RenderQuality, RenderQueueItem, RenderStatus, ResizeQuality, SwitchOverride, TimeSpan,++ AlphaMode, AudioFormat, AudioOutput, Channels, ColorDepth, CurrentOrOff, EffectsMode, FieldRender, OpusApplication, OutputFormat, PostRenderAction,++ ProResProfile, Pulldown, RESIZE_PRESETS, RenderLog, RenderQuality, RenderQueueItem, RenderStatus, ResizeQuality, SwitchOverride, TimeSpan, WebmVideoCodec,};+ use effectcraft_engine::project::render_templates::RenderTemplates;use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};use serde_json::{Value, json};@@@ -98,9 -144,16 +144,16 @@@ fn output_menu(it: &RenderQueueItem, av}v.push(("-".into(), Value::Null));v.push((mark(o.channels == Channels::Rgb, "Channels: RGB"), json!({"channels": "rgb"})));- if o.format.supports_alpha() {+ if o.supports_alpha() {v.push((mark(o.channels == Channels::Rgba, "Channels: RGB + Alpha"), json!({"channels": "rgba"})));}+ if !o.format.is_audio_only() {+ v.push((mark(o.channels == Channels::Alpha, "Channels: Alpha"), json!({"channels": "alpha"})));+ }+ if o.channels == Channels::Rgba {+ v.push((mark(o.alpha_mode == AlphaMode::Straight, "Color: Straight (Unmatted)"), json!({"color": "straight"})));+ v.push((mark(o.alpha_mode == AlphaMode::Premultiplied, "Color: Premultiplied (Matted)"), json!({"color": "premultiplied"})));+ }match o.format {OutputFormat::ProRes => {v.push(("-".into(), Value::Null));@@@ -114,33 -167,15 +167,35 @@@v.push((mark(o.bitrate_kbps == kbps, &format!("Bitrate: {} Mbps", kbps / 1000)), json!({"bitrate": kbps})));}}- OutputFormat::JpegSequence | OutputFormat::WebM => {+ OutputFormat::Hevc | OutputFormat::Av1 => codec_menu(o, &mut v),+ OutputFormat::WebM => {v.push(("-".into(), Value::Null));- for q in [60u8, 80, 90, 100] {- v.push((mark(o.quality == q && !o.webm_bitrate, &format!("Quality: {q}")), json!({"quality": q, "webmBitrate": false})));+ for c in [WebmVideoCodec::Vp9, WebmVideoCodec::Av1] {+ v.push((mark(o.webm_codec == c, &format!("Video Codec: {}", c.label())), json!({"webmCodec": c.label().to_ascii_lowercase()})));}- if o.format == OutputFormat::WebM {+ if o.webm_codec == WebmVideoCodec::Av1 {+ codec_menu(o, &mut v);+ } else {+ v.push(("-".into(), Value::Null));+ for q in [60u8, 80, 90, 100] {- v.push((mark(o.quality == q, &format!("Quality: {q}")), json!({"quality": q})));++ v.push((mark(o.quality == q && !o.webm_bitrate, &format!("Quality: {q}")), json!({"quality": q, "webmBitrate": false})));+ }+ v.push((mark(o.webm_bitrate, &format!("Target Bitrate ({} kbps)…", o.bitrate_kbps)), json!({"form": "bitrate"})));+ v.push((mark(o.keyframe_interval > 0, "Key Frame Interval…"), json!({"form": "keyframes"})));}+ v.push(("-".into(), Value::Null));+ for kbps in [24u32, 32, 64, 96, 128, 192, 256] {+ v.push((mark(o.opus_bitrate_kbps == kbps, &format!("Opus Bitrate: {kbps} kbps")), json!({"audioBitrate": kbps})));+ }+ for (a, k) in [(OpusApplication::Audio, "audio"), (OpusApplication::Voip, "voice")] {+ v.push((mark(o.opus_application == a, &format!("Opus Tuning: {}", a.label())), json!({"opusApplication": k})));+ }+ }+ OutputFormat::JpegSequence => {+ v.push(("-".into(), Value::Null));+ for q in [60u8, 80, 90, 100] {+ v.push((mark(o.quality == q, &format!("Quality: {q}")), json!({"quality": q})));+ }}OutputFormat::Gif => {v.push(("-".into(), Value::Null));@@@ -162,45 -236,75 +256,125 @@@v}+/// HEVC / AV1 options: profile, level, rate control (bitrate or constant quality), key frames.+fn codec_menu(o: &effectcraft_engine::project::render_queue::OutputModule, v: &mut Vec<(String, Value)>) {+ use effectcraft_engine::project::render_queue::{CodecProfile, RateControlMode, VideoCodecOptions};- let mark = |on: bool, l: &str| if on { format!("✓ {l}") } else { format!(" {l}") };+ let c = &o.codec;+ v.push(("-".into(), Value::Null));+ for p in CodecProfile::ALL {+ v.push((mark(c.profile == p, &format!("Profile: {}", p.label())), json!({"profile": format!("{p:?}").to_ascii_lowercase()})));+ }+ v.push(("-".into(), Value::Null));+ v.push((mark(c.level.is_none(), "Level: Auto"), json!({"level": "auto"})));+ // The common HEVC / AV1 levels (every level is reachable over the control channel).+ for l in [30u8, 31, 40, 41, 50, 51, 52] {+ debug_assert!(VideoCodecOptions::HEVC_LEVELS.contains(&l) && VideoCodecOptions::AV1_LEVELS.contains(&l));+ let name = format!("{}.{}", l / 10, l % 10);+ v.push((mark(c.level == Some(l), &format!("Level: {name}")), json!({"level": name})));+ }+ v.push(("-".into(), Value::Null));+ for r in [RateControlMode::Bitrate, RateControlMode::Quality] {+ v.push((mark(c.rate_control == r, &format!("Rate Control: {}", r.label())), json!({"rateControl": format!("{r:?}").to_ascii_lowercase()})));+ }+ if c.rate_control == RateControlMode::Bitrate {+ for kbps in [1_000u32, 2_000, 5_000, 10_000, 20_000, 40_000] {+ let l = if kbps < 2_000 { format!("Bitrate: {kbps} kbps") } else { format!("Bitrate: {} Mbps", kbps / 1000) };+ v.push((mark(o.bitrate_kbps == kbps, &l), json!({"bitrate": kbps})));+ }++ v.push((mark(false, "Bitrate: Custom…"), json!({"form": "codecBitrate"})));+ } else {+ for q in [40u8, 60, 70, 80, 90, 100] {+ v.push((mark(c.quality == q, &format!("Quality: {q}")), json!({"quality": q})));+ }+ }+ v.push(("-".into(), Value::Null));- for k in [0u32, 1, 12, 30, 60, 120, 250] {++ for k in [0u32, 1, 30, 60, 120, 250] {+ let l = match k {+ 0 => "Key Frames: Auto (2 s)".to_string(),+ 1 => "Key Frames: Every Frame (all intra)".to_string(),+ k => format!("Key Frames: Every {k} Frames"),+ };- v.push((mark(c.keyframe_interval == k, &l), json!({"keyframeInterval": k})));++ v.push((mark(o.keyframe_interval == k, &l), json!({"keyframeInterval": k})));++ }++ v.push((mark(false, "Key Frame Interval…"), json!({"form": "keyframes"})));++}+++ /// Open the form behind a `{"form": …}` menu entry.+ fn open_menu_form(app: &mut EffectcraftApp, it: &RenderQueueItem, form: &str) {+ use crate::panels::forms::{Field, form as open};+ let id = it.id;+ let o = &it.output;+ match form {+ "makeRenderTemplate" => open(+ app,+ "Make Render Settings Template",+ "renderQueue.saveTemplate",+ json!({"kind": "renderSettings", "item": id}),+ vec![Field::text("name", "Template name", "")],+ ),+ "makeOutputTemplate" => open(+ app,+ "Make Output Module Template",+ "renderQueue.saveTemplate",+ json!({"kind": "outputModule", "item": id}),+ vec![Field::text("name", "Template name", "")],+ ),+ "timeSpan" => {+ let comp = app.session.project.comp(it.comp);+ let (a, b) = comp.map(|c| it.settings.span(c)).unwrap_or_default();+ open(+ app,+ "Custom Time Span",+ "renderQueue.setRenderSettings",+ json!({"item": id, "timeSpan": "custom"}),+ vec![Field::num("start", "Start (s)", a.seconds()), Field::num("duration", "Duration (s)", (b.seconds() - a.seconds()).max(0.04))],+ )+ }+ "frameRate" => {+ let r = app.session.project.comp(it.comp).map(|c| it.settings.rate(c).as_f64()).unwrap_or(30.0);+ open(app, "Use This Frame Rate", "renderQueue.setRenderSettings", json!({"item": id}), vec![Field::num("frameRate", "Frames per second", r)])+ }+ "crop" => open(+ app,+ "Crop",+ "renderQueue.setOutputModule",+ json!({"item": id}),+ vec![+ Field::num("cropTop", "Top", o.crop.top as f64),+ Field::num("cropLeft", "Left", o.crop.left as f64),+ Field::num("cropBottom", "Bottom", o.crop.bottom as f64),+ Field::num("cropRight", "Right", o.crop.right as f64),+ ],+ ),+ "resize" => open(+ app,+ "Resize to",+ "renderQueue.setOutputModule",+ json!({"item": id}),+ vec![Field::num("resizeWidth", "Width", o.resize.width as f64), Field::num("resizeHeight", "Height", o.resize.height as f64)],+ ),+ "bitrate" => open(+ app,+ "WebM Target Bitrate",+ "renderQueue.setOutputModule",+ json!({"item": id, "webmBitrate": true}),+ vec![Field::num("bitrate", "Bitrate (kbps)", o.bitrate_kbps as f64)],+ ),++ "codecBitrate" => open(++ app,++ "Target Bitrate",++ "renderQueue.setOutputModule",++ json!({"item": id, "rateControl": "bitrate"}),++ vec![Field::num("bitrate", "Bitrate (kbps)", o.bitrate_kbps as f64)],++ ),+ "keyframes" => open(+ app,+ "Key Frame Interval",+ "renderQueue.setOutputModule",+ json!({"item": id}),+ vec![Field::num("keyframeInterval", "Frames between key frames (0 = every 2 s)", o.keyframe_interval as f64)],+ ),+ _ => {}}}diff --cc docs/architecture.mdindex a48eb5e04,ed86d9b5f..71c9560f1--- a/docs/architecture.md+++ b/docs/architecture.md@@@ -33,12 -32,13 +34,13 @@@ cpal or muda. Everything in L0 to L4, t| L3 | `render` | Evaluation and compositing: sources, masks, effects, transforms, 3D, motion blur, mattes, blending, layer cache, audio mixdown || L3 | `media` | Footage decoding (FilmCraft's pure-Rust codecs), image sequences, Photoshop and SVG stills, frame cache || L3 | `expr` | The expression engine (JavaScript via boa) with the After Effects object model |-| L3 | `export` | Render queue encoding: H.264, ProRes, WebM (VP9 + alpha, Opus), PNG/JPEG/TIFF/EXR sequences, GIF, WAV/AIFF |+| L3 | `export` | Render queue encoding: H.264, HEVC and AV1 MP4, ProRes, WebM (VP9 + alpha or AV1, Opus), PNG/JPEG/TIFF/EXR sequences, GIF, WAV/AIFF || L3 | `gpu` | The GPU compositor and GPU effects on wgpu compute shaders (Metal, Vulkan, Direct3D 12, WebGPU), checked against the CPU renderer || L3 | `lottie` | Lottie JSON / dotLottie import and export (layers, precomps, eased and spatial keyframes, shapes, masks, mattes) with a warnings list for what Lottie cannot express |- | L4 | `engine` | `Session`: project, undo history, editor state, the command registry and menus |- | L4 | `script` | Scripting: JavaScript (boa) with an After Effects-style object model (`app.project`, comps, layers, properties, render queue) whose edits run engine commands; AE match names |- | L4 | `host` | A fully wired `Session` (media, expressions, scripting, exporter) for the frontends |+ | L3 | `plugin` | Effect plug-ins: loads sandboxed WebAssembly effect modules (plug-in API v1; the wasmi interpreter behind the `wasm` feature, on for native hosts) into the effect registry ([plugins.md](plugins.md)) |+ | L4 | `engine` | `Session`: project, branching undo history, editor state, the command registry and menus, the ScriptUI window model (`scriptui`) |+ | L4 | `script` | Scripting: JavaScript (boa) with an After Effects-style object model (`app.project`, comps, layers, properties, render queue) and ScriptUI (dialogs, palettes, dockable panels; script-host threads so dialogs block `show()`), whose edits run engine commands; AE match names |+ | L4 | `host` | A fully wired `Session` (media, expressions, scripting, WebAssembly plug-ins, exporter) for the frontends || L5 | `ui-egui` | The desktop interface: docking, panels, viewer, timeline, graph editor, dialogs, control channel || L5 | `automation` | The MCP server, headless or bridged to the running app || L6 | apps `effectcraft`, `effectcraft-cli`, `effectcraft-web` | Desktop app; command-line tool (render, exec, get/set, MCP); the browser app (wasm32, [web.md](web.md)) |