FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Importers: never crash — interchange, captions, project, text, automation
Brandon Thomasf0e6b128193e
diff --git a/crates/automation/src/bridge.rs b/crates/automation/src/bridge.rsindex b6c46beed..809ef8132 100644--- a/crates/automation/src/bridge.rs+++ b/crates/automation/src/bridge.rs@@ -42,7 +42,9 @@ impl BridgeClient {*guard = Some((BufReader::new(r), w));}let id = self.next_id.fetch_add(1, Ordering::Relaxed);- let conn = guard.as_mut().expect("connected");+ let Some(conn) = guard.as_mut() else {+ return Err(AutomationError::Bridge(format!("not connected to {}", self.addr)));+ };let line = format!("{}\n", json!({"id": id, "method": method, "params": params}));let res: Result<Value, AutomationError> = async {conn.1.write_all(line.as_bytes()).await.map_err(|e| AutomationError::Bridge(e.to_string()))?;diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rsindex 76428c9eb..b3537aaf4 100644--- a/crates/automation/src/lib.rs+++ b/crates/automation/src/lib.rs@@ -8,6 +8,8 @@//! (`filmcraft --control <port>`), so agents can also inspect, screenshot, click, drag, scroll//! and type in the live UI — every menu, panel, timeline gesture and keystroke.+#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]+pub mod bridge;pub mod server;diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rsindex 7ddf759f2..da5592be9 100644--- a/crates/captions/src/lib.rs+++ b/crates/captions/src/lib.rs@@ -15,6 +15,8 @@//! - **Burn-in:** [`burn`] lays a caption out with the track style and draws it with the//! `filmcraft-text` engine (Inter SemiBold, shaped and kerned).+#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]+pub mod burn;pub mod cea608;pub mod mcc;@@ -212,7 +214,7 @@ pub fn parse(bytes: &[u8], format: Format) -> Result<Document> {Format::Scc => scc::parse(&text),Format::Mcc => mcc::parse(&text),Format::Ttml | Format::Dfxp => ttml::parse(&text),- Format::Stl => unreachable!("handled above"),+ Format::Stl => stl::parse(bytes),}}diff --git a/crates/captions/src/mcc.rs b/crates/captions/src/mcc.rsindex 2c2be41dc..b5da4e295 100644--- a/crates/captions/src/mcc.rs+++ b/crates/captions/src/mcc.rs@@ -411,10 +411,10 @@ impl Dec708 {}fn put(&mut self, c: char) {let w = self.w();- if w.rows.is_empty() {- w.rows.push(String::new());+ match w.rows.last_mut() {+ Some(row) => row.push(c),+ None => w.rows.push(c.to_string()),}- w.rows.last_mut().expect("row").push(c);}fn bitmap(&mut self, m: u8, f: impl Fn(&mut Win)) {for (i, w) in self.win.iter_mut().enumerate() {diff --git a/crates/captions/src/stl.rs b/crates/captions/src/stl.rsindex 7b4a7b47c..ad248c72a 100644--- a/crates/captions/src/stl.rs+++ b/crates/captions/src/stl.rs@@ -251,7 +251,9 @@ pub fn parse(bytes: &[u8]) -> Result<Document> {if !sniff(bytes) {return Err(Error::NotFormat("EBU STL"));}- let rate = rate_of(&bytes[3..11]).expect("sniffed");+ let Some(rate) = bytes.get(3..11).and_then(rate_of) else {+ return Err(Error::NotFormat("EBU STL"));+ };let gsi = &bytes[..GSI];// start of programme (HHMMSSFF, ASCII)let tcp = ascii_field(&gsi[256..264]);diff --git a/crates/captions/src/ttml.rs b/crates/captions/src/ttml.rsindex 20e090f75..0eba7cb4d 100644--- a/crates/captions/src/ttml.rs+++ b/crates/captions/src/ttml.rs@@ -103,7 +103,7 @@ fn inline(text: &str) -> String {rest = &after[end + 1..];continue;}- let ch = rest.chars().next().expect("non-empty");+ let Some(ch) = rest.chars().next() else { break };if ch == '\n' {out.push_str("<br/>");} else {diff --git a/crates/interchange/src/edl.rs b/crates/interchange/src/edl.rsindex 756dcce1a..fb7b841f1 100644--- a/crates/interchange/src/edl.rs+++ b/crates/interchange/src/edl.rs@@ -224,9 +224,8 @@ fn parse(text: &str, report: &mut Report) -> Parsed {p.max_ff = p.max_ff.max(tc.f);p.any_df |= tc.df;}- let same = p.events.last().and_then(|e| e.lines.last()).is_some_and(|last| last.num == line.num);- if same {- p.events.last_mut().unwrap().lines.push(line);+ if let Some(e) = p.events.last_mut().filter(|e| e.lines.last().is_some_and(|last| last.num == line.num)) {+ e.lines.push(line);} else {p.events.push(Event { lines: vec![line], df, ..Default::default() });}@@ -944,8 +943,9 @@ pub(crate) fn export(p: &Project, seq_id: ItemId, opts: &ExportOptions, report:x.tc(x.rec_frames(l.rec.1)),));}- if let Some((reel, fps, entry)) = &ev.m2 {- let l = ev.lines.last().unwrap();+ if let Some((reel, fps, entry)) = &ev.m2+ && let Some(l) = ev.lines.last()+ {let sign = if *fps < 0.0 { "-" } else { "" };out.push_str(&format!("M2 {:<w$} {sign}{:05.1} {}\n", reel, fps.abs(), x.tc(src_tc(&x, l, *entry))));}diff --git a/crates/interchange/src/fcp7.rs b/crates/interchange/src/fcp7.rsindex 54b704227..dadd1a391 100644--- a/crates/interchange/src/fcp7.rs+++ b/crates/interchange/src/fcp7.rs@@ -781,8 +781,10 @@ impl Exp<'_, '_> {self.w.empty("sequence", &[("id", &sid)]);return;}- let it = self.p.item(id).expect("sequence item");- let seq = it.as_sequence().expect("sequence");+ let Some((it, seq)) = self.p.item(id).and_then(|it| Some((it, it.as_sequence()?))) else {+ self.w.empty("sequence", &[("id", &sid)]);+ return;+ };self.writing.insert(id);let rate = seq.settings.frame_rate;let df = seq.settings.drop_frame && rate.supports_drop_frame();diff --git a/crates/interchange/src/fcpxml.rs b/crates/interchange/src/fcpxml.rsindex 643391642..ad8b7bbed 100644--- a/crates/interchange/src/fcpxml.rs+++ b/crates/interchange/src/fcpxml.rs@@ -715,7 +715,10 @@ impl Exp<'_, '_> {if let Some(r) = self.assets.get(&item) {return r.id.clone();}- let m = item_media(self.p, item).expect("media");+ let Some(m) = item_media(self.p, item) else {+ self.report.warn("clip without media skipped");+ return String::new();+ };let name = self.p.item(item).map(|i| i.name.clone()).unwrap_or_default();let fmt = m.info.video.as_ref().map(|v| self.format(m.interpret.frame_rate.unwrap_or(v.frame_rate), v.width, v.height));let id = self.rid();@@ -748,7 +751,10 @@ impl Exp<'_, '_> {if let Some(r) = self.medias.get(&item) {return r.id.clone();}- let s = self.p.sequence(item).expect("sequence");+ let Some(s) = self.p.sequence(item) else {+ self.report.warn("missing nested sequence skipped");+ return String::new();+ };let fmt = self.format(s.settings.frame_rate, s.settings.width, s.settings.height);let id = self.rid();self.medias.insert(item, Res { id: id.clone() });@@ -771,7 +777,7 @@ impl Exp<'_, '_> {}fn sequence_xml(&mut self, seq_id: ItemId, fmt: &str, indent: usize) -> String {- let seq = self.p.sequence(seq_id).expect("sequence");+ let Some(seq) = self.p.sequence(seq_id) else { return String::new() };let rate = seq.settings.frame_rate;let df = seq.settings.drop_frame && rate.supports_drop_frame();let tc0 = rate.tick_of(seq.start_timecode);@@ -963,8 +969,8 @@ impl Exp<'_, '_> {} else {self.media(base)};- let s = self.p.sequence(base).unwrap();- ("ref-clip", r, s.settings.frame_rate.tick_of(s.start_timecode))+ let origin = self.p.sequence(base).map(|s| s.settings.frame_rate.tick_of(s.start_timecode)).unwrap_or(Tick::ZERO);+ ("ref-clip", r, origin)} else {let r = self.asset(base, rate);let m = item_media(self.p, base);diff --git a/crates/interchange/src/lib.rs b/crates/interchange/src/lib.rsindex 786d82592..61f46275a 100644--- a/crates/interchange/src/lib.rs+++ b/crates/interchange/src/lib.rs@@ -23,6 +23,8 @@//! This crate is L2: it does no file I/O. Media references are strings (absolute paths, or paths//! resolved against the `base_dir` passed to the importer); the engine probes/relinks them.+#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]+pub mod aaf;pub mod ale;pub mod edl;@@ -271,7 +273,7 @@ pub fn import_with(bytes: &[u8], format: Format, opts: &ImportOptions) -> ResultFormat::Fcp7Xml => fcp7::import(&text, opts, &mut report)?,Format::Fcpxml => fcpxml::import(&text, opts, &mut report)?,Format::Otio => otio::import(&text, opts, &mut report)?,- Format::Aaf | Format::Omf => unreachable!("handled above"),+ Format::Aaf | Format::Omf => return Err(Error::Other("AAF / OMF are binary documents".into())),};Ok((imported, report))}@@ -388,7 +390,7 @@ pub fn export(project: &Project, sequence: ItemId, format: Format, opts: &ExportFormat::Fcp7Xml => fcp7::export(project, sequence, opts, &mut report)?,Format::Fcpxml => fcpxml::export(project, sequence, opts, &mut report)?,Format::Otio => otio::export(project, sequence, opts, &mut report)?,- Format::Aaf | Format::Omf => unreachable!("handled above"),+ Format::Aaf | Format::Omf => return Err(Error::Other("AAF / OMF are binary documents".into())),};Ok((text.into_bytes(), report))}diff --git a/crates/interchange/src/otio.rs b/crates/interchange/src/otio.rsindex 0c58d9fc9..6cc56dd7b 100644--- a/crates/interchange/src/otio.rs+++ b/crates/interchange/src/otio.rs@@ -138,8 +138,7 @@ pub(crate) fn export(p: &Project, seq_id: ItemId, opts: &ExportOptions, report:impl Exp<'_, '_> {fn seq_meta(&self, id: ItemId) -> Value {- let it = self.p.item(id).unwrap();- let s = it.as_sequence().unwrap();+ let Some((it, s)) = self.p.item(id).and_then(|it| Some((it, it.as_sequence()?))) else { return json!({}) };json!({"item": id.0,"label": it.label,@@ -152,7 +151,10 @@ impl Exp<'_, '_> {/// The `Stack` for a sequence; `range` = (source in, duration) when nested in a track.fn stack_json(&mut self, id: ItemId, name: &str, range: Option<(Tick, Tick, FrameRate)>) -> Value {- let seq = self.p.sequence(id).unwrap();+ let Some(seq) = self.p.sequence(id) else {+ self.report.warn("missing nested sequence skipped");+ return json!({"OTIO_SCHEMA": "Stack.1", "name": name, "children": [], "effects": [], "markers": [], "enabled": true, "metadata": {}});+ };let rate = seq.settings.frame_rate;let mut tracks = Vec::new();for kind in [TrackKind::Video, TrackKind::Audio] {diff --git a/crates/interchange/src/wav.rs b/crates/interchange/src/wav.rsindex 8200c2b92..22b996691 100644--- a/crates/interchange/src/wav.rs+++ b/crates/interchange/src/wav.rs@@ -16,13 +16,14 @@ pub fn wav_header(data_len: u32, channels: u16, sample_rate: u32, bits: u16) ->let block = channels.max(1) * bits.div_ceil(8);let mut v = Vec::with_capacity(44);v.extend_from_slice(b"RIFF");- v.extend_from_slice(&(36 + data_len + (data_len & 1)).to_le_bytes());+ // Saturating: a huge source (data_len saturated by the caller) must not overflow.+ v.extend_from_slice(&36u32.saturating_add(data_len).saturating_add(data_len & 1).to_le_bytes());v.extend_from_slice(b"WAVEfmt ");v.extend_from_slice(&16u32.to_le_bytes());v.extend_from_slice(&1u16.to_le_bytes());v.extend_from_slice(&channels.max(1).to_le_bytes());v.extend_from_slice(&sample_rate.to_le_bytes());- v.extend_from_slice(&(sample_rate * block as u32).to_le_bytes());+ v.extend_from_slice(&sample_rate.saturating_mul(block as u32).to_le_bytes());v.extend_from_slice(&block.to_le_bytes());v.extend_from_slice(&bits.to_le_bytes());v.extend_from_slice(b"data");@@ -159,6 +160,14 @@ fn from_extended(b: [u8; 10]) -> f64 {#[cfg(test)]mod tests {+ /// A mutated EDL whose clip ran for days produced an OMF descriptor for more than 4 GiB of+ /// PCM: the RIFF size field overflowed ("attempt to add with overflow").+ #[test]+ fn huge_wav_header_saturates() {+ let h = super::wav_header(u32::MAX, 2, u32::MAX, 24);+ assert_eq!(&h[4..8], &u32::MAX.to_le_bytes());+ }+use super::*;#[test]diff --git a/crates/interchange/src/xml.rs b/crates/interchange/src/xml.rsindex 3c1cd7a51..6bd1c51dc 100644--- a/crates/interchange/src/xml.rs+++ b/crates/interchange/src/xml.rs@@ -57,7 +57,7 @@ impl XmlWriter {}pub fn close(&mut self) {- let name = self.stack.pop().expect("close without open");+ let Some(name) = self.stack.pop() else { return };self.indent();let _ = writeln!(self.out, "</{name}>");}diff --git a/crates/project/src/graphic.rs b/crates/project/src/graphic.rsindex e4d58e5a1..1ecf6292d 100644--- a/crates/project/src/graphic.rs+++ b/crates/project/src/graphic.rs@@ -360,9 +360,23 @@ fn set(e: &mut EffectInstance, id: &str, v: ParamValue) {e.params.insert(id.to_string(), Param::new(v));}+/// A fresh instance of a built-in layer effect (bare, with no parameters, if it were ever+/// missing from the registry; `set` adds the ones the constructors fill in).+fn layer_instance(id: &str) -> EffectInstance {+ crate::effect::find_effect(id).map(crate::effect::EffectDef::instance).unwrap_or_else(|| EffectInstance {+ effect: id.to_string(),+ enabled: true,+ params: Default::default(),+ masks: Vec::new(),+ post_fader: false,+ essential: false,+ layer: None,+ })+}+/// A new text layer at `position` (graphic canvas pixels).pub fn new_text_layer(text: &str, position: Vec2, size: f64) -> EffectInstance {- let mut e = crate::effect::find_effect(TEXT_LAYER).expect("registered").instance();+ let mut e = layer_instance(TEXT_LAYER);set(&mut e, "text", ParamValue::Text(text.into()));set(&mut e, "position", ParamValue::Vec2(position));set(&mut e, "size", ParamValue::Float(size));@@ -392,7 +406,7 @@ pub fn reset_layer_params(e: &mut EffectInstance) {/// A new shape layer centred at `position`.pub fn new_shape_layer(shape: u32, position: Vec2, size: Vec2, points: Vec<[f32; 2]>) -> EffectInstance {- let mut e = crate::effect::find_effect(SHAPE_LAYER).expect("registered").instance();+ let mut e = layer_instance(SHAPE_LAYER);set(&mut e, "shape", ParamValue::Choice(shape.min(3)));set(&mut e, "position", ParamValue::Vec2(position));set(&mut e, "size", ParamValue::Vec2(size));diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rsindex f85720ab4..35f3a01cc 100644--- a/crates/project/src/lib.rs+++ b/crates/project/src/lib.rs@@ -7,6 +7,8 @@//!//! Time: timeline positions are sequence ticks; `source_in` is media time.+#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]+pub mod caption;pub mod effect;pub mod essential;@@ -1172,8 +1174,10 @@ impl Project {if !self.items.contains_key(&id) || !self.root.remove_item(id) {continue;}- self.root.find_bin_mut(target).expect("checked above").children.push(BinEntry::Item(id));- moved += 1;+ if let Some(b) = self.root.find_bin_mut(target) {+ b.children.push(BinEntry::Item(id));+ moved += 1;+ }}Some(moved)}diff --git a/crates/project/src/mixer.rs b/crates/project/src/mixer.rsindex fccabf104..8a4a41a37 100644--- a/crates/project/src/mixer.rs+++ b/crates/project/src/mixer.rs@@ -293,7 +293,7 @@ impl Track {LANE_PAN => self.pan = v.clamp(-100.0, 100.0),LANE_MUTE => self.muted = v >= 0.5,k if PAN51_LANES.contains(&k) => {- let i = lane_info(k).expect("pan51 lanes have info");+ let Some(i) = lane_info(k) else { return false };let v = v.clamp(i.min, i.max);self.mixer.lanes.entry(k.to_string()).or_insert_with(|| Param::new(ParamValue::Float(v))).value = ParamValue::Float(v);}diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rsindex f2147d465..d0ecb2c19 100644--- a/crates/text/src/fonts.rs+++ b/crates/text/src/fonts.rs@@ -293,7 +293,10 @@ pub fn system_scanned() -> bool {db().read().unwrap_or_else(|e| e.into_inner()).scanned}-/// A face by id (panics never: unknown ids give the default face).+/// A face by id (unknown ids give the default face).+// The bundled faces are compiled in (`include_bytes!`) and registered when the database is+// created, so `faces` is never empty.+#[allow(clippy::expect_used)]pub fn face(id: FaceId) -> Arc<Face> {let d = db().read().unwrap_or_else(|e| e.into_inner());d.faces.get(id).or_else(|| d.faces.first()).cloned().expect("bundled fonts present")@@ -369,7 +372,7 @@ pub fn resolve(family: &str, style: &str) -> Resolved {return r;}}- let mut r = resolve_in(DEFAULT_FAMILY, style).expect("Inter is bundled");+ let mut r = resolve_in(DEFAULT_FAMILY, style).unwrap_or(Resolved { face: 0, synth_bold: false, synth_italic: false, missing: true });r.missing = !family.is_empty() && !family.eq_ignore_ascii_case(DEFAULT_FAMILY);r}@@ -384,13 +387,10 @@ fn resolve_in(family: &str, style: &str) -> Option<Resolved> {return Some(Resolved { face: f.id, synth_bold: false, synth_italic: false, missing: false });}let (w, it) = style_wants(style);- let best = fam- .iter()- .min_by_key(|f| {- let italic_pen = if f.info.italic == it { 0 } else { 1000 };- italic_pen + (f.info.weight as i32 - w as i32).unsigned_abs()- })- .expect("non-empty");+ let best = fam.iter().min_by_key(|f| {+ let italic_pen = if f.info.italic == it { 0 } else { 1000 };+ italic_pen + (f.info.weight as i32 - w as i32).unsigned_abs()+ })?;Some(Resolved { face: best.id, synth_bold: w >= 600 && best.info.weight <= 500, synth_italic: it && !best.info.italic, missing: false })}diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rsindex 974c8b6bf..6d205ed13 100644--- a/crates/text/src/layout.rs+++ b/crates/text/src/layout.rs@@ -460,7 +460,7 @@ fn paragraph(text: &str, base: usize, sty: &Styles, para: &ParagraphStyle) -> Velast_ok = Some(p);break;}- let b = last_ok.take().expect("checked");+ let Some(b) = last_ok.take() else { break };ranges.push(start..b);start = b;}@@ -685,9 +685,9 @@ pub fn layout_rich_uncached(text: &str, style: &TextStyle, runs: &[StyleRun], pax0 = 0.0;x1 = x1.max(w);}- let first = &lay.lines[0];- let last = lay.lines.last().expect("at least one line");- lay.bounds = [x0, first.baseline - first.ascent, x1.max(x0), last.baseline + last.descent];+ if let (Some(first), Some(last)) = (lay.lines.first(), lay.lines.last()) {+ lay.bounds = [x0, first.baseline - first.ascent, x1.max(x0), last.baseline + last.descent];+ }lay}diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rsindex be956e269..62517076b 100644--- a/crates/text/src/lib.rs+++ b/crates/text/src/lib.rs@@ -12,6 +12,8 @@//! under any affine transform.//! - [`mask`]: strokes (outer/centre/inner via a Euclidean distance transform), blur, offsets.+#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]+pub mod fonts;pub mod layout;pub mod mask;diff --git a/crates/text/src/raster.rs b/crates/text/src/raster.rsindex 33bf2f4dc..adeb78650 100644--- a/crates/text/src/raster.rs+++ b/crates/text/src/raster.rs@@ -63,8 +63,10 @@ impl Path {if !self.open {self.move_to(self.cur.0, self.cur.1);}- if (x, y) != self.cur {- self.contours.last_mut().expect("open contour").push((x, y));+ if (x, y) != self.cur+ && let Some(c) = self.contours.last_mut()+ {+ c.push((x, y));}self.cur = (x, y);}