FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M10.4: caption commands in the engine (captions.* — tracks, add at playhead, split/merge/trim/move/delete, text/speaker/timing, style, next/previous, show/hide, list), file.import detects .srt/.vtt/.scc into a new caption track, File ▸ Export ▸ Captions… (SRT/VTT/SCC), Clear/Ripple Delete on selected captions; caption overlays in render + GPU frame plans; burn-in on export (ffmpeg-oracle test)
Brandon Thomas9eb12c004353
diff --git a/Cargo.lock b/Cargo.lockindex 0edf49114..dfcc51d49 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1577,6 +1577,7 @@ name = "filmcraft-render"version = "0.1.0"dependencies = ["filmcraft-audio-dsp",+ "filmcraft-captions","filmcraft-color","filmcraft-frame","filmcraft-geom",diff --git a/crates/engine/src/captions.rs b/crates/engine/src/captions.rsnew file mode 100644index 000000000..2bcb97634--- /dev/null+++ b/crates/engine/src/captions.rs@@ -0,0 +1,551 @@+//! Caption commands: caption tracks, caption editing, caption file import/export.+//!+//! Ids (`captions.*`) follow Premiere's Sequence ▸ Captions menu and the Text panel's Captions tab.+//! Captions are addressed by id (`caption`, `captions`); without one, commands use the caption+//! selection (`EditorState::caption_selection`) or the caption under the playhead. Caption tracks+//! are addressed by id or `"C1"`, `"C2"`… (top first); the default is the first caption track.++use serde_json::{Value, json};++use filmcraft_captions::{Document, Format, WriteOptions};+use filmcraft_edit as edit;+use filmcraft_edit::Edge;+use filmcraft_project::{CaptionAlign, CaptionAnchor, CaptionFormat, CaptionStyle, CaptionTrack, ClipId, SequenceSettings, TrackId};+use filmcraft_time::{Tick, TimeDisplay, format_time};++use crate::commands::{CommandSpec, always, bad, bool_p, f64_p, has_seq, str_p, time_p, u64_p};+use crate::{EngineError, Result, Session};++type Run = fn(&mut Session, &Value) -> Result<Value>;+type Enabled = fn(&Session) -> std::result::Result<(), String>;++fn spec(+ id: &'static str,+ label: &'static str,+ menu: &'static [&'static str],+ shortcut: Option<&'static str>,+ params: &'static str,+ enabled: Enabled,+ run: Run,+) -> CommandSpec {+ CommandSpec { id, label, menu, shortcut, params, enabled, run, journal: true }+}++fn has_caption_track(s: &Session) -> std::result::Result<(), String> {+ has_seq(s)?;+ if s.active_sequence().is_some_and(|q| !q.caption_tracks.is_empty()) { Ok(()) } else { Err("the sequence has no caption track".into()) }+}++fn has_captions(s: &Session) -> std::result::Result<(), String> {+ has_caption_track(s)?;+ if s.active_sequence().is_some_and(|q| q.caption_tracks.iter().any(|t| !t.captions.is_empty())) { Ok(()) } else { Err("there are no captions".into()) }+}++/// The caption track named by `track` (id or "C1"…), else the first one.+pub fn track_param(s: &Session, p: &Value) -> Option<TrackId> {+ let seq = s.active_sequence()?;+ match p.get("track") {+ Some(Value::Number(n)) => n.as_u64().map(TrackId).filter(|t| seq.caption_track(*t).is_some()),+ Some(Value::String(name)) => {+ let idx: usize = name.trim_start_matches(['C', 'c']).parse().ok()?;+ seq.caption_tracks.get(idx.checked_sub(1)?).map(|t| t.id)+ }+ _ => seq.caption_tracks.first().map(|t| t.id),+ }+}++fn caption_ids(s: &Session, p: &Value) -> Vec<ClipId> {+ if let Some(a) = p.get("captions").and_then(Value::as_array) {+ return a.iter().filter_map(Value::as_u64).map(ClipId).collect();+ }+ if let Some(c) = u64_p(p, "caption") {+ return vec![ClipId(c)];+ }+ if !s.state.caption_selection.is_empty() {+ return s.state.caption_selection.clone();+ }+ // the caption under the playhead on the first caption track that has one+ let t = s.playhead();+ s.active_sequence().and_then(|q| q.caption_tracks.iter().find_map(|tr| tr.caption_at(t).map(|c| c.id))).into_iter().collect()+}++fn one_caption(s: &Session, p: &Value, cmd: &str) -> Result<ClipId> {+ caption_ids(s, p).first().copied().ok_or_else(|| bad(cmd, "no caption (pass `caption` or select one)"))+}++fn parse_color(v: &Value) -> Option<[u8; 4]> {+ if let Some(a) = v.as_array() {+ let c: Vec<u8> = a.iter().filter_map(|x| x.as_u64().map(|n| n.min(255) as u8)).collect();+ return match c.len() {+ 3 => Some([c[0], c[1], c[2], 255]),+ 4 => Some([c[0], c[1], c[2], c[3]]),+ _ => None,+ };+ }+ let h = v.as_str()?.trim_start_matches('#');+ let b = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok();+ match h.len() {+ 6 => Some([b(0)?, b(2)?, b(4)?, 255]),+ 8 => Some([b(0)?, b(2)?, b(4)?, b(6)?]),+ _ => None,+ }+}++fn hex(c: [u8; 4]) -> String {+ format!("#{:02x}{:02x}{:02x}{:02x}", c[0], c[1], c[2], c[3])+}++/// The caption format of a file, if it is one (extension `.srt` / `.vtt` / `.scc`, confirmed by+/// content).+pub fn detect(path: &str, bytes: &[u8]) -> Option<Format> {+ let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);+ if !matches!(ext.as_deref(), Some("srt" | "vtt" | "scc" | "webvtt")) {+ return None;+ }+ filmcraft_captions::detect(bytes, ext.as_deref())+}++/// Import a caption file as a new caption track in the active sequence (a new sequence is made+/// when none is open), snapped to the sequence's frames. One undo step.+pub fn import(s: &mut Session, path: &str, bytes: &[u8], format: Format, name: Option<&str>) -> Result<Value> {+ let mut doc = filmcraft_captions::parse(bytes, format).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ let stem = std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Captions".into());+ let track_name = name.map(str::to_string).unwrap_or_else(|| stem.clone());+ let seq_id = match s.state.active_sequence.filter(|id| s.project.sequence(*id).is_some()) {+ Some(id) => id,+ None => {+ let id = s.edit("New Sequence", |p, _| Ok(p.new_sequence(&stem, SequenceSettings::default(), 3, 3, None)))?;+ s.state.active_sequence = Some(id);+ s.state.open_sequences.push(id);+ id+ }+ };+ let rate = s.project.sequence(seq_id).map(|q| q.settings.frame_rate).unwrap_or_default();+ doc.snap_to_frames(rate);+ let n = doc.cues.len();+ let warnings = doc.warnings.clone();+ let tid = s.edit(&format!("Import Captions {stem}"), |p, st| {+ let tid = TrackId(p.alloc_id());+ let mut next = p.next_id;+ let mut alloc = || {+ let v = next;+ next += 1;+ v+ };+ let mut track = filmcraft_captions::track_from_document(&doc, tid, &track_name, format.track_format(), &mut alloc);+ if format == Format::Scc {+ track.style.background_color = [0, 0, 0, 255];+ }+ p.next_id = next;+ let q = p.sequence_mut(seq_id).ok_or(EngineError::NoSequence)?;+ q.caption_tracks.insert(0, track);+ q.check().map_err(EngineError::Other)?;+ st.caption_selection.clear();+ Ok(tid)+ })?;+ Ok(json!({"format": format.name(), "sequence": seq_id.0, "track": tid.0, "captions": n, "warnings": warnings}))+}++/// Delete captions (Clear / Ripple Delete with captions selected).+pub fn delete(s: &mut Session, ids: &[ClipId], ripple: bool) -> Result<Value> {+ if ids.is_empty() {+ return Err(bad("captions.delete", "no captions"));+ }+ let ids = ids.to_vec();+ let n = s.edit_sequence(if ripple { "Ripple Delete Captions" } else { "Delete Captions" }, |q, _, st| {+ let n = edit::captions::delete_captions(q, &ids, ripple)?;+ st.caption_selection.retain(|c| !ids.contains(c));+ Ok(n)+ })?;+ Ok(json!({"deleted": n}))+}++fn caption_json(s: &Session, c: &filmcraft_project::Caption) -> Value {+ let q = s.active_sequence();+ let (rate, df) = q.map(|q| (q.settings.frame_rate, q.settings.drop_frame)).unwrap_or_default();+ let tc = |t: Tick| format_time(t, rate, df, TimeDisplay::Timecode, 48_000);+ json!({+ "id": c.id.0,+ "start": c.start.0,+ "end": c.end().0,+ "in": tc(c.start),+ "out": tc(c.end()),+ "duration": tc(c.duration),+ "text": c.text,+ "speaker": c.speaker,+ "settings": c.settings,+ })+}++fn track_json(s: &Session, t: &CaptionTrack, index: usize) -> Value {+ json!({+ "id": t.id.0,+ "label": format!("C{}", index + 1),+ "name": t.name,+ "format": t.format.label(),+ "language": t.language,+ "enabled": t.enabled,+ "locked": t.locked,+ "syncLock": t.sync_lock,+ "style": {+ "font": t.style.font, "size": t.style.size, "color": hex(t.style.color),+ "background": t.style.background, "backgroundColor": hex(t.style.background_color),+ "align": format!("{:?}", t.style.align).to_lowercase(), "anchor": format!("{:?}", t.style.anchor).to_lowercase(),+ "margin": t.style.margin, "lineSpacing": t.style.line_spacing, "outline": t.style.outline, "outlineColor": hex(t.style.outline_color),+ },+ "captions": t.captions.iter().map(|c| caption_json(s, c)).collect::<Vec<_>>(),+ })+}++fn export(s: &mut Session, p: &Value) -> Result<Value> {+ let path = str_p(p, "path").ok_or_else(|| bad("captions.export", "need `path`"))?.to_string();+ let ext = std::path::Path::new(&path).extension().and_then(|e| e.to_str()).unwrap_or("");+ let format = str_p(p, "format").and_then(Format::from_name).or_else(|| Format::from_name(ext)).unwrap_or(Format::Srt);+ let tid = track_param(s, p).ok_or_else(|| bad("captions.export", "no caption track"))?;+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let track = seq.caption_track(tid).ok_or_else(|| bad("captions.export", "no such caption track"))?;+ let doc: Document = filmcraft_captions::document_from_track(track, Tick::ZERO);+ let df = bool_p(p, "dropFrame").unwrap_or(true);+ let bytes = filmcraft_captions::write(&doc, format, WriteOptions { drop_frame: df });+ let n = doc.cues.len();+ s.services.write_file(&path, &bytes).map_err(|e| EngineError::Other(e.to_string()))?;+ Ok(json!({"path": path, "format": format.name(), "captions": n, "bytes": bytes.len()}))+}++fn delta_p(s: &Session, p: &Value) -> Option<Tick> {+ if let Some(d) = p.get("delta").and_then(Value::as_i64) {+ return Some(Tick(d));+ }+ p.get("deltaFrames").and_then(Value::as_i64).map(|f| s.sequence_rate().tick_of(f))+}++pub fn commands() -> Vec<CommandSpec> {+ vec![+ spec(+ "captions.newTrack",+ "Add New Caption Track…",+ &["Sequence", "Captions"],+ Some("Cmd+Alt+A"),+ r#"{"format":"Subtitle|CEA-608|CEA-708|Teletext","name":str?,"language":str?}"#,+ has_seq,+ |s, p| {+ let format = str_p(p, "format").and_then(CaptionFormat::from_name).unwrap_or_default();+ let name = str_p(p, "name").map(str::to_string).unwrap_or_else(|| format.label().to_string());+ let lang = str_p(p, "language").unwrap_or("en").to_string();+ let seq = s.state.active_sequence.ok_or(EngineError::NoSequence)?;+ let id = s.edit("Add Caption Track", |pr, _| {+ let id = TrackId(pr.alloc_id());+ let mut t = CaptionTrack::new(id, name, format);+ t.language = lang;+ if format == CaptionFormat::Cea608 {+ t.style.background_color = [0, 0, 0, 255];+ }+ pr.sequence_mut(seq).ok_or(EngineError::NoSequence)?.caption_tracks.insert(0, t);+ Ok(id)+ })?;+ Ok(json!({"track": id.0}))+ },+ ),+ spec("captions.deleteTrack", "Delete Caption Track", &[], None, r#"{"track":id|"C1"}"#, has_caption_track, |s, p| {+ let tid = track_param(s, p).ok_or_else(|| bad("captions.deleteTrack", "no such caption track"))?;+ s.edit_sequence("Delete Caption Track", |q, _, st| {+ q.caption_tracks.retain(|t| t.id != tid);+ st.caption_selection.retain(|c| q.find_caption(*c).is_some());+ Ok(())+ })?;+ Ok(Value::Null)+ }),+ spec(+ "captions.setTrack",+ "Caption Track Settings",+ &[],+ None,+ r#"{"track":id|"C1","name":str?,"format":str?,"language":str?,"enabled":bool?,"locked":bool?,"syncLock":bool?}"#,+ has_caption_track,+ |s, p| {+ let tid = track_param(s, p).ok_or_else(|| bad("captions.setTrack", "no such caption track"))?;+ let p = p.clone();+ s.edit("Caption Track Settings", |pr, st| {+ let seq = st.active_sequence.ok_or(EngineError::NoSequence)?;+ let t = pr.sequence_mut(seq).and_then(|q| q.caption_track_mut(tid)).ok_or(EngineError::NoSequence)?;+ if let Some(n) = str_p(&p, "name") {+ t.name = n.to_string();+ }+ if let Some(f) = str_p(&p, "format") {+ t.format = CaptionFormat::from_name(f).ok_or_else(|| bad("captions.setTrack", "unknown format"))?;+ }+ if let Some(l) = str_p(&p, "language") {+ t.language = l.to_string();+ }+ if let Some(b) = bool_p(&p, "enabled") {+ t.enabled = b;+ }+ if let Some(b) = bool_p(&p, "locked") {+ t.locked = b;+ }+ if let Some(b) = bool_p(&p, "syncLock") {+ t.sync_lock = b;+ }+ Ok(())+ })?;+ Ok(Value::Null)+ },+ ),+ spec(+ "captions.setStyle",+ "Caption Track Style",+ &[],+ None,+ r##"{"track":id|"C1","font":str?,"size":f32?,"color":"#rrggbb[aa]"?,"background":bool?,"backgroundColor":"#rrggbbaa"?,"align":"left|center|right"?,"anchor":"top|middle|bottom"?,"margin":f32?,"lineSpacing":f32?,"outline":f32?,"outlineColor":str?,"reset":bool?}"##,+ has_caption_track,+ |s, p| {+ let tid = track_param(s, p).ok_or_else(|| bad("captions.setStyle", "no such caption track"))?;+ let p = p.clone();+ s.edit("Caption Style", |pr, st| {+ let seq = st.active_sequence.ok_or(EngineError::NoSequence)?;+ let t = pr.sequence_mut(seq).and_then(|q| q.caption_track_mut(tid)).ok_or(EngineError::NoSequence)?;+ let y = &mut t.style;+ if bool_p(&p, "reset").unwrap_or(false) {+ *y = CaptionStyle::default();+ }+ if let Some(v) = str_p(&p, "font") {+ y.font = v.to_string();+ }+ if let Some(v) = f64_p(&p, "size") {+ y.size = (v as f32).clamp(4.0, 400.0);+ }+ if let Some(c) = p.get("color").and_then(parse_color) {+ y.color = c;+ }+ if let Some(b) = bool_p(&p, "background") {+ y.background = b;+ }+ if let Some(c) = p.get("backgroundColor").and_then(parse_color) {+ y.background_color = c;+ }+ if let Some(c) = p.get("outlineColor").and_then(parse_color) {+ y.outline_color = c;+ }+ if let Some(v) = f64_p(&p, "outline") {+ y.outline = (v as f32).clamp(0.0, 40.0);+ }+ if let Some(v) = f64_p(&p, "margin") {+ y.margin = (v as f32).clamp(0.0, 0.45);+ }+ if let Some(v) = f64_p(&p, "lineSpacing") {+ y.line_spacing = (v as f32).clamp(0.8, 4.0);+ }+ match str_p(&p, "align") {+ Some("left") => y.align = CaptionAlign::Left,+ Some("right") => y.align = CaptionAlign::Right,+ Some("center") => y.align = CaptionAlign::Center,+ Some(o) => return Err(bad("captions.setStyle", format!("unknown align `{o}`"))),+ None => {}+ }+ match str_p(&p, "anchor") {+ Some("top") => y.anchor = CaptionAnchor::Top,+ Some("middle") => y.anchor = CaptionAnchor::Middle,+ Some("bottom") => y.anchor = CaptionAnchor::Bottom,+ Some(o) => return Err(bad("captions.setStyle", format!("unknown anchor `{o}`"))),+ None => {}+ }+ Ok(())+ })?;+ Ok(Value::Null)+ },+ ),+ spec(+ "captions.add",+ "Add Caption at Playhead",+ &["Sequence", "Captions"],+ Some("Cmd+Alt+C"),+ r#"{"track":id|"C1"?,"text":str?,"time":ticks?,"seconds":f64?,"durationSeconds":f64=3}"#,+ has_seq,+ |s, p| {+ // a caption track is created when the sequence has none+ if s.active_sequence().is_some_and(|q| q.caption_tracks.is_empty()) {+ s.execute("captions.newTrack", json!({}))?;+ }+ let tid = track_param(s, p).ok_or_else(|| bad("captions.add", "no such caption track"))?;+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ let rate = s.sequence_rate();+ let dur = Tick::from_seconds_f64(f64_p(p, "durationSeconds").unwrap_or(edit::captions::DEFAULT_SECONDS as f64));+ let dur = rate.snap_nearest(dur).max(rate.frame_duration());+ let text = str_p(p, "text").unwrap_or("New caption").to_string();+ let t = rate.snap(t);+ let id = s.edit_sequence("Add Caption", |q, ctx, st| {+ let id = edit::captions::add_caption(q, tid, t, dur, &text, ctx)?;+ st.caption_selection = vec![id];+ st.selection.clear();+ Ok(id)+ })?;+ Ok(json!({"caption": id.0}))+ },+ ),+ spec("captions.split", "Split Caption", &[], None, r#"{"caption":id?,"time":ticks?}"#, has_captions, |s, p| {+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ let explicit = u64_p(p, "caption").map(ClipId);+ let ids = s.edit_sequence("Split Caption", |q, ctx, st| {+ let ids = match explicit {+ Some(c) => vec![edit::captions::split_caption(q, c, t, ctx)?],+ None => edit::captions::split_captions_at(q, &[], t, ctx),+ };+ if ids.is_empty() {+ return Err(edit::EditError::Nothing.into());+ }+ st.caption_selection = ids.clone();+ Ok(ids)+ })?;+ Ok(json!({"captions": ids.iter().map(|c| c.0).collect::<Vec<_>>()}))+ }),+ spec("captions.merge", "Merge Captions", &[], None, r#"{"captions":[id]?}"#, has_captions, |s, p| {+ let ids = caption_ids(s, p);+ let id = s.edit_sequence("Merge Captions", |q, _, st| {+ let id = edit::captions::merge_captions(q, &ids)?;+ st.caption_selection = vec![id];+ Ok(id)+ })?;+ Ok(json!({"caption": id.0}))+ }),+ spec("captions.setText", "Edit Caption Text", &[], None, r#"{"caption":id?,"text":str?,"speaker":str|null?}"#, has_captions, |s, p| {+ let id = one_caption(s, p, "captions.setText")?;+ let text = str_p(p, "text").map(str::to_string);+ let speaker: Option<Option<String>> = match p.get("speaker") {+ None => None,+ Some(Value::Null) => Some(None),+ Some(v) => Some(v.as_str().map(str::to_string)),+ };+ if text.is_none() && speaker.is_none() {+ return Err(bad("captions.setText", "need `text` or `speaker`"));+ }+ s.edit_sequence("Edit Caption", |q, _, _| Ok(edit::captions::set_caption(q, id, text.as_deref(), speaker.as_ref().map(|o| o.as_deref()))?))?;+ Ok(Value::Null)+ }),+ spec(+ "captions.setTimes",+ "Set Caption In/Out",+ &[],+ None,+ r#"{"caption":id?,"startTime|startFrame|startSeconds|startTimecode":…,"endTime|endFrame|endSeconds|endTimecode":…}"#,+ has_captions,+ |s, p| {+ let id = one_caption(s, p, "captions.setTimes")?;+ let cur = s+ .active_sequence()+ .and_then(|q| q.find_caption(id))+ .map(|(_, c)| (c.start, c.end()))+ .ok_or(EngineError::Edit(edit::EditError::NoItem(id)))?;+ let rate = s.sequence_rate();+ let start = time_p(s, p, "start").map(|t| rate.snap_nearest(t)).unwrap_or(cur.0);+ let end = time_p(s, p, "end").map(|t| rate.snap_nearest(t)).unwrap_or(cur.1);+ s.edit_sequence("Caption Timing", |q, ctx, _| Ok(edit::captions::set_caption_times(q, id, start, end, ctx)?))?;+ Ok(json!({"start": start.0, "end": end.0}))+ },+ ),+ spec("captions.trim", "Trim Caption", &[], None, r#"{"caption":id,"edge":"in|out","delta":ticks|"deltaFrames":i64}"#, has_captions, |s, p| {+ let id = one_caption(s, p, "captions.trim")?;+ let edge = if str_p(p, "edge") == Some("in") { Edge::In } else { Edge::Out };+ let d = delta_p(s, p).ok_or_else(|| bad("captions.trim", "need `delta` or `deltaFrames`"))?;+ let applied = s.edit_sequence("Trim Caption", |q, ctx, _| Ok(edit::captions::trim_caption(q, id, edge, d, ctx)?))?;+ Ok(json!({"applied": applied.0}))+ }),+ spec("captions.move", "Move Captions", &[], None, r#"{"captions":[id]?,"delta":ticks|"deltaFrames":i64}"#, has_captions, |s, p| {+ let ids = caption_ids(s, p);+ let d = delta_p(s, p).ok_or_else(|| bad("captions.move", "need `delta` or `deltaFrames`"))?;+ let applied = s.edit_sequence("Move Captions", |q, _, _| Ok(edit::captions::move_captions(q, &ids, d)?))?;+ Ok(json!({"applied": applied.0}))+ }),+ spec("captions.delete", "Delete Captions", &[], None, r#"{"captions":[id]?,"ripple":bool=false}"#, has_captions, |s, p| {+ let ids = caption_ids(s, p);+ delete(s, &ids, bool_p(p, "ripple").unwrap_or(false))+ }),+ spec("captions.select", "Select Captions", &[], None, r#"{"captions":[id],"add":bool?}"#, has_seq, |s, p| {+ let ids: Vec<ClipId> =+ p.get("captions").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(ClipId).collect()).unwrap_or_default();+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let ids: Vec<ClipId> = ids.into_iter().filter(|c| seq.find_caption(*c).is_some()).collect();+ if bool_p(p, "add").unwrap_or(false) {+ for c in ids {+ if !s.state.caption_selection.contains(&c) {+ s.state.caption_selection.push(c);+ }+ }+ } else {+ s.state.caption_selection = ids;+ s.state.selection.clear();+ }+ Ok(json!({"captions": s.state.caption_selection.iter().map(|c| c.0).collect::<Vec<_>>()}))+ }),+ spec("captions.goTo", "Go to Caption", &[], None, r#"{"caption":id}"#, has_captions, |s, p| {+ let id = one_caption(s, p, "captions.goTo")?;+ let start = s.active_sequence().and_then(|q| q.find_caption(id)).map(|(_, c)| c.start).ok_or(EngineError::Edit(edit::EditError::NoItem(id)))?;+ s.set_playhead(start);+ s.state.caption_selection = vec![id];+ s.state.selection.clear();+ Ok(json!({"time": start.0}))+ }),+ spec("captions.next", "Go to Next Caption Segment", &["Sequence", "Captions"], Some("Cmd+Alt+Down"), "{}", has_captions, |s, _| step(s, true)),+ spec("captions.previous", "Go to Previous Caption Segment", &["Sequence", "Captions"], Some("Cmd+Alt+Up"), "{}", has_captions, |s, _| step(s, false)),+ spec("captions.showAll", "Show All Caption Tracks", &["Sequence", "Captions"], None, "{}", has_caption_track, |s, _| show_all(s, true)),+ spec("captions.hideAll", "Hide All Caption Tracks", &["Sequence", "Captions"], None, "{}", has_caption_track, |s, _| show_all(s, false)),+ spec("captions.import", "Import Captions…", &[], None, r#"{"path":str,"name":str?}"#, always, |s, p| {+ let path = str_p(p, "path").ok_or_else(|| bad("captions.import", "need `path`"))?.to_string();+ let bytes = s.services.read_file(&path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ let ext = std::path::Path::new(&path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);+ let format = filmcraft_captions::detect(&bytes, ext.as_deref()).ok_or_else(|| EngineError::Other(format!("{path}: not a caption file")))?;+ import(s, &path, &bytes, format, str_p(p, "name"))+ }),+ spec(+ "captions.export",+ "Captions…",+ &["File", "Export"],+ None,+ r#"{"path":str,"format":"srt|vtt|scc"?,"track":id|"C1"?,"dropFrame":bool=true}"#,+ has_caption_track,+ export,+ ),+ CommandSpec {+ id: "captions.list",+ label: "List Captions",+ menu: &[],+ shortcut: None,+ params: r#"{"track":id|"C1"?}"#,+ enabled: always,+ run: |s, p| {+ let Some(seq) = s.active_sequence() else { return Ok(json!({"tracks": []})) };+ let only = p.get("track").and_then(|_| track_param(s, p));+ let tracks: Vec<Value> =+ seq.caption_tracks.iter().enumerate().filter(|(_, t)| only.is_none_or(|o| o == t.id)).map(|(i, t)| track_json(s, t, i)).collect();+ Ok(json!({"tracks": tracks, "selection": s.state.caption_selection.iter().map(|c| c.0).collect::<Vec<_>>()}))+ },+ journal: false,+ },+ ]+}++fn step(s: &mut Session, forward: bool) -> Result<Value> {+ let t = s.playhead();+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let mut starts: Vec<(Tick, ClipId)> = seq.caption_tracks.iter().filter(|t| t.enabled).flat_map(|t| t.captions.iter().map(|c| (c.start, c.id))).collect();+ starts.sort();+ let hit = if forward { starts.iter().find(|(st, _)| *st > t).copied() } else { starts.iter().rev().find(|(st, _)| *st < t).copied() };+ let (time, id) = hit.ok_or_else(|| EngineError::Other("no more captions".into()))?;+ s.set_playhead(time);+ s.state.caption_selection = vec![id];+ Ok(json!({"time": time.0, "caption": id.0}))+}++fn show_all(s: &mut Session, on: bool) -> Result<Value> {+ s.edit(if on { "Show All Caption Tracks" } else { "Hide All Caption Tracks" }, |p, st| {+ let seq = st.active_sequence.ok_or(EngineError::NoSequence)?;+ for t in &mut p.sequence_mut(seq).ok_or(EngineError::NoSequence)?.caption_tracks {+ t.enabled = on;+ }+ Ok(())+ })?;+ Ok(Value::Null)+}++#[cfg(test)]+#[path = "captions_tests.rs"]+mod tests;diff --git a/crates/engine/src/captions_tests.rs b/crates/engine/src/captions_tests.rsnew file mode 100644index 000000000..2167d4b77--- /dev/null+++ b/crates/engine/src/captions_tests.rs@@ -0,0 +1,139 @@+use serde_json::json;++use crate::Session;+use filmcraft_project::ClipId;+use filmcraft_time::{TICKS_PER_SECOND, Tick};++fn demo() -> Session {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ s+}++#[test]+fn captions_import_edit_export_and_burn_in() {+ let dir = std::env::temp_dir().join(format!("fc-cap-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let srt = dir.join("talk.srt");+ std::fs::write(+ &srt,+ "\u{feff}1\r\n00:00:00,500 --> 00:00:02,000\r\nHello there\r\n\r\n2\r\n00:00:02,500 --> 00:00:04,000\r\nSecond line\r\nwith two rows\r\n",+ )+ .unwrap();+ let mut s = demo();+ let r = s.execute("file.import", json!({"paths": [srt.to_string_lossy()]})).unwrap();+ assert_eq!(r["documents"][0]["captions"], 2, "{r}");+ let q = s.active_sequence().unwrap();+ let rate = q.settings.frame_rate;+ let tr = q.caption_tracks[0].clone();+ assert_eq!(tr.name, "talk");+ assert_eq!(tr.captions[0].start, rate.snap_nearest(Tick(TICKS_PER_SECOND / 2)), "snapped to frames");+ let first = tr.captions[0].id;+ let second = tr.captions[1].id;++ // edit text, split, merge, trim, move, add at playhead, delete — each one undoable+ s.execute("captions.setText", json!({"caption": first.0, "text": "Hi!", "speaker": "Ann"})).unwrap();+ let split_at = rate.tick_of(rate.frame_at(tr.captions[1].start) + 10);+ let r = s.execute("captions.split", json!({"caption": second.0, "time": split_at.0})).unwrap();+ let right = ClipId(r["captions"][0].as_u64().unwrap());+ assert_eq!(s.active_sequence().unwrap().caption_tracks[0].captions.len(), 3);+ s.execute("captions.merge", json!({"captions": [second.0, right.0]})).unwrap();+ assert_eq!(s.active_sequence().unwrap().caption_tracks[0].captions.len(), 2);+ s.execute("captions.trim", json!({"caption": second.0, "edge": "out", "deltaFrames": 12})).unwrap();+ s.execute("captions.move", json!({"captions": [second.0], "deltaFrames": 24})).unwrap();+ s.execute("playhead.set", json!({"seconds": 8.0})).unwrap();+ let r = s.execute("captions.add", json!({"text": "Added"})).unwrap();+ let added = ClipId(r["caption"].as_u64().unwrap());+ assert_eq!(s.state.caption_selection, vec![added]);+ s.execute("edit.clear", json!({})).unwrap();+ assert!(s.active_sequence().unwrap().find_caption(added).is_none(), "Clear deletes selected captions");+ s.execute("edit.undo", json!({})).unwrap();+ assert!(s.active_sequence().unwrap().find_caption(added).is_some());+ let list = s.execute("captions.list", json!({})).unwrap();+ assert_eq!(list["tracks"][0]["captions"][0]["text"], "Hi!");+ assert_eq!(list["tracks"][0]["captions"][0]["speaker"], "Ann");+ s.active_sequence().unwrap().check().unwrap();++ // export in all three formats and read back: same texts+ for ext in ["srt", "vtt", "scc"] {+ let path = dir.join(format!("out.{ext}")).to_string_lossy().to_string();+ let r = s.execute("captions.export", json!({"path": path})).unwrap();+ assert_eq!(r["captions"], 3, "{ext}: {r}");+ let back = filmcraft_captions::parse(&std::fs::read(&path).unwrap(), filmcraft_captions::Format::from_name(ext).unwrap()).unwrap();+ let texts: Vec<String> = back.cues.iter().map(|c| filmcraft_project::plain_text(&c.text)).collect();+ assert_eq!(texts.len(), 3, "{ext}");+ assert_eq!(texts[0], "Hi!", "{ext}");+ }++ // the program renders captions; hiding the track removes them+ s.execute("playhead.set", json!({"seconds": 1.0})).unwrap();+ let with = s.render_program(0.25).unwrap();+ s.execute("captions.hideAll", json!({})).unwrap();+ let without = s.render_program(0.25).unwrap();+ let diff = with.px.iter().zip(&without.px).filter(|(a, b)| (*a - *b).abs() > 0.05).count();+ assert!(diff > 200, "captions change the picture ({diff} samples)");+ let half = with.w * 4 * (with.h / 2);+ let top_diff = with.px[..half].iter().zip(&without.px[..half]).filter(|(a, b)| (*a - *b).abs() > 0.05).count();+ assert_eq!(top_diff, 0, "bottom-anchored captions stay in the lower half");+ s.execute("captions.showAll", json!({})).unwrap();+ let plan = filmcraft_render::plan::plan_frame(+ &s.project,+ s.state.active_sequence.unwrap(),+ s.playhead(),+ filmcraft_render::RenderOptions { scale: 0.25, captions: true, ..Default::default() },+ &s.media.provider(s.project.clone(), s.services.clone()),+ );+ let cpu = filmcraft_render::plan::execute_cpu(&plan);+ let pd = cpu.px.iter().zip(&with.px).filter(|(a, b)| (*a - *b).abs() > 0.02).count();+ assert!(pd < cpu.px.len() / 200, "the GPU plan matches the CPU render ({pd})");++ // save/open keeps caption tracks+ let proj = dir.join("cap.fcproj").to_string_lossy().to_string();+ s.execute("file.saveAs", json!({"path": proj})).unwrap();+ let before = s.active_sequence().unwrap().caption_tracks.clone();+ s.execute("file.open", json!({"path": proj})).unwrap();+ assert_eq!(s.active_sequence().unwrap().caption_tracks, before);+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn caption_track_follows_sync_locked_insert() {+ let mut s = demo();+ s.execute("captions.newTrack", json!({"format": "CEA-608"})).unwrap();+ s.execute("playhead.set", json!({"seconds": 4.0})).unwrap();+ s.execute("captions.add", json!({"text": "later"})).unwrap();+ let start = s.active_sequence().unwrap().caption_tracks[0].captions[0].start;+ let item = s.project.items.values().find(|i| i.as_media().is_some_and(|m| m.info.has_video())).unwrap().id;+ s.execute("source.open", json!({"item": item.0})).unwrap();+ s.execute("playhead.set", json!({"seconds": 0.0})).unwrap();+ s.execute("source.insert", json!({})).unwrap();+ let after = s.active_sequence().unwrap().caption_tracks[0].captions[0].start;+ assert!(after > start, "caption moved right with the insert");+ s.active_sequence().unwrap().check().unwrap();+}++#[test]+fn caption_commands_need_tracks_and_navigate() {+ let mut s = demo();+ assert!(s.execute("captions.split", json!({})).is_err(), "disabled without captions");+ for (sec, text) in [(1.0, "one"), (3.0, "two"), (6.0, "three")] {+ s.execute("playhead.set", json!({"seconds": sec})).unwrap();+ s.execute("captions.add", json!({"text": text, "durationSeconds": 1.0})).unwrap();+ }+ s.execute("playhead.set", json!({"seconds": 0.0})).unwrap();+ s.execute("captions.next", json!({})).unwrap();+ s.execute("captions.next", json!({})).unwrap();+ let id = s.state.caption_selection[0];+ assert_eq!(s.active_sequence().unwrap().find_caption(id).unwrap().1.text, "two");+ s.execute("captions.previous", json!({})).unwrap();+ let id = s.state.caption_selection[0];+ assert_eq!(s.active_sequence().unwrap().find_caption(id).unwrap().1.text, "one");+ s.execute("captions.setStyle", json!({"color": "#ffff00", "anchor": "top", "size": 40})).unwrap();+ let st = &s.active_sequence().unwrap().caption_tracks[0].style;+ assert_eq!(st.color, [255, 255, 0, 255]);+ assert!(s.execute("captions.setStyle", json!({"anchor": "sideways"})).is_err());+ s.execute("captions.setTimes", json!({"caption": id.0, "startSeconds": 0.5, "endSeconds": 2.5})).unwrap();+ assert!(s.execute("captions.setTimes", json!({"caption": id.0, "endSeconds": 3.5})).is_err(), "would overlap `two`");+ s.execute("captions.deleteTrack", json!({"track": "C1"})).unwrap();+ assert!(s.active_sequence().unwrap().caption_tracks.is_empty());+}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 956dd8ca9..097b7b935 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -57,7 +57,7 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {// ---------- enablement -----------fn always(_: &Session) -> std::result::Result<(), String> {+pub(crate) fn always(_: &Session) -> std::result::Result<(), String> {Ok(())}fn has_edit_points(s: &Session) -> std::result::Result<(), String> {@@ -65,13 +65,18 @@ fn has_edit_points(s: &Session) -> std::result::Result<(), String> {if s.state.edit_points.is_empty() { Err("no edit points selected".into()) } else { Ok(()) }}-fn has_seq(s: &Session) -> std::result::Result<(), String> {+pub(crate) fn has_seq(s: &Session) -> std::result::Result<(), String> {s.active_sequence().map(|_| ()).ok_or_else(|| "no sequence is open".into())}fn has_selection(s: &Session) -> std::result::Result<(), String> {has_seq(s)?;if s.state.selection.is_empty() { Err("no clips selected".into()) } else { Ok(()) }}+/// Clips or captions selected (Clear / Ripple Delete work on either).+fn has_any_selection(s: &Session) -> std::result::Result<(), String> {+ has_seq(s)?;+ if s.state.selection.is_empty() && s.state.caption_selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) }+}fn has_source(s: &Session) -> std::result::Result<(), String> {has_seq(s)?;s.state.source_item.map(|_| ()).ok_or_else(|| "no clip in the Source monitor".into())@@ -96,24 +101,24 @@ fn has_clipboard(s: &Session) -> std::result::Result<(), String> {// ---------- param helpers -----------fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {+pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }}-fn str_p<'a>(p: &'a Value, k: &str) -> Option<&'a str> {+pub(crate) fn str_p<'a>(p: &'a Value, k: &str) -> Option<&'a str> {p.get(k).and_then(Value::as_str)}-fn f64_p(p: &Value, k: &str) -> Option<f64> {+pub(crate) fn f64_p(p: &Value, k: &str) -> Option<f64> {p.get(k).and_then(Value::as_f64)}-fn bool_p(p: &Value, k: &str) -> Option<bool> {+pub(crate) fn bool_p(p: &Value, k: &str) -> Option<bool> {p.get(k).and_then(Value::as_bool)}-fn u64_p(p: &Value, k: &str) -> Option<u64> {+pub(crate) fn u64_p(p: &Value, k: &str) -> Option<u64> {p.get(k).and_then(|v| v.as_u64().or_else(|| v.as_f64().map(|f| f as u64)))}/// Parse a time from params: `time` (ticks), `frame`, `seconds` or `timecode`, with `prefix`.-fn time_p(s: &Session, p: &Value, prefix: &str) -> Option<Tick> {+pub(crate) fn time_p(s: &Session, p: &Value, prefix: &str) -> Option<Tick> {let rate = s.sequence_rate();let k = |n: &str| if prefix.is_empty() { n.to_string() } else { format!("{prefix}{}{}", n[..1].to_uppercase(), &n[1..]) };if let Some(t) = p.get(k("time")).and_then(Value::as_i64) {@@ -496,6 +501,13 @@ fn build() -> Vec<CommandSpec> {let mut reports = Vec::new();for path in paths {match s.services.read_file(&path) {+ Ok(b) if crate::captions::detect(&path, &b).is_some() => {+ let fmt = crate::captions::detect(&path, &b).expect("detected");+ match crate::captions::import(s, &path, &b, fmt, None) {+ Ok(r) => reports.push(r),+ Err(e) => errors.push(format!("{path}: {e}")),+ }+ }Ok(b) if crate::interchange::detect(&path, &b).is_some() => {let fmt = crate::interchange::detect(&path, &b).expect("detected");match crate::interchange::import(s, &path, &b, fmt) {@@ -513,7 +525,7 @@ fn build() -> Vec<CommandSpec> {Err(e) => errors.push(format!("{path}: {e}")),}}- if ids.is_empty() && sequences.is_empty() && !errors.is_empty() {+ if ids.is_empty() && sequences.is_empty() && reports.is_empty() && !errors.is_empty() {return Err(EngineError::Other(errors.join("; ")));}if reports.is_empty() {@@ -583,7 +595,7 @@ fn build() -> Vec<CommandSpec> {"Media…",["File", "Export"],None,- r#"{"path":str,"format":"h264|prores|mjpeg|png|gif|wav","scale":f32=1,"audio":bool=true,"quality":0..100}"#,+ r#"{"path":str,"format":"h264|prores|mjpeg|png|gif|wav","scale":f32=1,"audio":bool=true,"quality":0..100,"burnCaptions":bool=false}"#,has_seq,|s, p| export_media(s, p)),@@ -613,7 +625,11 @@ fn build() -> Vec<CommandSpec> {}),cmd!("edit.paste", "Paste", ["Edit"], Some("Cmd+V"), "{}", has_clipboard, |s, _| paste(s, false)),cmd!("edit.pasteInsert", "Paste Insert", ["Edit"], Some("Cmd+Shift+V"), "{}", has_clipboard, |s, _| paste(s, true)),- cmd!("edit.clear", "Clear", ["Edit"], Some("Backspace"), r#"{"clips":[id]?}"#, has_selection, |s, p| {+ cmd!("edit.clear", "Clear", ["Edit"], Some("Backspace"), r#"{"clips":[id]?}"#, has_any_selection, |s, p| {+ if p.get("clips").is_none() && p.get("clip").is_none() && s.state.selection.is_empty() {+ let caps = s.state.caption_selection.clone();+ return crate::captions::delete(s, &caps, false);+ }let sel = with_links(s, &clips_p(s, p));s.edit_sequence("Clear", |q, _, st| {edit::delete_items(q, &sel);@@ -622,7 +638,11 @@ fn build() -> Vec<CommandSpec> {})?;Ok(Value::Null)}),- cmd!("edit.rippleDelete", "Ripple Delete", ["Edit"], Some("Shift+Delete"), r#"{"clips":[id]?}"#, has_selection, |s, p| {+ cmd!("edit.rippleDelete", "Ripple Delete", ["Edit"], Some("Shift+Delete"), r#"{"clips":[id]?}"#, has_any_selection, |s, p| {+ if p.get("clips").is_none() && p.get("clip").is_none() && s.state.selection.is_empty() {+ let caps = s.state.caption_selection.clone();+ return crate::captions::delete(s, &caps, true);+ }let sel = with_links(s, &clips_p(s, p));s.edit_sequence("Ripple Delete", |q, _, st| {edit::ripple_delete_items(q, &sel)?;@@ -638,6 +658,7 @@ fn build() -> Vec<CommandSpec> {}),cmd!("edit.deselectAll", "Deselect All", ["Edit"], Some("Cmd+Shift+A"), "{}", always, |s, _| {s.state.selection.clear();+ s.state.caption_selection.clear();Ok(Value::Null)}),cmd!("edit.duplicate", "Duplicate", ["Edit"], Some("Cmd+Shift+/"), "{}", has_project_selection, |s, _| {@@ -834,7 +855,11 @@ fn build() -> Vec<CommandSpec> {}),cmd!("sequence.addEditAllTracks", "Add Edit to All Tracks", ["Sequence"], Some("Cmd+Shift+K"), r#"{"time":ticks?}"#, has_seq, |s, p| {let t = time_p(s, p, "").unwrap_or(s.playhead());- let n = s.edit_sequence("Add Edit to All Tracks", |q, ctx, _| Ok(edit::razor(q, &[], t, ctx)))?;+ let n = s.edit_sequence("Add Edit to All Tracks", |q, ctx, _| {+ let mut n = edit::razor(q, &[], t, ctx);+ n.extend(edit::captions::split_captions_at(q, &[], t, ctx));+ Ok(n)+ })?;Ok(json!({"cuts": n.len()}))}),cmd!("sequence.lift", "Lift", ["Sequence"], Some(";"), "{}", has_in_out, |s, _| {@@ -1212,6 +1237,7 @@ fn build() -> Vec<CommandSpec> {}} else {s.state.selection = clips;+ s.state.caption_selection.clear();}Ok(json!({"selection": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>()}))}),@@ -1695,6 +1721,7 @@ fn build() -> Vec<CommandSpec> {json!({"undo": s.history.undo.iter().map(|h| &h.0).collect::<Vec<_>>(), "redo": s.history.redo.iter().map(|h| &h.0).collect::<Vec<_>>()}))),];+ v.extend(crate::captions::commands());// Labels as individual commands (Edit ▸ Label ▸ <name>)for l in Label::ALL {let _ = l;@@ -1718,6 +1745,7 @@ fn export_media(s: &mut Session, p: &Value) -> Result<Value> {include_audio: bool_p(p, "audio").unwrap_or(true),quality: u64_p(p, "quality").unwrap_or(90).min(100) as u8,bitrate_kbps: u64_p(p, "bitrateKbps").unwrap_or(20_000) as u32,+ burn_captions: bool_p(p, "burnCaptions").unwrap_or(false),};let id = s.jobs.len() as u64 + 1;let job = crate::Job {diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex afab02fb2..b491c8b9d 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -8,6 +8,7 @@//! The project is an `Arc<Project>` edited copy-on-write; undo keeps whole-project snapshots (cheap//! thanks to structural sharing of untouched items).+pub mod captions;pub mod commands;pub mod demo;pub mod interchange;@@ -123,6 +124,9 @@ pub struct EditorState {/// Selected edit points (trim mode).#[serde(default)]pub edit_points: Vec<trim::EditPoint>,+ /// Selected captions (caption tracks / Captions panel).+ #[serde(default)]+ pub caption_selection: Vec<ClipId>,}/// Events for frontends (drained each frame).@@ -299,8 +303,10 @@ impl Session {}if let Some(seq) = self.state.active_sequence.and_then(|s| p.sequence(s)) {self.state.selection.retain(|c| seq.find_item(*c).is_some());+ self.state.caption_selection.retain(|c| seq.find_caption(*c).is_some());} else {self.state.selection.clear();+ self.state.caption_selection.clear();}self.state.project_selection.retain(|i| p.item(*i).is_some());}@@ -362,7 +368,8 @@ impl Session {pub fn render_program(&self, scale: f32) -> Option<filmcraft_render::Image> {let seq = self.state.active_sequence?;let provider = self.media.provider(self.project.clone(), self.services.clone());- Some(filmcraft_render::render_sequence(&self.project, seq, self.playhead(), filmcraft_render::RenderOptions { scale, ..Default::default() }, &provider))+ let opts = filmcraft_render::RenderOptions { scale, captions: true, ..Default::default() };+ Some(filmcraft_render::render_sequence(&self.project, seq, self.playhead(), opts, &provider))}}diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex dd032b467..0fa6f9444 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -94,11 +94,23 @@ pub struct ExportSettings {pub quality: u8,/// Target video bitrate (kbps) for bitrate-driven encoders.pub bitrate_kbps: u32,+ /// Burn the visible caption tracks into the picture (Export ▸ Captions ▸ Burn Captions Into+ /// Video).+ pub burn_captions: bool,}impl Default for ExportSettings {fn default() -> Self {- Self { format: Format::H264, path: String::new(), range: None, scale: 1.0, include_audio: true, quality: 90, bitrate_kbps: 20_000 }+ Self {+ format: Format::H264,+ path: String::new(),+ range: None,+ scale: 1.0,+ include_audio: true,+ quality: 90,+ bitrate_kbps: 20_000,+ burn_captions: false,+ }}}@@ -439,7 +451,7 @@ pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, solet h = (((q.settings.height as f32 * settings.scale).round() as u32).max(2)) & !1;progress.total.store(if settings.format == Format::Wav { 1 } else { nframes }, Ordering::Relaxed);progress.set_status(format!("Exporting {} frames ({})", nframes, settings.format.label()));- let opts = RenderOptions { scale: w as f32 / q.settings.width as f32, ..Default::default() };+ let opts = RenderOptions { scale: w as f32 / q.settings.width as f32, captions: settings.burn_captions, ..Default::default() };let render = |f: i64| -> Vec<u8> {let img = filmcraft_render::render_sequence(project, seq, rate.tick_of(f), opts, sources);let mut rgba = img.over_black_rgba8();diff --git a/crates/export/src/tests.rs b/crates/export/src/tests.rsindex 7747a75b8..5ef76d183 100644--- a/crates/export/src/tests.rs+++ b/crates/export/src/tests.rs@@ -99,3 +99,79 @@ fn prores_export_roundtrip() {let f = src.video_frame(FrameRequest::full(Tick(TICKS_PER_SECOND / 3))).unwrap().to_rgba8();assert!(f[0] > 240 && f[1] < 15 && f[2] < 15, "{:?}", &f[..4]);}++/// Burn-in: an H.264 export of a dark-blue matte with a caption, decoded by ffmpeg (external test+/// oracle only), has bright caption pixels in the lower part of the frame, and none without+/// `burn_captions` or above the caption.+#[test]+fn caption_burn_in_h264_ffmpeg_oracle() {+ let Some(ffmpeg) = ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"].into_iter().find(|p| std::path::Path::new(p).exists()) else {+ eprintln!("ffmpeg not found; skipping oracle test");+ return;+ };+ let mut p = Project::new("cap");+ let (w, h) = (640u32, 360u32);+ let g = GeneratorSource::new(Generator::ColorMatte { color: [0.0, 0.0, 0.2, 1.0] }, w, h, FrameRate::FPS_24, Tick(2 * TICKS_PER_SECOND));+ let info = g.info().clone();+ let matte = p.add_item(+ "matte",+ Label::Iris,+ ItemKind::Media(MediaClip {+ media: MediaRef::Generator(g.generator.clone()),+ info,+ interpret: Default::default(),+ mark_in: None,+ mark_out: None,+ markers: vec![],+ offline: false,+ proxy: None,+ }),+ None,+ );+ let r = FrameRate::FPS_24;+ let seq = p.new_sequence("s", SequenceSettings { width: w, height: h, frame_rate: r, ..Default::default() }, 1, 0, None);+ let v = p.make_track_item(matte, TrackKind::Video, Tick::ZERO, TimeRange::new(Tick::ZERO, r.tick_of(24)), r).unwrap();+ let tid = filmcraft_project::TrackId(p.alloc_id());+ let cid = filmcraft_project::ClipId(p.alloc_id());+ let mut ct = filmcraft_project::CaptionTrack::new(tid, "Subtitle".into(), filmcraft_project::CaptionFormat::Subtitle);+ ct.style.background = false;+ ct.captions.push(filmcraft_project::Caption {+ id: cid,+ start: Tick::ZERO,+ duration: r.tick_of(24),+ text: "BURNED IN".into(),+ speaker: None,+ cue_id: None,+ settings: String::new(),+ });+ let q = p.sequence_mut(seq).unwrap();+ q.video_tracks[0].items.push(v);+ q.caption_tracks.push(ct);+ let mut m = SourceMap::default();+ m.0.insert(matte, Arc::new(g));+ let p = Arc::new(p);+ let decode = |burn: bool| -> Vec<u8> {+ let path = tmp(if burn { "burn.mp4" } else { "noburn.mp4" });+ let s = ExportSettings { format: Format::H264, path: path.clone(), include_audio: false, burn_captions: burn, ..Default::default() };+ export(&p, seq, &s, &m, &Progress::default()).unwrap();+ let out = std::process::Command::new(ffmpeg)+ .args(["-v", "error", "-i", &path, "-vf", "select=eq(n\\,12)", "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"])+ .output()+ .unwrap();+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ assert_eq!(out.stdout.len(), (w * h * 3) as usize);+ out.stdout+ };+ let bright = |rgb: &[u8], y0: u32, y1: u32, x0: u32, x1: u32| -> usize {+ (y0..y1).flat_map(|y| (x0..x1).map(move |x| ((y * w + x) * 3) as usize)).filter(|&i| rgb[i] > 200 && rgb[i + 1] > 200 && rgb[i + 2] > 200).count()+ };+ let with = decode(true);+ let without = decode(false);+ let lower = bright(&with, h * 2 / 3, h, 0, w);+ assert!(lower > 300, "white caption text in the lower third: {lower}");+ assert_eq!(bright(&with, 0, h / 2, 0, w), 0, "nothing above the caption");+ assert_eq!(bright(&without, 0, h, 0, w), 0, "no burn-in unless asked");+ // centred: text on both sides of the centre line+ let (left, right) = (bright(&with, h * 2 / 3, h, 0, w / 2), bright(&with, h * 2 / 3, h, w / 2, w));+ assert!(left > 100 && right > 100, "{left} / {right}");+}diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.tomlindex 4b5594b21..9d2ee00c8 100644--- a/crates/render/Cargo.toml+++ b/crates/render/Cargo.toml@@ -17,6 +17,7 @@ filmcraft-frame = { workspace = true }filmcraft-media = { workspace = true }filmcraft-project = { workspace = true }filmcraft-audio-dsp = { workspace = true }+filmcraft-captions = { workspace = true }rayon = { workspace = true }[dev-dependencies]diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex aca70ee01..2d2c8ba06 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -44,11 +44,14 @@ pub struct RenderOptions {pub effects: bool,/// Nesting depth guard.pub depth: u32,+ /// Draw the sequence's visible caption tracks over the picture (Program monitor, burn-in on+ /// export). Never applies to nested sequences.+ pub captions: bool,}impl Default for RenderOptions {fn default() -> Self {- Self { scale: 1.0, effects: true, depth: 0 }+ Self { scale: 1.0, effects: true, depth: 0, captions: false }}}@@ -124,9 +127,22 @@ fn render_seq(project: &Project, seq: &Sequence, t: Tick, opts: RenderOptions, sblend::composite(&mut canvas, &layer, op, bl);}}+ if opts.captions && opts.depth == 0 {+ for o in caption_overlays(seq, t, w, h) {+ o.composite_onto(&mut canvas.px, w, h);+ }+ }canvas}+/// Rendered captions of the visible caption tracks at `t` for a `w`×`h` output.+pub fn caption_overlays(seq: &Sequence, t: Tick, w: usize, h: usize) -> Vec<filmcraft_captions::burn::Overlay> {+ if seq.caption_tracks.is_empty() {+ return Vec::new();+ }+ filmcraft_captions::burn::sequence_overlays(seq, t, w, h)+}+fn with_opacity(mut img: Image, op: f32) -> Image {img.scale_alpha(op);img@@ -214,7 +230,7 @@ pub(crate) fn item_layer(Image { w, h, px }}ItemKind::Sequence(nested) => {- let sub = RenderOptions { scale: want, effects: opts.effects, depth: opts.depth + 1 };+ let sub = RenderOptions { scale: want, effects: opts.effects, depth: opts.depth + 1, captions: false };render_seq(project, nested, mt, sub, sources)}ItemKind::AdjustmentLayer { .. } => return None,diff --git a/crates/render/src/plan.rs b/crates/render/src/plan.rsindex 993a24d21..3732f0452 100644--- a/crates/render/src/plan.rs+++ b/crates/render/src/plan.rs@@ -116,6 +116,15 @@ pub fn plan_frame(project: &Project, seq_id: ItemId, t: Tick, opts: RenderOption}push_item(project, seq, item, t, opts, sources, 1.0, &mut layers);}+ if opts.captions {+ for o in crate::caption_overlays(seq, t, w, h) {+ layers.push(PlanLayer {+ frame: Arc::new(VideoFrame::rgba_f32(o.w as u32, o.h as u32, o.px)),+ matrix: Affine::translate(o.x as f64, o.y as f64),+ opacity: 1.0,+ });+ }+ }FramePlan::Layers { width: w, height: h, layers }}