Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

cache media artwork as project JPEGs

Domicaf4b3527e9842
diff --git a/engine/crates/concat-core/src/shader.rs b/engine/crates/concat-core/src/shader.rs
index 87a07003..c5c67afe 100644
--- a/engine/crates/concat-core/src/shader.rs
+++ b/engine/crates/concat-core/src/shader.rs
@@ -150,7 +150,12 @@ mod tests {
#[test]
fn the_identity_table_returns_what_it_is_given() {
let lut = Lut::identity(17);
- for rgb in [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.25, 0.5, 0.75], [0.9, 0.1, 0.3]] {
+ for rgb in [
+ [0.0, 0.0, 0.0],
+ [1.0, 1.0, 1.0],
+ [0.25, 0.5, 0.75],
+ [0.9, 0.1, 0.3],
+ ] {
let out = lut.sample(rgb);
for (a, b) in out.iter().zip(rgb.iter()) {
assert!((a - b).abs() < 0.01, "{rgb:?} -> {out:?}");
diff --git a/engine/crates/concat-effects/examples/previews.rs b/engine/crates/concat-effects/examples/previews.rs
index 0e9c1b78..93b89809 100644
--- a/engine/crates/concat-effects/examples/previews.rs
+++ b/engine/crates/concat-effects/examples/previews.rs
@@ -49,7 +49,17 @@ fn main() {
let name = id.rsplit('.').next().unwrap_or(id);
let target = out.join(format!("{name}.jpg"));
let status = Command::new("ffmpeg")
- .args(["-y", "-loglevel", "error", "-i", &still, "-vf", &chain, "-q:v", "3"])
+ .args([
+ "-y",
+ "-loglevel",
+ "error",
+ "-i",
+ &still,
+ "-vf",
+ &chain,
+ "-q:v",
+ "3",
+ ])
.arg(&target)
.status();
match status {
diff --git a/engine/crates/concat-effects/src/catalogue.rs b/engine/crates/concat-effects/src/catalogue.rs
index e5f415d8..a73ff19e 100644
--- a/engine/crates/concat-effects/src/catalogue.rs
+++ b/engine/crates/concat-effects/src/catalogue.rs
@@ -636,7 +636,12 @@ impl Catalogue {
1.0
};
let values = package.resolve(&set);
- Some(shader.pass(&values, &package.manifest.params, intensity, package.lut.clone()))
+ Some(shader.pass(
+ &values,
+ &package.manifest.params,
+ intensity,
+ package.lut.clone(),
+ ))
})
.collect()
}
diff --git a/engine/crates/concat-effects/src/cube.rs b/engine/crates/concat-effects/src/cube.rs
index 1a250c5d..653c1788 100644
--- a/engine/crates/concat-effects/src/cube.rs
+++ b/engine/crates/concat-effects/src/cube.rs
@@ -95,7 +95,12 @@ mod tests {
for g in 0..n {
for r in 0..n {
let s = 1.0 / (n - 1) as f32;
- text.push_str(&format!("{} {} {}\n", r as f32 * s, g as f32 * s, b as f32 * s));
+ text.push_str(&format!(
+ "{} {} {}\n",
+ r as f32 * s,
+ g as f32 * s,
+ b as f32 * s
+ ));
}
}
}
@@ -107,7 +112,11 @@ mod tests {
let lut = parse(&identity(9)).expect("parses");
assert_eq!(lut.size, 9);
let out = lut.sample([0.3, 0.6, 0.9]);
- assert!((out[0] - 0.3).abs() < 0.01 && (out[1] - 0.6).abs() < 0.01 && (out[2] - 0.9).abs() < 0.01);
+ assert!(
+ (out[0] - 0.3).abs() < 0.01
+ && (out[1] - 0.6).abs() < 0.01
+ && (out[2] - 0.9).abs() < 0.01
+ );
}
#[test]
diff --git a/engine/crates/concat-effects/src/lib.rs b/engine/crates/concat-effects/src/lib.rs
index afc9a84a..827d561b 100644
--- a/engine/crates/concat-effects/src/lib.rs
+++ b/engine/crates/concat-effects/src/lib.rs
@@ -133,8 +133,17 @@ mod tests {
.ffmpeg_fragment(&BTreeMap::new(), 0)
.expect("renders")
.expect("has a chain");
- assert!(chain.starts_with("lut3d=file='") && chain.ends_with("look.cube'"), "{chain}");
- assert_eq!(catalogue.shader_passes(&[AppliedFilter::new("test.table")])[0].lut.as_ref().map(|l| l.size), Some(2));
+ assert!(
+ chain.starts_with("lut3d=file='") && chain.ends_with("look.cube'"),
+ "{chain}"
+ );
+ assert_eq!(
+ catalogue.shader_passes(&[AppliedFilter::new("test.table")])[0]
+ .lut
+ .as_ref()
+ .map(|l| l.size),
+ Some(2)
+ );
let _ = std::fs::remove_dir_all(&dir);
}
diff --git a/engine/crates/concat-host/src/brush.rs b/engine/crates/concat-host/src/brush.rs
index 0889913f..ee019aaf 100644
--- a/engine/crates/concat-host/src/brush.rs
+++ b/engine/crates/concat-host/src/brush.rs
@@ -29,7 +29,9 @@ use concat_core::frame::Frame;
use concat_core::time::{FrameRate, Rational};
use concat_media::{DecodeOptions, Decoder, FrameSource};
use concat_project::model::{Stroke, Subject};
-use concat_vision::{Brush, Embedding, MASK_RATE, Mask, MaskStore, ModelId, mask_dir, models, region_dir};
+use concat_vision::{
+ Brush, Embedding, MASK_RATE, Mask, MaskStore, ModelId, mask_dir, models, region_dir,
+};
use crate::cutout::Progress;
use crate::jobs::SingleFlight;
@@ -122,7 +124,12 @@ impl Brushes {
cancel: &AtomicBool,
progress: &mut dyn FnMut(Progress),
) -> Result<Arc<Brush>, String> {
- if let Some(loaded) = self.brush.lock().map_err(|_| "brush slot poisoned")?.as_ref() {
+ if let Some(loaded) = self
+ .brush
+ .lock()
+ .map_err(|_| "brush slot poisoned")?
+ .as_ref()
+ {
return Ok(Arc::clone(loaded));
}
let encoder = models::model_file(&self.data, ModelId::BrushEncoder);
diff --git a/engine/crates/concat-host/src/cutout.rs b/engine/crates/concat-host/src/cutout.rs
index df5098b9..33866f45 100644
--- a/engine/crates/concat-host/src/cutout.rs
+++ b/engine/crates/concat-host/src/cutout.rs
@@ -344,7 +344,8 @@ impl Cutouts {
active = self.downloaded(ModelId::Object, &cancel, progress)?;
decoder = open(&active)?;
active.begin();
- let Some(again) = decoder.next_frame().map_err(|error| error.to_string())?
+ let Some(again) =
+ decoder.next_frame().map_err(|error| error.to_string())?
else {
break;
};
diff --git a/engine/crates/concat-host/src/preview.rs b/engine/crates/concat-host/src/preview.rs
index d73bb160..d586b5d6 100644
--- a/engine/crates/concat-host/src/preview.rs
+++ b/engine/crates/concat-host/src/preview.rs
@@ -156,7 +156,10 @@ impl Monitor {
gpu: bool,
) -> Arc<concat_export::PreviewPlan> {
let rate = (settings.rate_num, settings.rate_den);
- let mut slot = self.plan.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ let mut slot = self
+ .plan
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(entry) = slot.as_ref()
&& entry.width == spec.width
&& entry.height == spec.height
@@ -219,6 +222,9 @@ impl Monitor {
/// closes.
pub fn clear(&self) {
self.pool.clear();
- *self.plan.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
+ *self
+ .plan
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
}
}
diff --git a/engine/crates/concat-media/src/pool.rs b/engine/crates/concat-media/src/pool.rs
index 98832747..01615eca 100644
--- a/engine/crates/concat-media/src/pool.rs
+++ b/engine/crates/concat-media/src/pool.rs
@@ -696,10 +696,21 @@ mod tests {
let pool = ReaderPool::new(1, 4);
for attempt in 0..3 {
let got = pool
- .frame_at(&path, FrameRate::THIRTY.time_of_frame(attempt), 64, 64, true, None, None)
+ .frame_at(
+ &path,
+ FrameRate::THIRTY.time_of_frame(attempt),
+ 64,
+ 64,
+ true,
+ None,
+ None,
+ )
.unwrap_or_else(|error| panic!("request {attempt} decodes: {error}"));
let red = got.pixel(32, 32).expect("in bounds")[0];
- assert!(red > 150, "request {attempt} read red {red}, wanted the still");
+ assert!(
+ red > 150,
+ "request {attempt} read red {red}, wanted the still"
+ );
}
let _ = std::fs::remove_file(&path);
diff --git a/engine/crates/concat-render/src/gpu.rs b/engine/crates/concat-render/src/gpu.rs
index 8113f269..86b30b3c 100644
--- a/engine/crates/concat-render/src/gpu.rs
+++ b/engine/crates/concat-render/src/gpu.rs
@@ -1297,7 +1297,12 @@ mod tests {
.expect("compiles");
let red = solid(4, 4, [255, 0, 0, 255]);
let green = Lut::from_rgb(2, &[0.0, 1.0, 0.0].repeat(8)).expect("a table");
- let tabled = [shader.pass(&Default::default(), &[], 1.0, Some(std::sync::Arc::new(green)))];
+ let tabled = [shader.pass(
+ &Default::default(),
+ &[],
+ 1.0,
+ Some(std::sync::Arc::new(green)),
+ )];
let out = gpu.composite(4, 4, &[Layer::new(&red).with_passes(&tabled)]);
assert_eq!(&out.pixels()[..3], &[0, 255, 0]);
let plain = [shader.pass(&Default::default(), &[], 1.0, None)];
@@ -1325,7 +1330,11 @@ mod tests {
let red = solid(8, 8, [255, 0, 0, 255]);
let blue = solid(4, 4, [0, 0, 255, 255]);
let layers = [(Layer::new(&red), 0), (Layer::new(&blue), 2)];
- let full = [Treatment { track: 1, passes: &passes, strength: 1.0 }];
+ let full = [Treatment {
+ track: 1,
+ passes: &passes,
+ strength: 1.0,
+ }];
let out = gpu
.composite_treated(8, 8, 0.0, &layers, &full)
.expect("drawn");
@@ -1333,12 +1342,19 @@ mod tests {
assert_eq!(&out.pixels()[..3], &[0, 0, 255]);
let last = out.pixels().len() - 4;
assert_eq!(&out.pixels()[last..last + 3], &[0, 255, 255]);
- let half = [Treatment { track: 1, passes: &passes, strength: 0.5 }];
+ let half = [Treatment {
+ track: 1,
+ passes: &passes,
+ strength: 0.5,
+ }];
let out = gpu
.composite_treated(8, 8, 0.0, &layers, &half)
.expect("drawn");
let p = &out.pixels()[last..last + 3];
- assert!(p[0] > 120 && p[0] < 136 && p[1] > 120 && p[1] < 136, "{p:?}");
+ assert!(
+ p[0] > 120 && p[0] < 136 && p[1] > 120 && p[1] < 136,
+ "{p:?}"
+ );
}
fn gpu() -> Option<WgpuCompositor> {
diff --git a/engine/crates/concat-vision/src/apply.rs b/engine/crates/concat-vision/src/apply.rs
index 86d7c416..82364f62 100644
--- a/engine/crates/concat-vision/src/apply.rs
+++ b/engine/crates/concat-vision/src/apply.rs
@@ -130,8 +130,8 @@ pub fn highlight(frame: &mut Frame, mask: &Mask, mapping: &Mapping, colour: [u8;
// it is not: the tint reads as the mask's own edge.
let mix = mask.sample(u, v) * 0.55;
for c in 0..3 {
- pixel[c] = (f32::from(pixel[c]) * (1.0 - mix) + f32::from(colour[c]) * mix + 0.5)
- as u8;
+ pixel[c] =
+ (f32::from(pixel[c]) * (1.0 - mix) + f32::from(colour[c]) * mix + 0.5) as u8;
}
}
}
diff --git a/engine/crates/concat-vision/src/brush.rs b/engine/crates/concat-vision/src/brush.rs
index 1fd3a23c..74995fa8 100644
--- a/engine/crates/concat-vision/src/brush.rs
+++ b/engine/crates/concat-vision/src/brush.rs
@@ -107,7 +107,10 @@ impl Brush {
.encoder
.lock()
.map_err(|_| "brush encoder poisoned".to_owned())?
- .run(vec![input], &["image_embeddings", "image_positional_embeddings"])?;
+ .run(
+ vec![input],
+ &["image_embeddings", "image_positional_embeddings"],
+ )?;
let positional = outputs.pop().ok_or("brush: no positional embeddings")?;
let image = outputs.pop().ok_or("brush: no image embeddings")?;
Ok(Embedding {
@@ -157,7 +160,9 @@ impl Brush {
.into_iter()
.map(|(_, mask)| (overlap(&mask, previous), mask))
.max_by(|a, b| a.0.total_cmp(&b.0));
- Ok(best.filter(|(iou, _)| *iou >= STILL_IT).map(|(_, mask)| mask))
+ Ok(best
+ .filter(|(iou, _)| *iou >= STILL_IT)
+ .map(|(_, mask)| mask))
}
/// The model's three answers for `picked` points, each with the
@@ -223,8 +228,8 @@ impl Brush {
let logits = &masks[index * plane..(index + 1) * plane];
let mut bytes = Vec::with_capacity(size * size);
for y in 0..size {
- let py = ((y as f32 + 0.5) / size as f32) * sh / SAM_SIZE as f32
- * SAM_MASK as f32;
+ let py =
+ ((y as f32 + 0.5) / size as f32) * sh / SAM_SIZE as f32 * SAM_MASK as f32;
for x in 0..size {
let px = ((x as f32 + 0.5) / size as f32) * sw / SAM_SIZE as f32
* SAM_MASK as f32;
@@ -260,8 +265,12 @@ fn interior_points(region: &Mask) -> Vec<[f64; 2]> {
// The region's box, cut into a grid; the sure pixel nearest each
// cell's centre is a prompt, so the prompts cover the thing rather
// than cluster.
- let (x0, x1) = sure.iter().fold((usize::MAX, 0), |(lo, hi), &(x, _)| (lo.min(x), hi.max(x)));
- let (y0, y1) = sure.iter().fold((usize::MAX, 0), |(lo, hi), &(_, y)| (lo.min(y), hi.max(y)));
+ let (x0, x1) = sure
+ .iter()
+ .fold((usize::MAX, 0), |(lo, hi), &(x, _)| (lo.min(x), hi.max(x)));
+ let (y0, y1) = sure
+ .iter()
+ .fold((usize::MAX, 0), |(lo, hi), &(_, y)| (lo.min(y), hi.max(y)));
let cells = (AT_MOST as f64).sqrt().round() as usize;
let mut out = Vec::new();
for cy in 0..cells {
@@ -277,7 +286,10 @@ fn interior_points(region: &Mask) -> Vec<[f64; 2]> {
// thing's; skip it rather than prompt beside the thing.
let reach = ((x1 - x0).max(y1 - y0) as f64 / cells as f64).max(2.0);
if distance.sqrt() <= reach {
- out.push([(x as f64 + 0.5) / width as f64, (y as f64 + 0.5) / height as f64]);
+ out.push([
+ (x as f64 + 0.5) / width as f64,
+ (y as f64 + 0.5) / height as f64,
+ ]);
}
}
}
@@ -302,7 +314,11 @@ fn overlap(a: &Mask, b: &Mask) -> f32 {
either += u32::from(in_a || in_b);
}
}
- if either == 0 { 0.0 } else { both as f32 / either as f32 }
+ if either == 0 {
+ 0.0
+ } else {
+ both as f32 / either as f32
+ }
}
/// A value from a square plane, bilinear between the four around it,
@@ -343,7 +359,10 @@ mod tests {
let points = interior_points(&region);
assert!(!points.is_empty() && points.len() <= 9);
for [x, y] in &points {
- assert!((0.25..0.75).contains(x) && (0.25..0.75).contains(y), "{x} {y}");
+ assert!(
+ (0.25..0.75).contains(x) && (0.25..0.75).contains(y),
+ "{x} {y}"
+ );
}
assert_eq!(overlap(&region, &region), 1.0);
let empty = Mask::filled(32, 32, 0);
diff --git a/engine/crates/concat-vision/src/mask.rs b/engine/crates/concat-vision/src/mask.rs
index 7be3ab67..f83320e5 100644
--- a/engine/crates/concat-vision/src/mask.rs
+++ b/engine/crates/concat-vision/src/mask.rs
@@ -81,13 +81,19 @@ impl Mask {
let mut sum = 0u32;
for dy in 0..factor {
for dx in 0..factor {
- sum += u32::from(self.at(i64::from(x * factor + dx), i64::from(y * factor + dy)));
+ sum += u32::from(
+ self.at(i64::from(x * factor + dx), i64::from(y * factor + dy)),
+ );
}
}
data.push((sum / (factor * factor)) as u8);
}
}
- Mask { width, height, data }
+ Mask {
+ width,
+ height,
+ data,
+ }
}
/// The value at a pixel, clamped to the edge.
diff --git a/engine/crates/concat-vision/src/runtime.rs b/engine/crates/concat-vision/src/runtime.rs
index bfd78917..b9336006 100644
--- a/engine/crates/concat-vision/src/runtime.rs
+++ b/engine/crates/concat-vision/src/runtime.rs
@@ -90,8 +90,10 @@ impl Model {
/// Runs the model on `inputs` and returns the named outputs, in the
/// order asked for.
pub fn run(&mut self, inputs: Vec<Input<'_>>, outputs: &[&str]) -> Result<Vec<Output>, String> {
- let mut fed: Vec<(std::borrow::Cow<'static, str>, ort::session::SessionInputValue<'_>)> =
- Vec::with_capacity(inputs.len());
+ let mut fed: Vec<(
+ std::borrow::Cow<'static, str>,
+ ort::session::SessionInputValue<'_>,
+ )> = Vec::with_capacity(inputs.len());
for input in inputs {
let value: ort::session::SessionInputValue<'_> = match input.data {
Data::F32(data) => Tensor::from_array((input.dims, data))
diff --git a/engine/crates/concat-vision/src/store.rs b/engine/crates/concat-vision/src/store.rs
index 47b2f551..925af3ce 100644
--- a/engine/crates/concat-vision/src/store.rs
+++ b/engine/crates/concat-vision/src/store.rs
@@ -40,10 +40,11 @@ const CACHED: usize = 300;
/// folder. The subject is in it too, so a clip asked to keep the person
/// and one asked to keep the object never read each other's answer.
pub fn mask_dir(project: &Path, media_path: &str, subject: Subject) -> PathBuf {
- project
- .join("cache")
- .join("masks")
- .join(format!("{:016x}-{}", fnv1a(media_path.as_bytes()), subject.key()))
+ project.join("cache").join("masks").join(format!(
+ "{:016x}-{}",
+ fnv1a(media_path.as_bytes()),
+ subject.key()
+ ))
}
/// The file naming the model that made a directory's masks.
@@ -319,7 +320,9 @@ fn settings_key(
}
for (key, store) in region_stores {
key.hash(&mut hasher);
- store.nearest_millis(millis as f64 / 1000.0).hash(&mut hasher);
+ store
+ .nearest_millis(millis as f64 / 1000.0)
+ .hash(&mut hasher);
}
}
hasher.finish()
diff --git a/engine/crates/concat/Cargo.toml b/engine/crates/concat/Cargo.toml
index 9456f0f2..7abc7fa7 100644
--- a/engine/crates/concat/Cargo.toml
+++ b/engine/crates/concat/Cargo.toml
@@ -106,6 +106,9 @@ serde_json.workspace = true
# Text presets are TOML files, as the effect manifests are.
toml = "1.1"
+# JPEG encoding for the media artwork cache.
+image = { version = "0.25", default-features = false, features = ["jpeg"] }
+
# The renderer is picked by a feature here rather than by editing the
# dependency, so both variants build from one tree and can be compared:
#
diff --git a/engine/crates/concat/src/host.rs b/engine/crates/concat/src/host.rs
index b1758ba2..b33018ee 100644
--- a/engine/crates/concat/src/host.rs
+++ b/engine/crates/concat/src/host.rs
@@ -284,6 +284,159 @@ pub fn image_at(path: &std::path::Path) -> Option<slint::Image> {
slint::Image::load_from_path(path).ok()
}
+/// A filmstrip restored from the project's artwork cache.
+pub struct CachedStrip {
+ /// The strip image.
+ pub image: slint::Image,
+ /// How many frames the picture holds.
+ pub frames: u32,
+ /// One frame's width in the picture's pixels.
+ pub frame_width: u32,
+ /// The picture's height in pixels.
+ pub height: u32,
+}
+
+/// Artwork restored from the project's cache.
+pub struct CachedMediaArt {
+ /// Cached thumbnail, when present.
+ pub thumbnail: Option<slint::Image>,
+ /// Cached filmstrip, when present.
+ pub strip: Option<CachedStrip>,
+}
+
+/// Loads a media item's thumbnail and filmstrip from the project's JPEG cache.
+///
+/// The cache key includes the media id plus the source file's size and mtime,
+/// so replacing a file with the same project media id naturally misses and
+/// regenerates fresh artwork.
+pub fn cached_media_art(
+ project: &str,
+ id: &str,
+ path: &str,
+ kind: concat_project::model::MediaKind,
+) -> CachedMediaArt {
+ use concat_project::model::MediaKind;
+
+ if kind == MediaKind::Audio {
+ return CachedMediaArt {
+ thumbnail: None,
+ strip: None,
+ };
+ }
+
+ let dir = art_cache_dir(project);
+ let stem = art_cache_stem(id, path);
+
+ let thumbnail = image_at(&dir.join(format!("{stem}.thumb.jpg")));
+
+ let strip = std::fs::read_dir(&dir).ok().and_then(|entries| {
+ let prefix = format!("{stem}.strip.");
+ entries.filter_map(Result::ok).find_map(|entry| {
+ let name = entry.file_name();
+ let name = name.to_str()?;
+ let rest = name.strip_prefix(&prefix)?.strip_suffix(".jpg")?;
+ let mut parts = rest.split('.');
+ let frames: u32 = parts.next()?.parse().ok()?;
+ let frame_width: u32 = parts.next()?.parse().ok()?;
+ let height: u32 = parts.next()?.parse().ok()?;
+ if parts.next().is_some() {
+ return None;
+ }
+ let image = image_at(&entry.path())?;
+ Some(CachedStrip {
+ image,
+ frames,
+ frame_width,
+ height,
+ })
+ })
+ });
+
+ CachedMediaArt { thumbnail, strip }
+}
+
+fn art_cache_dir(project: &str) -> std::path::PathBuf {
+ std::path::Path::new(project).join("cache").join("art")
+}
+
+fn art_cache_stem(id: &str, path: &str) -> String {
+ format!("{}-{}", clean_cache_part(id), source_stamp(path))
+}
+
+fn clean_cache_part(text: &str) -> String {
+ text.chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
+ c
+ } else {
+ '_'
+ }
+ })
+ .collect()
+}
+
+fn source_stamp(path: &str) -> String {
+ let Ok(meta) = std::fs::metadata(path) else {
+ return "missing".to_owned();
+ };
+ let len = meta.len();
+ let modified = meta
+ .modified()
+ .ok()
+ .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|duration| duration.as_secs())
+ .unwrap_or(0);
+ format!("{len:x}-{modified:x}")
+}
+
+fn save_media_art_cache(
+ project: &str,
+ id: &str,
+ path: &str,
+ thumbnail: Option<&concat_core::frame::Frame>,
+ strip: Option<(&concat_core::frame::Frame, u32)>,
+) {
+ let dir = art_cache_dir(project);
+ if std::fs::create_dir_all(&dir).is_err() {
+ return;
+ }
+
+ let stem = art_cache_stem(id, path);
+
+ if let Some(frame) = thumbnail {
+ let _ = save_frame_jpeg(&dir.join(format!("{stem}.thumb.jpg")), frame, 82);
+ }
+
+ if let Some((frame, frames)) = strip {
+ let frames = frames.max(1);
+ let frame_width = frame.width() / frames;
+ let name = format!("{stem}.strip.{frames}.{frame_width}.{}.jpg", frame.height());
+ let _ = save_frame_jpeg(&dir.join(name), frame, 78);
+ }
+}
+
+fn save_frame_jpeg(
+ path: &std::path::Path,
+ frame: &concat_core::frame::Frame,
+ quality: u8,
+) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
+ let mut rgb = Vec::with_capacity(frame.width() as usize * frame.height() as usize * 3);
+ for pixel in frame.pixels().chunks_exact(4) {
+ rgb.extend_from_slice(&pixel[..3]);
+ }
+
+ let file = std::fs::File::create(path)?;
+ let mut writer = std::io::BufWriter::new(file);
+ let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut writer, quality);
+ encoder.encode(
+ &rgb,
+ frame.width(),
+ frame.height(),
+ image::ColorType::Rgb8.into(),
+ )?;
+ Ok(())
+}
+
/// A probe's error, in the words a toast can use.
pub fn probe_error(error: &str) -> String {
format!("Could not import: {error}")
@@ -326,6 +479,7 @@ pub fn media_art(
duration: Option<f64>,
project: String,
stream: Option<u32>,
+ pictures: bool,
) -> MediaArt {
use concat_project::model::MediaKind;
if stream.is_some() {
@@ -339,25 +493,44 @@ pub fn media_art(
strip: None,
};
}
- let thumbnail = match kind {
- MediaKind::Video | MediaKind::Image => {
- // Within the first two seconds, so the walk from the keyframe
- // before it is at most those two seconds of frames.
- let at = duration.map_or(0.0, |seconds| (seconds * 0.25).min(2.0));
- media::still_at(&path, if kind == MediaKind::Image { 0.0 } else { at }, 160).ok()
+ let thumbnail = if pictures {
+ match kind {
+ MediaKind::Video | MediaKind::Image => {
+ // Within the first two seconds, so the walk from the keyframe
+ // before it is at most those two seconds of frames.
+ let at = duration.map_or(0.0, |seconds| (seconds * 0.25).min(2.0));
+ media::still_at(&path, if kind == MediaKind::Image { 0.0 } else { at }, 160).ok()
+ }
+ MediaKind::Audio => None,
}
- MediaKind::Audio => None,
+ } else {
+ None
};
let peaks = (kind == MediaKind::Audio || has_audio)
.then(|| media::peaks(&path, None, Some(&project)).ok().map(Arc::new))
.flatten();
- let strip = match kind {
- MediaKind::Video => media::filmstrip(&path, STRIP_FRAMES, STRIP_HEIGHT)
- .ok()
- .map(|frame| (frame, STRIP_FRAMES)),
- MediaKind::Image => thumbnail.clone().map(|frame| (frame, 1)),
- MediaKind::Audio => None,
+ let strip = if pictures {
+ match kind {
+ MediaKind::Video => media::filmstrip(&path, STRIP_FRAMES, STRIP_HEIGHT)
+ .ok()
+ .map(|frame| (frame, STRIP_FRAMES)),
+ MediaKind::Image => thumbnail.clone().map(|frame| (frame, 1)),
+ MediaKind::Audio => None,
+ }
+ } else {
+ None
};
+
+ if pictures {
+ save_media_art_cache(
+ &project,
+ &id,
+ &path,
+ thumbnail.as_ref(),
+ strip.as_ref().map(|(frame, frames)| (frame, *frames)),
+ );
+ }
+
MediaArt {
id,
stream: None,
diff --git a/engine/crates/concat/src/studio.rs b/engine/crates/concat/src/studio.rs
index 12d989d4..7fafd3c1 100644
--- a/engine/crates/concat/src/studio.rs
+++ b/engine/crates/concat/src/studio.rs
@@ -45,7 +45,9 @@ use crate::dock::{
use crate::format::{
bytes, colour_of, eta, frames_timecode, hex_of, hex_with_alpha, wave_path, when_phrase,
};
-use crate::host::{Host, MediaArt, image_at, image_of, media_art, on_ui, spawn, spawn_art};
+use crate::host::{
+ Host, MediaArt, cached_media_art, image_at, image_of, media_art, on_ui, spawn, spawn_art,
+};
use crate::i18n::{self, t, tf};
use crate::prefs::{AudioTracks, Preferences};
use crate::presets::{self, TextPreset};
@@ -2141,6 +2143,7 @@ impl Studio {
has_audio: bool,
duration: Option<f64>,
stream: Option<u32>,
+ pictures: bool,
}
let project = self.project();
let mut wanted: Vec<Want> = project
@@ -2163,6 +2166,7 @@ impl Studio {
has_audio: item.has_audio,
duration: item.duration,
stream: None,
+ pictures: item.kind != model::MediaKind::Audio,
})
.collect();
// The other streams clips have chosen, once each.
@@ -2199,23 +2203,59 @@ impl Studio {
has_audio: item.has_audio,
duration: item.duration,
stream: Some(stream),
+ pictures: false,
});
}
for want in wanted {
- self.art_pending.insert(want.key);
- let project = project_path.clone();
let Want {
+ key,
id,
path,
kind,
has_audio,
duration,
stream,
- ..
+ mut pictures,
} = want;
+
+ // Restore pictures from the project's JPEG artwork cache before
+ // starting a decoder. Peaks already have their own disk cache in
+ // concat-media; thumbnails and filmstrips are what used to be
+ // recreated on every project open.
+ if stream.is_none() && kind != model::MediaKind::Audio {
+ let cached = cached_media_art(&project_path, &id, &path, kind);
+ if let Some(image) = cached.thumbnail {
+ self.thumbs.insert(id.clone(), image);
+ }
+ if let Some(strip) = cached.strip {
+ self.strips.insert(
+ id.clone(),
+ Strip {
+ image: strip.image,
+ frames: strip.frames as i32,
+ frame_width: strip.frame_width as i32,
+ height: strip.height as i32,
+ },
+ );
+ }
+ pictures = !self.thumbs.contains_key(&id) || !self.strips.contains_key(&id);
+ }
+
+ let needs_peaks =
+ (kind == model::MediaKind::Audio || has_audio) && !self.peaks.contains_key(&key);
+ if !pictures && !needs_peaks {
+ continue;
+ }
+
+ self.art_pending.insert(key);
+ let project = project_path.clone();
// On the artwork lane, a few at a time - see host.rs.
spawn_art(
- move || media_art(id, path, kind, has_audio, duration, project, stream),
+ move || {
+ media_art(
+ id, path, kind, has_audio, duration, project, stream, pictures,
+ )
+ },
|studio, _, _, art: MediaArt| {
let key = art_key(&art.id, art.stream);
studio.art_pending.remove(&key);
@@ -7172,7 +7212,8 @@ fn script_captions(text: &str) -> Vec<(String, f64)> {
.flat_map(sentences)
.flat_map(|sentence| wrap_caption(&sentence))
.map(|line| {
- let seconds = (line.chars().count() as f64 / f64::from(CHARS_PER_SECOND)).clamp(1.0, 7.0);
+ let seconds =
+ (line.chars().count() as f64 / f64::from(CHARS_PER_SECOND)).clamp(1.0, 7.0);
(line, seconds)
})
.collect()
@@ -7270,7 +7311,11 @@ mod tests {
"Ok?",
]
);
- assert!(lines.iter().all(|(_, seconds)| (1.0..=7.0).contains(seconds)));
+ assert!(
+ lines
+ .iter()
+ .all(|(_, seconds)| (1.0..=7.0).contains(seconds))
+ );
assert_eq!(lines[0].1, 1.0);
assert!(lines[2].1 > lines[0].1);
assert!(script_captions(" \n ").is_empty());