Merge branch 'codex/filmcraft-shared-dng-raw' into codex/filmcraft-shared-dng-opcodes

This commit is contained in:
FredApps
2026-11-16 10:55:28 +01:00
14 changed files with 1106 additions and 206 deletions
Generated
+58 -14
View File
@@ -1195,10 +1195,10 @@ dependencies = [
[[package]]
name = "craft-captions"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
source = "git+https://github.com/storytold/craft-libs?rev=47ce856487bf1c2d64ef2936822f4e9e09997c80#47ce856487bf1c2d64ef2936822f4e9e09997c80"
dependencies = [
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)",
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47ce856487bf1c2d64ef2936822f4e9e09997c80)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47ce856487bf1c2d64ef2936822f4e9e09997c80)",
"thiserror 2.0.21",
]
@@ -1252,6 +1252,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=f01f6aca3afdf664b6c3e651e8e58caddc701c62#f01f6aca3afdf664b6c3e651e8e58caddc701c62"
dependencies = [
"skrifa 0.47.0",
"thiserror 2.0.21",
"windows-registry",
]
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
@@ -1345,6 +1355,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=47ce856487bf1c2d64ef2936822f4e9e09997c80#47ce856487bf1c2d64ef2936822f4e9e09997c80"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-time"
version = "0.1.0"
@@ -1357,9 +1376,11 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
source = "git+https://github.com/storytold/craft-libs?rev=47ce856487bf1c2d64ef2936822f4e9e09997c80#47ce856487bf1c2d64ef2936822f4e9e09997c80"
dependencies = [
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47ce856487bf1c2d64ef2936822f4e9e09997c80)",
"serde",
"serde_json",
]
[[package]]
@@ -1367,7 +1388,7 @@ name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=654e8d55e16b349fba04f5a48e8da221680ee7e3#654e8d55e16b349fba04f5a48e8da221680ee7e3"
dependencies = [
"craft-time",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=654e8d55e16b349fba04f5a48e8da221680ee7e3)",
]
[[package]]
@@ -1385,7 +1406,7 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"serde",
"skrifa",
"skrifa 0.44.0",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
@@ -1452,9 +1473,10 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
source = "git+https://github.com/storytold/craft-libs?rev=47ce856487bf1c2d64ef2936822f4e9e09997c80#47ce856487bf1c2d64ef2936822f4e9e09997c80"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
@@ -2068,7 +2090,7 @@ dependencies = [
"parking_lot",
"profiling",
"self_cell",
"skrifa",
"skrifa 0.44.0",
"smallvec",
"unicode-bidi",
"unicode-general-category",
@@ -2536,7 +2558,7 @@ version = "0.20.1"
dependencies = [
"craft-aaf",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)",
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47ce856487bf1c2d64ef2936822f4e9e09997c80)",
"filmcraft-cfb",
"filmcraft-color",
"filmcraft-geom",
@@ -2691,9 +2713,10 @@ dependencies = [
name = "filmcraft-text"
version = "0.20.1"
dependencies = [
"craft-font-catalog",
"filmcraft-color",
"harfrust",
"skrifa",
"skrifa 0.44.0",
"tempfile",
"unicode-bidi",
"unicode-linebreak",
@@ -2704,7 +2727,7 @@ dependencies = [
name = "filmcraft-time"
version = "0.20.1"
dependencies = [
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)",
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47ce856487bf1c2d64ef2936822f4e9e09997c80)",
]
[[package]]
@@ -3365,7 +3388,7 @@ dependencies = [
"hashbrown 0.17.1",
"log",
"peniko",
"skrifa",
"skrifa 0.44.0",
"smallvec",
"vello_common",
]
@@ -3574,7 +3597,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
"smallvec",
]
@@ -5842,6 +5865,17 @@ dependencies = [
"once_cell",
]
[[package]]
name = "read-fonts"
version = "0.44.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8"
dependencies = [
"bytemuck",
"font-types",
"once_cell",
]
[[package]]
name = "reborrow"
version = "0.5.5"
@@ -6506,7 +6540,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
dependencies = [
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
]
[[package]]
name = "skrifa"
version = "0.47.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f"
dependencies = [
"bytemuck",
"read-fonts 0.44.0",
]
[[package]]
+3 -2
View File
@@ -63,6 +63,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs"
# Shared YUV4MPEG2 parser and frame index.
craft-jsonrpc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0c15f7c74913880da6bae5927b95f798c2ecf3c3", features = ["async-lines"] }
craft-fcproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6bd1c3dc357f012ddb31c6799ad2e36a1596003d" }
craft-font-catalog = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f01f6aca3afdf664b6c3e651e8e58caddc701c62", default-features = false }
craft-control-protocol = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "99d0a6eca48082183a9d125cb4ef1a1707576070" }
craft-y4m = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "25c7a8959cf70cf8c3f076d05baadb0990710569" }
# Shared lossless JPEG decoding for DNG.
@@ -79,8 +80,8 @@ craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-lib
# The video codecs (including H.264 encode, APV encode, ProRes, DNxHD / DNxHR and decoders), on the same commit as craft-media.
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82062077bba679ba5236e2d1a391f02d1533cbab", features = ["h264-decode", "h264-encode", "hevc-decode", "vp9-decode", "av1-decode", "vp8-decode", "mpeg2", "apv", "prores", "dnx", "threads"] }
# Exact time, EDL / ALE and the interchange report; serde for the project file's time fields.
craft-timeline = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", features = ["serde"] }
craft-captions = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-timeline = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47ce856487bf1c2d64ef2936822f4e9e09997c80", features = ["serde"] }
craft-captions = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47ce856487bf1c2d64ef2936822f4e9e09997c80" }
# ui
# Shared frontend components; keep this dependency above the engine boundary.
+16
View File
@@ -4,6 +4,11 @@ use crate::tiff::{Ifd, Tiff};
use crate::{Error, Result};
pub use craft_raw::dng_lines::{MAX_SAMPLES, PHOTOMETRIC_CFA, PHOTOMETRIC_LINEAR_RAW, RawImage, RawLayout};
/// Unpack `w` × `h` × `spp` uncompressed samples of `bits` bits, as the shared decoder does.
pub fn unpack(bytes: &[u8], w: usize, h: usize, spp: usize, bits: u32, big_endian: bool) -> Result<Vec<u16>> {
craft_raw::dng_lines::unpack(bytes, w, h, spp, bits, big_endian).map_err(error)
}
fn error(e: craft_raw::dng_lines::Error) -> Error {
match e {
craft_raw::dng_lines::Error::NotTiff => Error::NotDng,
@@ -26,3 +31,14 @@ pub fn layout(t: &Tiff, ifd: &Ifd) -> Result<RawLayout> {
pub fn read(t: &Tiff, ifd: &Ifd) -> Result<RawImage> {
craft_raw::dng_lines::read(&t.inner(), ifd).map_err(error)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unpack_keeps_its_public_signature_and_errors() {
assert_eq!(unpack(&[0x12, 0x34], 2, 1, 1, 8, true).unwrap(), [0x12, 0x34]);
assert!(matches!(unpack(&[0x12], 1, 1, 1, 0, false), Err(Error::Malformed(_))));
}
}
+42 -9
View File
@@ -309,14 +309,34 @@ pub(crate) fn set_props_keyed(
label: &str,
merge: Option<&str>,
keyframe: bool,
) -> Result<Vec<(String, usize)>> {
set_props_on(s, &[(clip, eidx)], props, tl, label, merge, keyframe)
}
/// [`set_props_keyed`] on several layers (each a clip and the effect index of one of its layers)
/// as one undo step: every layer gets the same values, each at its own clip's media time, and an
/// error on any of them changes none (#4625). Returns the first layer's keyframe counts.
fn set_props_on(
s: &mut Session,
targets: &[(ClipId, usize)],
props: &serde_json::Map<String, Value>,
tl: Tick,
label: &str,
merge: Option<&str>,
keyframe: bool,
) -> Result<Vec<(String, usize)>> {
let props = props.clone();
let mut counts = Vec::new();
s.edit_sequence_as(label, merge, |q, _, _| {
let (_, it) = q.find_item_mut(clip).ok_or(filmcraft_edit::EditError::NoItem(clip))?;
let mt = it.source_time_at(tl.clamp(it.start, it.end() - Tick(1)));
let e = it.effects.get_mut(eidx).ok_or_else(|| bad("graphics.set", "no such layer"))?;
counts = apply_props(e, &props, mt, keyframe)?;
for (i, &(clip, eidx)) in targets.iter().enumerate() {
let (_, it) = q.find_item_mut(clip).ok_or(filmcraft_edit::EditError::NoItem(clip))?;
let mt = it.source_time_at(tl.clamp(it.start, it.end() - Tick(1)));
let e = it.effects.get_mut(eidx).ok_or_else(|| bad("graphics.set", "no such layer"))?;
let c = apply_props(e, &props, mt, keyframe)?;
if i == 0 {
counts = c;
}
}
Ok(())
})?;
Ok(counts)
@@ -1112,20 +1132,33 @@ pub fn commands() -> Vec<CommandSpec> {
"Set Graphic Properties",
&[],
None,
r##"{"clip":id?,"layer":n|name?,"props":{"font":"Inter","font_style":"Bold","size":120,"align":"center","tracking":50,"leading":0,"fill_color":"#ffcc00","stroke":true,"stroke_width":6,"background":true,"shadow":true,"position":[x,y],"scale":100,"rotation":0,"opacity":100,…},"time":ticks? (timeline time, default the playhead: a property that is already animated gets or changes a keyframe there, any other changes its fixed value),"keyframe":bool? (true: every property in `props` gets a keyframe at `time` and becomes animated; the result lists each one's keyframe count),"merge":bool?,"begin":bool?}"##,
r##"{"clip":id?,"clips":[id]? (instead of `clip`: the same props on that layer of each listed graphic clip, as one undo step),"layer":n|name?,"props":{"font":"Inter","font_style":"Bold","size":120,"align":"center","tracking":50,"leading":0,"fill_color":"#ffcc00","stroke":true,"stroke_width":6,"background":true,"shadow":true,"position":[x,y],"scale":100,"rotation":0,"opacity":100,…},"time":ticks? (timeline time, default the playhead: a property that is already animated gets or changes a keyframe there, any other changes its fixed value),"keyframe":bool? (true: every property in `props` gets a keyframe at `time` and becomes animated; the result lists each one's keyframe count),"merge":bool?,"begin":bool?}"##,
has_graphic,
|s, p| {
let clip = target_clip(s, p).ok_or_else(|| bad("graphics.set", "no graphic clip"))?;
let (_, ei) = layer_effect_index(s, clip, p)?;
// `clips`: several selected text clips take a property change together (#4625)
let clips = if p.get("clips").is_some() {
let mut clips = crate::commands::target_clips_p(s, p, "graphics.set")?.unwrap_or_default();
let mut seen = std::collections::HashSet::new();
clips.retain(|c| seen.insert(*c));
let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;
if let Some(c) = clips.iter().find(|c| !is_graphic(s, seq, **c)) {
return Err(bad("graphics.set", format!("clip {} is not a graphic clip", c.0)));
}
clips
} else {
vec![target_clip(s, p).ok_or_else(|| bad("graphics.set", "no graphic clip"))?]
};
let targets = clips.iter().map(|&c| layer_effect_index(s, c, p).map(|(_, ei)| (c, ei))).collect::<Result<Vec<_>>>()?;
let props = p.get("props").and_then(Value::as_object).ok_or_else(|| bad("graphics.set", "need `props`"))?.clone();
let tl = time_p(s, p, "").unwrap_or_else(|| s.playhead());
// `merge`: a drag of a property is one undo step; `begin` starts a new one (#201)
let merge = bool_p(p, "merge").unwrap_or(false).then(|| format!("graphics.set:{}:{ei}", clip.0));
let key = targets.iter().map(|(c, ei)| format!("{}:{ei}", c.0)).collect::<Vec<_>>().join(",");
let merge = bool_p(p, "merge").unwrap_or(false).then(|| format!("graphics.set:{key}"));
if bool_p(p, "begin").unwrap_or(false) {
s.history.merge_key = None;
}
let keyframe = bool_p(p, "keyframe").unwrap_or(false);
let counts = set_props_keyed(s, clip, ei, &props, tl, "Change Graphic Property", merge.as_deref(), keyframe)?;
let counts = set_props_on(s, &targets, &props, tl, "Change Graphic Property", merge.as_deref(), keyframe)?;
// unchanged for a call without `keyframe`: nothing to report
if keyframe {
Ok(json!({"keyframes": counts.into_iter().map(|(k, n)| (k, json!(n))).collect::<serde_json::Map<_, _>>()}))
+46
View File
@@ -210,6 +210,52 @@ fn a_property_drag_is_one_undo_step() {
assert_eq!(color(&s)[0], 0.0, "and then the first");
}
/// #4625: `graphics.set` with `clips` sets the same properties on that layer of every listed
/// graphic clip as one undo step (a drag too), and a target it cannot change changes none.
#[test]
fn set_with_clips_changes_every_listed_graphic_in_one_undo_step() {
let mut s = demo();
let clips: Vec<u64> = (0..3).map(|i| s.execute("graphics.newText", json!({"text": format!("T{i}")})).unwrap()["clip"].as_u64().unwrap()).collect();
for (clip, size) in clips.iter().zip([60, 80, 90]) {
s.execute("graphics.set", json!({"clip": clip, "layer": 0, "props": {"size": size}})).unwrap();
}
let size = |s: &Session, clip: u64| -> f64 {
let (_, it) = s.active_sequence().unwrap().find_item(ClipId(clip)).unwrap();
it.effects.iter().find(|e| e.effect == "graphic_text").unwrap().param("size").unwrap().value_at(Tick::ZERO).as_f64().unwrap()
};
let before = s.project.clone();
let n = s.history.undo.len();
for (i, v) in [120, 130, 140].into_iter().enumerate() {
s.execute(
"graphics.set",
json!({"clips": [clips[0], clips[1], clips[0]], "layer": 0, "props": {"size": v, "font": "Inter"}, "merge": true, "begin": i == 0}),
)
.unwrap();
}
assert_eq!((size(&s, clips[0]), size(&s, clips[1]), size(&s, clips[2])), (140.0, 140.0, 90.0));
assert_eq!(s.history.undo.len(), n + 1, "a drag over several clips is one undo step");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.project, before, "one undo restores each clip's own size");
// a clip that is not a graphic, a missing clip or layer, or `clip` with `clips`: nothing changes
let video = s.active_sequence().unwrap().video_tracks[0].items[0].id.0;
for p in [
json!({"clips": [clips[0], video], "layer": 0, "props": {"size": 50}}),
json!({"clips": [clips[0], u64::MAX], "layer": 0, "props": {"size": 50}}),
json!({"clips": [clips[0], clips[1]], "layer": 1, "props": {"size": 50}}),
json!({"clips": [], "layer": 0, "props": {"size": 50}}),
json!({"clip": clips[0], "clips": [clips[1]], "layer": 0, "props": {"size": 50}}),
] {
assert!(s.execute("graphics.set", p.clone()).is_err(), "{p}");
assert_eq!(s.project, before, "{p}");
}
// the second clip's layer 1 is a shape: the text property fails there and the first clip keeps its size
s.execute("graphics.newShape", json!({"clip": clips[1], "shape": "rectangle"})).unwrap();
s.execute("graphics.newText", json!({"clip": clips[0], "text": "Second"})).unwrap();
let before = s.project.clone();
assert!(s.execute("graphics.set", json!({"clips": [clips[0], clips[1]], "layer": 1, "props": {"font": "Inter"}})).is_err());
assert_eq!(s.project, before);
}
#[test]
fn align_and_distribute_layers() {
let mut s = demo();
+1 -1
View File
@@ -10,13 +10,13 @@ rust-version.workspace = true
workspace = true
[dependencies]
craft-timeline = { workspace = true, features = ["otio"] }
filmcraft-time = { workspace = true }
filmcraft-geom = { workspace = true }
filmcraft-color = { workspace = true }
filmcraft-media = { workspace = true }
filmcraft-project = { workspace = true }
filmcraft-cfb = { workspace = true }
craft-timeline = { workspace = true }
craft-audio = { workspace = true, features = ["pcm-encode"] }
craft-aaf = { workspace = true }
serde = { workspace = true }
+3
View File
@@ -181,6 +181,7 @@ pub fn resolve_url(reference: &str, base_dir: Option<&str>) -> String {
}
/// A relative path written as a URL (the inverse of [`resolve_url`]'s decoding).
#[cfg(test)]
pub(crate) fn relative_url(path: &str) -> String {
percent_encode_path(path)
}
@@ -280,6 +281,7 @@ pub(crate) fn rate_from_timebase(timebase: i64, ntsc: bool) -> FrameRate {
}
/// Snap a floating rate (OTIO) to an exact rate.
#[cfg(test)]
pub(crate) fn rate_from_f64(r: f64) -> FrameRate {
if r <= 0.0 || !r.is_finite() || r > MAX_RATE as f64 {
return FrameRate::FPS_24;
@@ -430,6 +432,7 @@ impl Builder {
self.media.get(key).copied()
}
#[cfg(test)]
pub fn register_media(&mut self, key: &str, id: ItemId) {
self.media.insert(key.to_string(), id);
}
+25 -5
View File
@@ -32,10 +32,13 @@ pub mod essence;
pub mod fcp7;
pub mod fcpxml;
pub mod omf;
pub mod otio;
#[cfg(test)]
#[allow(dead_code, reason = "Legacy parser fixtures retained for their regression tests")]
mod otio;
mod common;
mod comp;
mod timeline_model;
pub use craft_audio::essence_pcm as wav;
mod xml;
@@ -232,14 +235,21 @@ pub const MAX_REPORT_ENTRIES: usize = 2000;
impl Report {
pub fn push(&mut self, level: Level, message: impl Into<String>) {
self.push_n(level, message, 1);
}
/// Record `count` occurrences of one message in a single step.
pub fn push_n(&mut self, level: Level, message: impl Into<String>, count: u32) {
if count == 0 {
return;
}
let mut message = message.into();
if self.entries.len() >= MAX_REPORT_ENTRIES && !self.entries.iter().any(|e| e.level == level && e.message == message) {
message = "further diagnostics omitted".into();
}
if let Some(e) = self.entries.iter_mut().find(|e| e.level == level && e.message == message) {
e.count += 1;
e.count = e.count.saturating_add(count);
} else {
self.entries.push(ReportEntry { level, message, count: 1 });
self.entries.push(ReportEntry { level, message, count });
}
}
pub fn warn(&mut self, message: impl Into<String>) {
@@ -324,7 +334,7 @@ pub fn import_with(bytes: &[u8], format: Format, opts: &ImportOptions) -> Result
Format::Edl => edl::import(&text, opts, &mut report)?,
Format::Fcp7Xml => fcp7::import(&text, opts, &mut report)?,
Format::Fcpxml => fcpxml::import(&text, opts, &mut report)?,
Format::Otio => otio::import(&text, opts, &mut report)?,
Format::Otio => timeline_model::import_otio(&text, opts, &mut report)?,
Format::Aaf | Format::Omf => return Err(Error::Other("AAF / OMF are binary documents".into())),
};
let mut imported = imported;
@@ -478,7 +488,7 @@ pub fn export(project: &Project, sequence: ItemId, format: Format, opts: &Export
Format::Edl => edl::export(project, sequence, opts, &mut report)?,
Format::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::Otio => timeline_model::export_otio(project, sequence, opts, &mut report)?,
Format::Aaf | Format::Omf => return Err(Error::Other("AAF / OMF are binary documents".into())),
};
Ok((text.into_bytes(), report))
@@ -652,4 +662,14 @@ mod report_tests {
r.warn("line 0 is not recognised");
assert_eq!(r.entries[0].count, 2);
}
#[test]
fn repeated_counts_merge_in_one_step() {
let mut r = Report::default();
r.push_n(Level::Info, "skipped", 0);
assert!(r.entries.is_empty());
r.push_n(Level::Info, "skipped", 3);
r.push_n(Level::Info, "skipped", u32::MAX);
assert_eq!((r.entries.len(), r.entries[0].count), (1, u32::MAX));
}
}
+817
View File
@@ -0,0 +1,817 @@
//! Conversion between FilmCraft effect values and the shared timeline model.
use craft_timeline::model as shared;
use filmcraft_project as film;
use filmcraft_time::Tick;
fn to_value(value: &film::ParamValue) -> Result<shared::ParamValue, serde_json::Error> {
Ok(match value {
film::ParamValue::Float(v) => shared::ParamValue::Float(*v),
film::ParamValue::Vec2(v) => shared::ParamValue::Vec2(shared::Vec2::new(v.x, v.y)),
film::ParamValue::Color(v) => shared::ParamValue::Color(*v),
film::ParamValue::Bool(v) => shared::ParamValue::Bool(*v),
film::ParamValue::Choice(v) => shared::ParamValue::Choice(*v),
film::ParamValue::Text(v) => shared::ParamValue::Text(v.clone()),
film::ParamValue::Curve(_) | film::ParamValue::Path(_) => shared::ParamValue::Opaque(serde_json::to_string(value)?),
})
}
fn from_value(value: &shared::ParamValue) -> Result<film::ParamValue, serde_json::Error> {
Ok(match value {
shared::ParamValue::Float(v) => film::ParamValue::Float(*v),
shared::ParamValue::Vec2(v) => film::ParamValue::Vec2(filmcraft_geom::Vec2::new(v.x, v.y)),
shared::ParamValue::Color(v) => film::ParamValue::Color(*v),
shared::ParamValue::Bool(v) => film::ParamValue::Bool(*v),
shared::ParamValue::Choice(v) => film::ParamValue::Choice(*v),
shared::ParamValue::Text(v) => film::ParamValue::Text(v.clone()),
shared::ParamValue::Opaque(v) => serde_json::from_str(v)?,
})
}
fn to_interp(value: film::Interpolation) -> shared::Interpolation {
match value {
film::Interpolation::Linear => shared::Interpolation::Linear,
film::Interpolation::Hold => shared::Interpolation::Hold,
film::Interpolation::Bezier => shared::Interpolation::Bezier,
film::Interpolation::AutoBezier => shared::Interpolation::AutoBezier,
film::Interpolation::ContinuousBezier => shared::Interpolation::ContinuousBezier,
film::Interpolation::EaseIn => shared::Interpolation::EaseIn,
film::Interpolation::EaseOut => shared::Interpolation::EaseOut,
}
}
fn from_interp(value: shared::Interpolation) -> film::Interpolation {
match value {
shared::Interpolation::Linear => film::Interpolation::Linear,
shared::Interpolation::Hold => film::Interpolation::Hold,
shared::Interpolation::Bezier => film::Interpolation::Bezier,
shared::Interpolation::AutoBezier => film::Interpolation::AutoBezier,
shared::Interpolation::ContinuousBezier => film::Interpolation::ContinuousBezier,
shared::Interpolation::EaseIn => film::Interpolation::EaseIn,
shared::Interpolation::EaseOut => film::Interpolation::EaseOut,
}
}
fn to_effect(effect: &film::EffectInstance) -> Result<shared::EffectInstance, serde_json::Error> {
let params = effect
.params
.iter()
.map(|(name, param)| {
let keyframes = param
.keyframes
.iter()
.map(|k| {
Ok(shared::Keyframe {
time: craft_timeline::time::Tick(k.time.0),
value: to_value(&k.value)?,
interp: to_interp(k.interp),
out_influence: k.out_influence,
in_influence: k.in_influence,
})
})
.collect::<Result<Vec<_>, serde_json::Error>>()?;
Ok((name.clone(), shared::Param { value: to_value(&param.value)?, keyframes }))
})
.collect::<Result<_, serde_json::Error>>()?;
// Shared OTIO emits extension fields after the shared fields; retain FilmCraft's effect-only data.
let ext = serde_json::json!({"masks": effect.masks, "post_fader": effect.post_fader, "essential": effect.essential, "layer": effect.layer});
Ok(shared::EffectInstance { effect: effect.effect.clone(), enabled: effect.enabled, params, ext: Some(serde_json::to_string(&ext)?) })
}
fn from_effect(effect: &shared::EffectInstance) -> Result<film::EffectInstance, serde_json::Error> {
let params: std::collections::BTreeMap<String, film::Param> = effect
.params
.iter()
.map(|(name, param)| {
let keyframes = param
.keyframes
.iter()
.map(|k| {
Ok(film::Keyframe {
time: Tick(k.time.0),
value: from_value(&k.value)?,
interp: from_interp(k.interp),
out_influence: k.out_influence,
in_influence: k.in_influence,
})
})
.collect::<Result<Vec<_>, serde_json::Error>>()?;
Ok((name.clone(), film::Param { value: from_value(&param.value)?, keyframes }))
})
.collect::<Result<_, serde_json::Error>>()?;
let ext: serde_json::Value = effect.ext.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_else(|| serde_json::json!({}));
Ok(film::EffectInstance {
effect: effect.effect.clone(),
enabled: effect.enabled,
params,
masks: ext.get("masks").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(),
post_fader: ext.get("post_fader").and_then(serde_json::Value::as_bool).unwrap_or(false),
essential: ext.get("essential").and_then(serde_json::Value::as_bool).unwrap_or(false),
layer: ext.get("layer").and_then(|v| serde_json::from_value(v.clone()).ok()),
})
}
fn to_marker(marker: &film::Marker) -> Result<shared::Marker, serde_json::Error> {
Ok(shared::Marker {
id: shared::MarkerId(marker.id.0),
start: craft_timeline::time::Tick(marker.start.0),
duration: craft_timeline::time::Tick(marker.duration.0),
name: marker.name.clone(),
comment: marker.comment.clone(),
kind: match marker.kind {
film::MarkerKind::Comment => shared::MarkerKind::Comment,
film::MarkerKind::Chapter => shared::MarkerKind::Chapter,
film::MarkerKind::Segmentation => shared::MarkerKind::Segmentation,
film::MarkerKind::WebLink => shared::MarkerKind::WebLink,
film::MarkerKind::FlashCue => shared::MarkerKind::FlashCue,
},
color: shared::Label::from_name(marker.color.name()).unwrap_or(shared::Label::Green),
url: marker.url.clone(),
author: marker.author.clone(),
ext: Some(serde_json::to_string(&serde_json::json!({"custom_color": marker.custom_color, "filmcraft_marker_id": marker.id.0}))?),
})
}
fn from_marker(marker: &shared::Marker) -> Result<film::Marker, serde_json::Error> {
let ext: serde_json::Value = match &marker.ext {
Some(v) => serde_json::from_str(v)?,
None => serde_json::json!({}),
};
Ok(film::Marker {
id: film::MarkerId(marker.id.0),
start: Tick(marker.start.0),
duration: Tick(marker.duration.0),
name: marker.name.clone(),
comment: marker.comment.clone(),
kind: match marker.kind {
shared::MarkerKind::Comment => film::MarkerKind::Comment,
shared::MarkerKind::Chapter => film::MarkerKind::Chapter,
shared::MarkerKind::Segmentation => film::MarkerKind::Segmentation,
shared::MarkerKind::WebLink => film::MarkerKind::WebLink,
shared::MarkerKind::FlashCue => film::MarkerKind::FlashCue,
},
color: film::Label::from_name(marker.color.name()).unwrap_or(film::Label::Green),
url: marker.url.clone(),
author: marker.author.clone(),
custom_color: serde_json::from_value(ext.get("custom_color").cloned().unwrap_or(serde_json::Value::Null))?,
})
}
// The neutral interchange model carries only the settings common to timeline formats.
// The complete FilmCraft value is retained separately in item metadata by the adapter.
fn to_settings(settings: &film::SequenceSettings) -> shared::SequenceSettings {
shared::SequenceSettings {
width: settings.width,
height: settings.height,
frame_rate: settings.frame_rate,
par: settings.par,
sample_rate: settings.sample_rate,
drop_frame: settings.drop_frame,
}
}
fn from_settings(settings: &shared::SequenceSettings) -> film::SequenceSettings {
film::SequenceSettings {
width: settings.width,
height: settings.height,
frame_rate: settings.frame_rate,
par: settings.par,
sample_rate: settings.sample_rate,
drop_frame: settings.drop_frame,
..film::SequenceSettings::default()
}
}
fn to_channels(channels: film::AudioChannels) -> shared::AudioChannels {
match channels {
film::AudioChannels::Mono => shared::AudioChannels::Mono,
film::AudioChannels::Stereo => shared::AudioChannels::Stereo,
film::AudioChannels::Surround51 => shared::AudioChannels::Surround51,
film::AudioChannels::Adaptive => shared::AudioChannels::Adaptive,
}
}
fn from_channels(channels: shared::AudioChannels) -> film::AudioChannels {
match channels {
shared::AudioChannels::Mono => film::AudioChannels::Mono,
shared::AudioChannels::Stereo => film::AudioChannels::Stereo,
shared::AudioChannels::Surround51 => film::AudioChannels::Surround51,
shared::AudioChannels::Adaptive => film::AudioChannels::Adaptive,
}
}
fn to_track_kind(kind: film::TrackKind) -> shared::TrackKind {
match kind {
film::TrackKind::Video => shared::TrackKind::Video,
film::TrackKind::Audio => shared::TrackKind::Audio,
}
}
fn from_track_kind(kind: shared::TrackKind) -> film::TrackKind {
match kind {
shared::TrackKind::Video => film::TrackKind::Video,
shared::TrackKind::Audio => film::TrackKind::Audio,
}
}
fn to_align(align: film::TransitionAlign) -> shared::TransitionAlign {
match align {
film::TransitionAlign::CenterAtCut => shared::TransitionAlign::CenterAtCut,
film::TransitionAlign::StartAtCut => shared::TransitionAlign::StartAtCut,
film::TransitionAlign::EndAtCut => shared::TransitionAlign::EndAtCut,
}
}
fn from_align(align: shared::TransitionAlign) -> film::TransitionAlign {
match align {
shared::TransitionAlign::CenterAtCut => film::TransitionAlign::CenterAtCut,
shared::TransitionAlign::StartAtCut => film::TransitionAlign::StartAtCut,
shared::TransitionAlign::EndAtCut => film::TransitionAlign::EndAtCut,
}
}
fn to_track_item(item: &film::TrackItem) -> Result<shared::TrackItem, serde_json::Error> {
Ok(shared::TrackItem {
id: shared::ClipId(item.id.0),
item: shared::ItemId(item.item.0),
name: item.name.clone(),
label: shared::Label::from_name(item.label.name()).unwrap_or(shared::Label::Iris),
start: item.start,
duration: item.duration,
source_in: item.source_in,
speed: item.speed,
reverse: item.reverse,
enabled: item.enabled,
link: item.link,
group: item.group,
effects: item.effects.iter().map(to_effect).collect::<Result<_, _>>()?,
markers: item.markers.iter().map(to_marker).collect::<Result<_, _>>()?,
gain_db: item.gain_db,
frame_hold: item.frame_hold,
scale_to_frame: item.scale_to_frame,
source_channels: item.source_channels.clone(),
ext: Some(serde_json::json!({"custom_label_color":item.custom_label_color}).to_string()),
})
}
fn to_transition(t: &film::Transition) -> Result<shared::Transition, serde_json::Error> {
Ok(shared::Transition {
id: shared::TransitionId(t.id.0),
effect: to_effect(&t.effect)?,
start: t.start,
duration: t.duration,
from: t.from.map(|id| shared::ClipId(id.0)),
to: t.to.map(|id| shared::ClipId(id.0)),
align: to_align(t.align),
reverse: t.reverse,
ext: None,
})
}
fn to_track(t: &film::Track) -> Result<shared::Track, serde_json::Error> {
Ok(shared::Track {
id: shared::TrackId(t.id.0),
kind: to_track_kind(t.kind),
name: t.name.clone(),
items: t.items.iter().map(to_track_item).collect::<Result<_, _>>()?,
transitions: t.transitions.iter().map(to_transition).collect::<Result<_, _>>()?,
locked: t.locked,
enabled: t.enabled,
channels: to_channels(t.channels),
ext: Some(
serde_json::json!({"sync_lock":t.sync_lock,"muted":t.muted,"solo":t.solo,"volume_db":t.volume_db,"pan":t.pan,"effects":t.effects}).to_string(),
),
})
}
fn to_sequence(s: &film::Sequence) -> Result<shared::Sequence, serde_json::Error> {
Ok(shared::Sequence {
settings: to_settings(&s.settings),
video_tracks: s.video_tracks.iter().map(to_track).collect::<Result<_, _>>()?,
audio_tracks: s.audio_tracks.iter().map(to_track).collect::<Result<_, _>>()?,
markers: s.markers.iter().map(to_marker).collect::<Result<_, _>>()?,
start_timecode: s.start_timecode,
})
}
fn from_track_item(item: &shared::TrackItem, kind: film::TrackKind, builder: &mut crate::common::Builder) -> Result<film::TrackItem, serde_json::Error> {
let mut out = builder.clip(film::ItemId(item.item.0), kind, &item.name, item.start, item.duration, item.source_in);
if let Some(meta) = legacy_or_ext(&item.ext) {
out.custom_label_color = meta.get("custom_label_color").and_then(|v| serde_json::from_value(v.clone()).ok());
}
out.id = film::ClipId(item.id.0);
out.item = film::ItemId(item.item.0);
out.name = item.name.clone();
out.label = film::Label::from_name(item.label.name()).unwrap_or(film::Label::Iris);
out.start = item.start;
out.duration = item.duration;
out.source_in = item.source_in;
out.speed = item.speed;
out.reverse = item.reverse;
out.enabled = item.enabled;
out.link = item.link;
out.group = item.group;
out.effects = item.effects.iter().map(from_effect).collect::<Result<_, _>>()?;
out.markers = item.markers.iter().map(from_marker).collect::<Result<_, _>>()?;
out.gain_db = item.gain_db;
out.frame_hold = item.frame_hold;
out.scale_to_frame = item.scale_to_frame;
out.source_channels = item.source_channels.clone();
Ok(out)
}
fn from_transition(t: &shared::Transition) -> Result<film::Transition, serde_json::Error> {
Ok(film::Transition {
id: film::TransitionId(t.id.0),
effect: from_effect(&t.effect)?,
start: t.start,
duration: t.duration,
from: t.from.map(|id| film::ClipId(id.0)),
to: t.to.map(|id| film::ClipId(id.0)),
align: from_align(t.align),
reverse: t.reverse,
})
}
fn from_track(t: &shared::Track, builder: &mut crate::common::Builder) -> Result<film::Track, serde_json::Error> {
let kind = from_track_kind(t.kind);
let mut out = film::Track::new(film::TrackId(t.id.0), kind, t.name.clone());
if let Some(meta) = legacy_or_ext(&t.ext) {
out.sync_lock = meta.get("sync_lock").and_then(serde_json::Value::as_bool).unwrap_or(out.sync_lock);
out.muted = meta.get("muted").and_then(serde_json::Value::as_bool).unwrap_or(out.muted);
out.solo = meta.get("solo").and_then(serde_json::Value::as_bool).unwrap_or(out.solo);
out.volume_db = meta.get("volume_db").and_then(serde_json::Value::as_f64).unwrap_or(out.volume_db);
out.pan = meta.get("pan").and_then(serde_json::Value::as_f64).unwrap_or(out.pan);
if let Some(effects) = meta.get("effects").and_then(|v| serde_json::from_value(v.clone()).ok()) {
out.effects = effects;
}
}
out.id = film::TrackId(t.id.0);
out.kind = kind;
out.name = t.name.clone();
out.locked = t.locked;
out.enabled = t.enabled;
out.channels = from_channels(t.channels);
out.items = t.items.iter().map(|item| from_track_item(item, kind, builder)).collect::<Result<_, _>>()?;
out.transitions = t.transitions.iter().map(from_transition).collect::<Result<_, _>>()?;
Ok(out)
}
fn from_sequence(seq: &shared::Sequence, ext: &shared::Ext, builder: &mut crate::common::Builder) -> Result<film::Sequence, serde_json::Error> {
let mut out = crate::common::empty_sequence(from_settings(&seq.settings));
if let Some(meta) = legacy_or_ext(ext) {
if let Some(settings) = meta.get("filmcraft_settings").or_else(|| meta.get("settings")).and_then(|v| serde_json::from_value(v.clone()).ok()) {
out.settings = settings;
}
out.master_volume_db = meta.get("master_volume_db").and_then(serde_json::Value::as_f64).unwrap_or(out.master_volume_db);
if let Some(effects) = meta.get("master_effects").and_then(|v| serde_json::from_value(v.clone()).ok()) {
out.master_effects = effects;
}
}
out.settings.width = seq.settings.width;
out.settings.height = seq.settings.height;
out.settings.frame_rate = seq.settings.frame_rate;
out.settings.par = seq.settings.par;
out.settings.sample_rate = seq.settings.sample_rate;
out.settings.drop_frame = seq.settings.drop_frame;
out.video_tracks = seq.video_tracks.iter().map(|t| from_track(t, builder)).collect::<Result<_, _>>()?;
out.audio_tracks = seq.audio_tracks.iter().map(|t| from_track(t, builder)).collect::<Result<_, _>>()?;
out.markers = seq.markers.iter().map(from_marker).collect::<Result<_, _>>()?;
out.start_timecode = seq.start_timecode;
Ok(out)
}
fn to_generator(g: &filmcraft_media::Generator) -> Result<shared::Generator, serde_json::Error> {
use filmcraft_media::Generator as F;
Ok(match g {
F::BarsAndTone => shared::Generator::BarsAndTone,
F::BlackVideo => shared::Generator::BlackVideo,
F::TransparentVideo => shared::Generator::TransparentVideo,
F::CountingLeader => shared::Generator::CountingLeader,
F::ColorMatte { color } => shared::Generator::ColorMatte { color: *color },
_ => shared::Generator::Other { name: g.label(), data: serde_json::to_string(g)? },
})
}
fn from_generator(g: &shared::Generator) -> filmcraft_media::Generator {
use filmcraft_media::Generator as F;
match g {
shared::Generator::BarsAndTone => F::BarsAndTone,
shared::Generator::BlackVideo => F::BlackVideo,
shared::Generator::TransparentVideo => F::TransparentVideo,
shared::Generator::CountingLeader => F::CountingLeader,
shared::Generator::ColorMatte { color } => F::ColorMatte { color: *color },
shared::Generator::Other { data, .. } => serde_json::from_str(data).unwrap_or(F::BlackVideo),
}
}
fn to_media(m: &film::MediaClip) -> Result<shared::MediaClip, serde_json::Error> {
use filmcraft_media::MediaKind as F;
let info = &m.info;
let kind = match info.kind {
F::Movie => shared::MediaKind::Movie,
F::AudioOnly => shared::MediaKind::AudioOnly,
F::Still => shared::MediaKind::Still,
F::ImageSequence => shared::MediaKind::ImageSequence,
F::Synthetic => shared::MediaKind::Synthetic,
};
let media = match &m.media {
film::MediaRef::File { path } => shared::MediaRef::File { path: path.clone() },
film::MediaRef::Generator(g) => shared::MediaRef::Generator(to_generator(g)?),
};
Ok(shared::MediaClip {
media,
info: shared::MediaInfo {
name: info.name.clone(),
kind,
duration: info.duration,
video: info.video.as_ref().map(|v| shared::VideoStreamInfo { width: v.width, height: v.height, frame_rate: v.frame_rate, par: v.par }),
audio_streams: info
.audio_streams
.iter()
.map(|a| shared::AudioStreamInfo { sample_rate: a.sample_rate, channels: a.channels, bits_per_sample: a.bits_per_sample })
.collect(),
start_timecode: info.start_timecode,
},
interpret_frame_rate: m.interpret.frame_rate,
markers: m.markers.iter().map(to_marker).collect::<Result<_, _>>()?,
offline: m.offline,
})
}
fn from_media(m: &shared::MediaClip, ext: &shared::Ext) -> Result<film::MediaClip, serde_json::Error> {
let media = match &m.media {
shared::MediaRef::File { path } => film::MediaRef::File { path: path.clone() },
shared::MediaRef::Generator(g) => film::MediaRef::Generator(from_generator(g)),
};
let spec = crate::common::MediaSpec {
duration: Some(m.info.duration),
video: m.info.video.as_ref().map(|v| (v.width, v.height, v.frame_rate)),
audio: m.info.audio().map(|a| (a.sample_rate, a.channels)),
start_tc: m.info.start_timecode,
kind: None,
};
let mut out = crate::common::media_clip(media.clone(), crate::common::media_info(&m.info.name, &spec));
if let Some(info) =
legacy_or_ext(ext).and_then(|meta| meta.get("filmcraft_info").or_else(|| meta.get("info")).and_then(|v| serde_json::from_value(v.clone()).ok()))
{
out.info = info;
}
out.media = media;
out.info.name = m.info.name.clone();
out.info.duration = m.info.duration;
out.info.kind = match m.info.kind {
shared::MediaKind::Movie => filmcraft_media::MediaKind::Movie,
shared::MediaKind::AudioOnly => filmcraft_media::MediaKind::AudioOnly,
shared::MediaKind::Still => filmcraft_media::MediaKind::Still,
shared::MediaKind::ImageSequence => filmcraft_media::MediaKind::ImageSequence,
shared::MediaKind::Synthetic => filmcraft_media::MediaKind::Synthetic,
};
if let Some(source) = &m.info.video {
if out.info.video.is_none() {
out.info.video = crate::common::media_info(&m.info.name, &spec).video;
}
if let Some(v) = &mut out.info.video {
v.width = source.width;
v.height = source.height;
v.frame_rate = source.frame_rate;
v.par = source.par;
}
} else {
out.info.video = None;
}
out.info.audio_streams = m
.info
.audio_streams
.iter()
.enumerate()
.map(|(index, a)| {
let mut out = out.info.audio_streams.get(index).cloned().unwrap_or(filmcraft_media::AudioStreamInfo {
sample_rate: a.sample_rate,
channels: a.channels,
codec: String::new(),
bits_per_sample: a.bits_per_sample,
});
out.sample_rate = a.sample_rate;
out.channels = a.channels;
out.bits_per_sample = a.bits_per_sample;
out
})
.collect();
out.info.start_timecode = m.info.start_timecode;
out.interpret.frame_rate = m.interpret_frame_rate;
out.offline = m.offline;
out.markers = m.markers.iter().map(from_marker).collect::<Result<_, _>>()?;
Ok(out)
}
fn from_bin(bin: &shared::Bin) -> film::Bin {
film::Bin {
id: film::BinId(bin.id.0),
name: bin.name.clone(),
children: bin
.children
.iter()
.map(|e| match e {
shared::BinEntry::Item(id) => film::BinEntry::Item(film::ItemId(id.0)),
shared::BinEntry::Bin(b) => film::BinEntry::Bin(from_bin(b)),
})
.collect(),
}
}
fn to_project(project: &film::Project, root: film::ItemId) -> Result<shared::Project, serde_json::Error> {
let mut out = shared::Project::new(&project.name);
out.next_id = project.next_id;
let mut pending = vec![root];
let mut seen = std::collections::BTreeSet::new();
while let Some(id) = pending.pop() {
if !seen.insert(id) {
continue;
}
let Some(item) = project.items.get(&id) else { continue };
match &item.kind {
film::ItemKind::Sequence(seq) => pending.extend(seq.all_tracks().flat_map(|track| track.items.iter().map(|clip| clip.item))),
film::ItemKind::Subclip { parent, .. } => pending.push(*parent),
_ => {}
}
let (kind, ext) = match &item.kind {
film::ItemKind::Media(m) => {
(shared::ItemKind::Media(Box::new(to_media(m)?)), serde_json::json!({"filmcraft_info":m.info,"custom_label_color":item.custom_label_color}))
}
film::ItemKind::Sequence(seq) => (
shared::ItemKind::Sequence(Box::new(to_sequence(seq)?)),
serde_json::json!({"filmcraft_settings":seq.settings,"custom_label_color":item.custom_label_color,"master_volume_db":seq.master_volume_db,"master_effects":seq.master_effects,"custom_colors":project.custom_colors,"custom_color_names":project.custom_color_names}),
),
film::ItemKind::Subclip { parent, range, .. } => {
(shared::ItemKind::Subclip { parent: shared::ItemId(parent.0), range: *range }, serde_json::json!({}))
}
film::ItemKind::AdjustmentLayer { width, height, rate, duration } => (
shared::ItemKind::Uncarried { what: "adjustment layer".into(), width: *width, height: *height, rate: *rate, duration: *duration },
serde_json::json!({}),
),
film::ItemKind::Graphic { width, height, rate } => (
shared::ItemKind::Uncarried { what: "graphic clip".into(), width: *width, height: *height, rate: *rate, duration: Tick::ZERO },
serde_json::json!({}),
),
};
out.items.insert(
shared::ItemId(id.0),
shared::ProjectItem {
id: shared::ItemId(id.0),
name: item.name.clone(),
label: shared::Label::from_name(item.label.name()).unwrap_or(shared::Label::Iris),
kind,
metadata: item.metadata.clone(),
ext: Some(ext.to_string()),
},
);
}
Ok(out)
}
fn from_project(project: &shared::Project) -> Result<film::Project, serde_json::Error> {
let mut builder = crate::common::Builder::new(&project.name);
let mut out = film::Project::new(&project.name);
out.root = from_bin(&project.root);
out.next_id = project.next_id;
for (id, item) in &project.items {
let kind = match &item.kind {
shared::ItemKind::Media(m) => film::ItemKind::Media(Box::new(from_media(m, &item.ext)?)),
shared::ItemKind::Sequence(seq) => film::ItemKind::Sequence(std::sync::Arc::new(from_sequence(seq, &item.ext, &mut builder)?)),
shared::ItemKind::Subclip { parent, range } => film::ItemKind::Subclip { parent: film::ItemId(parent.0), range: *range, restrict_trims: false },
shared::ItemKind::Uncarried { width, height, rate, duration, .. } => {
film::ItemKind::AdjustmentLayer { width: *width, height: *height, rate: *rate, duration: *duration }
}
};
let mut out_item = film::ProjectItem {
id: film::ItemId(id.0),
name: item.name.clone(),
label: film::Label::from_name(item.label.name()).unwrap_or(film::Label::Iris),
custom_label_color: None,
kind,
metadata: item.metadata.clone(),
created: 0,
split: Default::default(),
};
if let Some(meta) = legacy_or_ext(&item.ext) {
out_item.custom_label_color = meta.get("custom_label_color").and_then(|v| serde_json::from_value(v.clone()).ok());
}
out.items.insert(out_item.id, out_item);
}
out.next_id = out.next_id.max(builder.p.next_id);
Ok(out)
}
struct FilmCatalog;
impl FilmCatalog {
fn convert(def: &film::effect::EffectDef) -> Option<shared::EffectDef> {
use film::effect::EffectKind as F;
let kind = match def.kind {
F::Video => shared::EffectKind::Video,
F::Audio => shared::EffectKind::Audio,
F::VideoTransition => shared::EffectKind::VideoTransition,
F::AudioTransition => shared::EffectKind::AudioTransition,
};
let params = def
.params
.iter()
.map(|p| Some(shared::ParamDef { id: p.id.into(), label: p.label.into(), default: to_value(&p.default).ok()? }))
.collect::<Option<Vec<_>>>()?;
Some(shared::EffectDef {
id: def.id.into(),
name: film::effect::interchange_name(def).into(),
kind,
category: def.category.last().copied().unwrap_or("").into(),
intrinsic: def.intrinsic,
params,
})
}
}
impl shared::Catalog for FilmCatalog {
fn effect(&self, id: &str) -> Option<shared::EffectDef> {
film::find_effect(id).and_then(Self::convert)
}
fn effect_by_name(&self, name: &str) -> Option<shared::EffectDef> {
film::effect::find_effect_by_name(name).and_then(Self::convert)
}
fn generator_by_name(&self, name: &str) -> Option<shared::Generator> {
let scene = filmcraft_media::DemoScene::ALL.iter().find(|scene| scene.file_name().eq_ignore_ascii_case(name))?;
to_generator(&filmcraft_media::Generator::Demo(*scene)).ok()
}
fn intrinsic(&self, kind: shared::TrackKind) -> Vec<shared::EffectInstance> {
let values = match kind {
shared::TrackKind::Video => film::effect::intrinsic_video(),
shared::TrackKind::Audio => film::effect::intrinsic_audio(),
};
values.iter().filter_map(|v| to_effect(v).ok()).collect()
}
}
fn preserve_legacy_metadata(value: &mut serde_json::Value) {
match value {
serde_json::Value::Object(map) => {
if let Some(meta) = map.get_mut("metadata").and_then(|v| v.get_mut("filmcraft")).and_then(serde_json::Value::as_object_mut) {
// Keep the old application's object before the shared reader consumes known keys.
let mut original = meta.clone();
original.remove("filmcraft_legacy_metadata");
meta.insert("filmcraft_legacy_metadata".into(), serde_json::Value::Object(original));
}
for (key, child) in map.iter_mut() {
if key != "metadata" {
preserve_legacy_metadata(child);
}
}
}
serde_json::Value::Array(values) => {
for child in values {
preserve_legacy_metadata(child);
}
}
_ => {}
}
}
fn restore_legacy_output(value: &mut serde_json::Value) {
match value {
serde_json::Value::Object(map) => {
if let Some(meta) = map.get_mut("metadata").and_then(|v| v.get_mut("filmcraft")).and_then(serde_json::Value::as_object_mut) {
if let Some(settings) = meta.remove("filmcraft_settings") {
meta.insert("settings".into(), settings);
}
if let Some(info) = meta.remove("filmcraft_info") {
meta.insert("info".into(), info);
}
}
for (key, child) in map.iter_mut() {
if key != "metadata" {
restore_legacy_output(child);
}
}
}
serde_json::Value::Array(values) => {
for child in values {
restore_legacy_output(child);
}
}
_ => {}
}
}
fn legacy_or_ext(ext: &shared::Ext) -> Option<serde_json::Value> {
let outer: serde_json::Value = serde_json::from_str(ext.as_deref()?).ok()?;
Some(outer.get("filmcraft_legacy_metadata").cloned().unwrap_or(outer))
}
fn merge_report(dst: &mut crate::Report, src: craft_timeline::Report) {
for entry in src.entries {
let level = match entry.level {
craft_timeline::Level::Info => crate::Level::Info,
craft_timeline::Level::Warning => crate::Level::Warning,
};
dst.push_n(level, entry.message, entry.count);
}
}
fn convert_error(e: craft_timeline::Error) -> crate::Error {
match e {
craft_timeline::Error::Parse { format, message } => crate::Error::Parse { format, message },
craft_timeline::Error::Empty => crate::Error::Empty,
craft_timeline::Error::NoSequence(id) => crate::Error::NoSequence(film::ItemId(id.0)),
craft_timeline::Error::Other(message) => crate::Error::Other(message),
}
}
fn merge_otio_palette(project: &mut film::Project, meta: Option<&serde_json::Value>, report: &mut crate::Report) {
use serde_json::Value;
if let Some(colors) = meta.and_then(|m| m.get("custom_colors")).and_then(Value::as_array) {
let mut overflow = false;
for color in colors.iter().filter_map(Value::as_str).filter_map(filmcraft_project::HexColor::parse) {
if project.custom_colors.contains(&color) {
continue;
}
if project.custom_colors.len() >= 64 {
overflow = true;
break;
}
project.custom_colors.push(color);
}
if overflow {
report.warn("OTIO saved palettes exceed the 64-color project limit; additional colors were not imported.");
}
}
if let Some(names) = meta.and_then(|m| m.get("custom_color_names")).and_then(Value::as_object) {
for (key, value) in names {
if let (Some(color), Some(name)) = (filmcraft_project::HexColor::parse(key), value.as_str())
&& project.custom_colors.contains(&color)
&& name.len() <= 128
&& !name.chars().any(char::is_control)
{
project.custom_color_names.entry(color).or_insert_with(|| name.to_owned());
}
}
}
}
pub(crate) fn import_otio(text: &str, opts: &crate::ImportOptions, report: &mut crate::Report) -> crate::Result<crate::Imported> {
let mut value: serde_json::Value = serde_json::from_str(text).map_err(|e| crate::Error::parse(crate::Format::Otio, e.to_string()))?;
preserve_legacy_metadata(&mut value);
let normalized = serde_json::to_string(&value).map_err(|e| crate::Error::Other(e.to_string()))?;
drop(value);
let catalog = FilmCatalog;
let shared_opts =
craft_timeline::ImportOptions { base_dir: opts.base_dir.as_deref(), name: opts.name.as_deref(), catalog: &catalog, namespace: "filmcraft" };
let mut shared_report = craft_timeline::Report::default();
let result = craft_timeline::otio::import_with_report_limit(&normalized, &shared_opts, &mut shared_report, Some(crate::MAX_REPORT_ENTRIES));
merge_report(report, shared_report);
let imported = result.map_err(convert_error)?;
let mut project = from_project(&imported.project).map_err(|e| crate::Error::Other(e.to_string()))?;
for id in &imported.sequences {
merge_otio_palette(&mut project, imported.project.items.get(id).and_then(|item| legacy_or_ext(&item.ext)).as_ref(), report);
}
Ok(crate::Imported { project, sequences: imported.sequences.into_iter().map(|id| film::ItemId(id.0)).collect() })
}
pub(crate) fn export_otio(project: &film::Project, seq: film::ItemId, opts: &crate::ExportOptions, report: &mut crate::Report) -> crate::Result<String> {
let project = to_project(project, seq).map_err(|e| crate::Error::Other(e.to_string()))?;
let catalog = FilmCatalog;
let shared_opts = craft_timeline::ExportOptions {
relative_to: opts.relative_to.as_deref(),
name: opts.name.as_deref(),
catalog: &catalog,
namespace: "filmcraft",
xmeml_version: opts.xmeml_version,
fcpxml_version: Default::default(),
};
let mut shared_report = craft_timeline::Report::default();
let result =
craft_timeline::otio::export_with_report_limit(&project, shared::ItemId(seq.0), &shared_opts, &mut shared_report, Some(crate::MAX_REPORT_ENTRIES));
merge_report(report, shared_report);
let text = result.map_err(convert_error)?;
let mut value: serde_json::Value = serde_json::from_str(&text).map_err(|e| crate::Error::Other(e.to_string()))?;
restore_legacy_output(&mut value);
serde_json::to_string_pretty(&value).map_err(|e| crate::Error::Other(e.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn effect_keyframes_and_app_fields_roundtrip() {
let mut effect = film::EffectInstance {
effect: "unknown".into(),
enabled: true,
params: Default::default(),
masks: Vec::new(),
post_fader: false,
essential: false,
layer: None,
};
effect.post_fader = true;
let mut param = film::Param::new(film::ParamValue::Curve(vec![[0.25, 0.75]]));
let mut key = film::Keyframe::new(Tick(123), film::ParamValue::Vec2(filmcraft_geom::Vec2::new(1.0, 2.0)));
key.interp = film::Interpolation::Bezier;
key.out_influence = 0.6;
param.keyframes.push(key);
effect.params.insert("curve".into(), param);
let neutral = to_effect(&effect).unwrap();
assert_eq!(from_effect(&neutral).unwrap(), effect);
}
#[test]
fn shared_reader_matches_legacy_plain_clip_timing() {
let doc = r#"{"OTIO_SCHEMA":"Timeline.1","name":"T","tracks":{"OTIO_SCHEMA":"Stack.1","children":[{"OTIO_SCHEMA":"Track.1","kind":"Video","children":[{"OTIO_SCHEMA":"Clip.2","name":"A","source_range":{"OTIO_SCHEMA":"TimeRange.1","start_time":{"OTIO_SCHEMA":"RationalTime.1","rate":24,"value":12},"duration":{"OTIO_SCHEMA":"RationalTime.1","rate":24,"value":48}},"media_references":{"DEFAULT_MEDIA":{"OTIO_SCHEMA":"ExternalReference.1","target_url":"file:///tmp/a.mov"}},"active_media_reference_key":"DEFAULT_MEDIA"}]}]}}"#;
let opts = crate::ImportOptions::default();
let old = crate::otio::import(doc, &opts, &mut crate::Report::default()).unwrap();
let new = import_otio(doc, &opts, &mut crate::Report::default()).unwrap();
let old_clip = &old.project.sequence(old.sequences[0]).unwrap().video_tracks[0].items[0];
let new_clip = &new.project.sequence(new.sequences[0]).unwrap().video_tracks[0].items[0];
assert_eq!((new_clip.start, new_clip.duration, new_clip.source_in), (old_clip.start, old_clip.duration, old_clip.source_in));
}
#[test]
fn exported_metadata_keeps_legacy_settings_and_media_info() {
let mut value = serde_json::json!({"metadata":{"filmcraft":{"settings":{"width":1},"filmcraft_settings":{"width":2,"preset":"legacy"},"info":{"name":"shared"},"filmcraft_info":{"name":"original","container":"mov"}}}});
restore_legacy_output(&mut value);
let meta = &value["metadata"]["filmcraft"];
assert_eq!(meta["settings"]["preset"], "legacy");
assert_eq!(meta["info"]["container"], "mov");
assert!(meta.get("filmcraft_settings").is_none() && meta.get("filmcraft_info").is_none());
}
}
+1
View File
@@ -10,6 +10,7 @@ rust-version.workspace = true
workspace = true
[dependencies]
craft-font-catalog = { workspace = true }
filmcraft-color = { workspace = true }
# Font tables, glyph outlines and metrics (MIT OR Apache-2.0). Rasterisation is our own.
skrifa = { version = "0.44", default-features = false, features = ["std"] }
+8 -174
View File
@@ -1,158 +1,15 @@
//! Minimal SFNT (TrueType / OpenType / collection) header reader for font discovery: reads only
//! the table directory, `name` and `OS/2` of each face, so scanning a system font folder does not
//! load whole files.
use std::io::{Read, Seek, SeekFrom};
/// The tables skrifa reads glyph outlines from: TrueType, CFF, CFF2 and VARC. The renderer draws
/// no glyph of a face that has none of them, such as a face with bitmaps only or with its outlines
/// in Apple's `hvgl` table.
const OUTLINE_TABLES: [&[u8; 4]; 4] = [b"glyf", b"CFF ", b"CFF2", b"VARC"];
/// Names and style attributes of one face in a font file.
#[derive(Clone, Debug, PartialEq)]
pub struct FaceNames {
pub index: u32,
pub family: String,
pub style: String,
pub full_name: String,
pub weight: u16,
pub italic: bool,
}
fn be16(b: &[u8], o: usize) -> Option<u16> {
Some(u16::from_be_bytes([*b.get(o)?, *b.get(o + 1)?]))
}
fn be32(b: &[u8], o: usize) -> Option<u32> {
Some(u32::from_be_bytes([*b.get(o)?, *b.get(o + 1)?, *b.get(o + 2)?, *b.get(o + 3)?]))
}
fn read_at<R: Read + Seek>(r: &mut R, off: u64, len: usize) -> Option<Vec<u8>> {
if len > 4 << 20 {
return None;
}
r.seek(SeekFrom::Start(off)).ok()?;
let mut v = vec![0u8; len];
r.read_exact(&mut v).ok()?;
Some(v)
}
/// Read the names of every face in a font file (a single font or a collection). Faces with none
/// of the `OUTLINE_TABLES` are left out.
pub fn read_faces<R: Read + Seek>(r: &mut R) -> Vec<FaceNames> {
let Some(head) = read_at(r, 0, 12) else { return Vec::new() };
let offsets: Vec<u32> = if &head[0..4] == b"ttcf" {
let n = be32(&head, 8).unwrap_or(0).min(256) as usize;
let Some(t) = read_at(r, 12, n * 4) else { return Vec::new() };
(0..n).filter_map(|i| be32(&t, i * 4)).collect()
} else {
vec![0]
};
offsets.iter().enumerate().filter_map(|(i, &o)| read_face(r, o as u64, i as u32)).collect()
}
/// Names from in-memory font data.
pub fn read_faces_bytes(data: &[u8]) -> Vec<FaceNames> {
read_faces(&mut std::io::Cursor::new(data))
}
fn read_face<R: Read + Seek>(r: &mut R, off: u64, index: u32) -> Option<FaceNames> {
let h = read_at(r, off, 12)?;
let tag = &h[0..4];
if tag != [0, 1, 0, 0] && tag != b"OTTO" && tag != b"true" {
return None;
}
let n = be16(&h, 4)? as usize;
let dir = read_at(r, off + 12, n * 16)?;
if !dir.as_chunks::<16>().0.iter().any(|rec| OUTLINE_TABLES.iter().any(|t| rec.starts_with(*t))) {
return None;
}
let mut name = None;
let mut os2 = None;
for i in 0..n {
let rec = &dir[i * 16..i * 16 + 16];
let (o, l) = (be32(rec, 8)? as u64, be32(rec, 12)? as usize);
match &rec[0..4] {
b"name" => name = Some((o, l)),
b"OS/2" => os2 = Some((o, l)),
_ => {}
}
}
let (no, nl) = name?;
let nb = read_at(r, no, nl)?;
let get = |id: u16| name_string(&nb, id);
let family = get(16).or_else(|| get(1))?;
let style = get(17).or_else(|| get(2)).unwrap_or_else(|| "Regular".into());
let full_name = get(4).unwrap_or_else(|| format!("{family} {style}"));
let (mut weight, mut italic) = (400u16, false);
if let Some((oo, ol)) = os2
&& let Some(ob) = read_at(r, oo, ol.min(78))
{
weight = be16(&ob, 4).unwrap_or(400);
italic = be16(&ob, 62).is_some_and(|fs| fs & 1 != 0);
}
let sl = style.to_ascii_lowercase();
italic |= sl.contains("italic") || sl.contains("oblique");
Some(FaceNames { index, family, style, full_name, weight, italic })
}
/// A name-table string by id, preferring Windows Unicode English, then any Unicode, then Mac Roman.
fn name_string(b: &[u8], id: u16) -> Option<String> {
let count = be16(b, 2)? as usize;
let storage = be16(b, 4)? as usize;
let mut best: Option<(u8, String)> = None;
for i in 0..count {
let r = 6 + i * 12;
let (plat, enc, lang, nid, len, off) =
(be16(b, r)?, be16(b, r + 2)?, be16(b, r + 4)?, be16(b, r + 6)?, be16(b, r + 8)? as usize, be16(b, r + 10)? as usize);
if nid != id {
continue;
}
let rank = match plat {
3 if enc == 1 || enc == 10 => {
if best.as_ref().is_some_and(|(current, _)| *current <= if lang == 0x409 { 0 } else { 1 }) {
continue;
}
if lang == 0x409 { 0 } else { 1 }
}
0 => {
if best.as_ref().is_some_and(|(current, _)| *current <= 2) {
continue;
}
2
}
1 if enc == 0 => {
if best.as_ref().is_some_and(|(current, _)| *current <= 3) {
continue;
}
3
}
_ => continue,
};
// Only decode a record that can improve the selected name. A hostile name table may
// point thousands of records at the same huge string.
let raw = b.get(storage + off..storage + off + len)?;
let s = match plat {
3 => {
let u: Vec<u16> = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
String::from_utf16_lossy(&u)
}
0 => {
let u: Vec<u16> = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
String::from_utf16_lossy(&u)
}
1 => raw.iter().map(|&c| if c < 128 { c as char } else { '?' }).collect(),
_ => return None,
};
best = Some((rank, s));
}
best.map(|(_, s)| s).filter(|s| !s.trim().is_empty())
}
//! SFNT face metadata discovery for FilmCraft fonts.
pub use craft_font_catalog::sfnt::{FaceNames, read_faces, read_faces_bytes};
#[cfg(test)]
mod tests {
use super::*;
fn be16(b: &[u8], o: usize) -> Option<u16> {
Some(u16::from_be_bytes([*b.get(o)?, *b.get(o + 1)?]))
}
fn be32(b: &[u8], o: usize) -> Option<u32> {
Some(u32::from_be_bytes([*b.get(o)?, *b.get(o + 1)?, *b.get(o + 2)?, *b.get(o + 3)?]))
}
#[test]
fn reads_bundled_names() {
let f = read_faces_bytes(crate::fonts::INTER_BOLD);
@@ -206,27 +63,4 @@ mod tests {
assert_eq!(faces.len(), 1);
assert_eq!((faces[0].index, faces[0].family.as_str(), faces[0].style.as_str()), (1, "Inter", "Regular"));
}
#[test]
fn later_non_improving_name_records_are_not_decoded() {
// The first record is the preferred Windows-English value. The second names an invalid
// range: it must be ignored instead of making the whole name lookup fail.
let mut table = vec![0; 30];
table[2..4].copy_from_slice(&2u16.to_be_bytes());
table[4..6].copy_from_slice(&30u16.to_be_bytes());
let first = 6usize;
table[first..first + 2].copy_from_slice(&3u16.to_be_bytes());
table[first + 2..first + 4].copy_from_slice(&1u16.to_be_bytes());
table[first + 4..first + 6].copy_from_slice(&0x409u16.to_be_bytes());
table[first + 6..first + 8].copy_from_slice(&1u16.to_be_bytes());
table[first + 8..first + 10].copy_from_slice(&4u16.to_be_bytes());
let second = first + 12;
table[second..second + 2].copy_from_slice(&3u16.to_be_bytes());
table[second + 2..second + 4].copy_from_slice(&1u16.to_be_bytes());
table[second + 4..second + 6].copy_from_slice(&0x409u16.to_be_bytes());
table[second + 6..second + 8].copy_from_slice(&1u16.to_be_bytes());
table[second + 8..second + 10].copy_from_slice(&u16::MAX.to_be_bytes());
table.extend_from_slice(&[0, b'A', 0, b'B']);
assert_eq!(name_string(&table, 1).as_deref(), Some("AB"));
}
}
@@ -542,6 +542,23 @@ fn text_section_header(
open
}
/// The clips a layer property change in the editor goes to (#4625): `clip`, the one it shows,
/// then each other selected graphic clip whose layer `l` is the same kind of layer (text or
/// shape), outside locked tracks. With several text clips selected, a Font or Font Size change
/// sets that value on all of them.
fn property_targets(app: &FilmcraftApp, clip: ClipId, it: &TrackItem, l: usize) -> Vec<u64> {
let mut ids = vec![clip.0];
let layer_kind = |it: &TrackItem| layer_indices(&it.effects).get(l).and_then(|&i| it.effects.get(i)).map(|e| e.effect.clone());
let (Some(q), Some(kind)) = (app.session.active_sequence(), layer_kind(it)) else { return ids };
for &c in &app.session.state.selection {
let Some((track, other)) = q.find_item(c) else { continue };
if !ids.contains(&c.0) && q.track(track).is_some_and(|t| !t.locked) && is_graphic_clip(app, c) && layer_kind(other).as_ref() == Some(&kind) {
ids.push(c.0);
}
}
ids
}
pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let Some((clip, it)) = selected_graphic(app) else {
@@ -560,6 +577,7 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let mt = it.effect_time_at(ph.clamp(it.start, it.end() - Tick(1)));
let idx = layer_indices(&it.effects);
let sel = app.session.state.graphic_layers.first().copied().filter(|l| *l < idx.len());
let group = sel.map_or_else(Vec::new, |l| property_targets(app, clip, &it, l));
let mut actions: Vec<(String, Value)> = Vec::new();
let mut autos: Vec<(String, Rect, String)> = Vec::new();
let mut bui = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(vec2(12.0, 6.0))).id_salt("gfx-props"));
@@ -801,6 +819,18 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
cx.number(ui, tl!(" Blur"), NumberField { id: "shadow_blur", speed: 0.5, range: (0.0, 1000.0), decimals: 0, unit: "" });
}
}
// a property change goes to the layer of every clip in the group (#4625); character styles
// of a Type-tool selection stay on their own clip
if group.len() > 1 {
for (cmd, p) in &mut cx.actions {
if cmd == "graphics.set"
&& let Some(o) = p.as_object_mut()
{
o.remove("clip");
o.insert("clips".into(), json!(group));
}
}
}
actions.append(&mut cx.actions);
autos.append(&mut cx.autos);
});
+49
View File
@@ -741,3 +741,52 @@ fn effect_controls_font_and_style_are_drop_downs_that_apply() {
pick(&mut d, "Bold Italic");
assert_eq!(text_param(&mut d, clip, "font_style"), Some(filmcraft_project::ParamValue::Text("Bold Italic".into())), "picking a style applies it");
}
/// #4625: with several text clips selected, a text property changed in the Properties panel
/// (Font Size, Font) is set on every selected text clip, not only the first one shown there. A
/// clip on a locked track keeps its value, and one undo restores each clip's own size.
#[test]
fn a_text_property_change_applies_to_every_selected_text_clip() {
let mut d = Driver::demo();
d.ok("ui.set", json!({"workspace": "Captions and Graphics"}));
let clips: Vec<u64> = (0..3).map(|i| d.exec("graphics.newText", json!({"text": format!("Title {i}")}))["clip"].as_u64().unwrap()).collect();
for (clip, size) in clips.iter().zip([60, 80, 90]) {
d.exec("graphics.set", json!({"clip": clip, "layer": 0, "props": {"size": size}}));
}
let locked_track = {
let q = d.harness.state().session.active_sequence().unwrap();
q.video_tracks.iter().position(|t| t.items.iter().any(|it| it.id.0 == clips[2])).unwrap()
};
d.exec("timeline.setTrack", json!({"track": format!("V{}", locked_track + 1), "locked": true}));
d.exec("timeline.select", json!({"clips": clips, "linked": false}));
d.frames(4);
let size = |d: &mut Driver, clip: u64| text_param(d, clip, "size").and_then(|v| v.as_f64()).unwrap();
let before = d.harness.state().session.project.clone();
let n = d.harness.state().session.history.undo.len();
let r = d.rect("graphics.prop.size");
d.ok(
"ui.drag",
json!({"from": {"x": r[0] + r[2] / 2.0, "y": r[1] + r[3] / 2.0}, "to": {"x": r[0] + r[2] / 2.0 + 80.0, "y": r[1] + r[3] / 2.0}, "steps": 8}),
);
d.frames(3);
let first = size(&mut d, clips[0]);
assert_ne!(first, 60.0, "the drag changed the size shown in the panel");
assert_eq!(size(&mut d, clips[1]), first, "the other selected text clip gets the same size");
assert_eq!(size(&mut d, clips[2]), 90.0, "a clip on a locked track keeps its size");
assert_eq!(d.harness.state().session.history.undo.len(), n + 1, "the drag is one undo step for every clip");
d.exec("edit.undo", json!({}));
assert_eq!(*d.harness.state().session.project, *before, "one undo restores every clip's own size");
// Font: picking a family in the drop-down sets it on every selected text clip
let fam = filmcraft_text::picker_families()
.into_iter()
.map(|(f, _)| f)
.find(|f| Some(filmcraft_project::ParamValue::Text(f.clone())) != text_param(&mut d, clips[0], "font"))
.expect("another family");
d.ok("ui.click", json!({"id": "graphics.prop.font"}));
d.frames(3);
pick(&mut d, &fam);
for clip in &clips[..2] {
assert_eq!(text_param(&mut d, *clip, "font"), Some(filmcraft_project::ParamValue::Text(fam.clone())), "clip {clip} has the picked family");
}
assert_ne!(text_param(&mut d, clips[2], "font"), Some(filmcraft_project::ParamValue::Text(fam.clone())), "the locked clip keeps its family");
}
+7 -1
View File
@@ -44,6 +44,12 @@ properties prefixed `stroke2`; snake_case names are also accepted. Colours are h
`[r,g,b,a]`. Overrides persist in projects and follow text edits; `clear:true` removes them with
the other character styles. Without a character selection, the controls edit layer values.
With several graphic clips selected, the Properties panel shows the first one, and a layer
property changed there (Font, Font Size, Fill and the rest) is set on the same layer of every
selected graphic clip whose layer at that place is the same kind (text or shape), as one undo
step. The other selected clips on locked tracks keep their values. Character styles of a
Type-tool selection stay on the clip being edited.
### Point text and paragraph text
A text layer is one of two types, as in Premiere Pro (behaviour observed in Premiere Pro 26):
@@ -107,7 +113,7 @@ Timecode and Clip Name effects also draw with the text engine.
| `graphics.newShape` | (agents) | `shape` (rectangle/ellipse/polygon/path), `position` (the shape's centre), `size`, `points`, `clip` (add to this graphic), `seconds` (5), `track`, `time` |
| `graphics.setTextType` | Text Properties ▸ Text Layer Type | `clip`, `layer`, `type` (`point` / `paragraph`); the text stays where it is |
| `graphics.setText` | typing on the monitor | `clip`, `layer`, `text`, `merge` (coalesce one typing session into one undo step) |
| `graphics.set` | Properties panel | `clip`, `layer`, `props` {parameter id or camelCase alias: value; choices by index or name}, `time`, `merge` + `begin` (a drag is one undo step: send `merge: true` on every change and `begin: true` on the first change of each press) |
| `graphics.set` | Properties panel | `clip` or `clips` (the same props on that layer of each listed graphic clip, as one undo step; an error on any of them changes none), `layer`, `props` {parameter id or camelCase alias: value; choices by index or name}, `time`, `merge` + `begin` (a drag is one undo step: send `merge: true` on every change and `begin: true` on the first change of each press) |
| `graphics.selectLayer` | layer list / monitor click (Shift-click adds or removes) | `clip`, `layers` |
| `graphics.moveLayers` | dragging selected layers on the Program monitor | `clip`, `layers` (default: the selected layers), `delta` `[dx, dy]` in graphic pixels — one undo step; pinned layers keep following their targets (moved together with its target, a pinned layer moves once, with it) |
| `graphics.deleteLayer`, `graphics.arrangeLayer` | layer list | `clip`, `layer`, `to` (front/back/forward/backward/index) |