feat(shell): File › Import › Import Video: options, progress with Cancel, reference videos on the stage, relink in Layer Properties (M5)

This commit is contained in:
Tanish Manku committed 2026-11-18 08:05:29 -07:00
1 parent bb833c4b85
commit fea891cf59
9 files changed
+578 -11

No files matched your search

+1 -1
View File
@@ -443,7 +443,7 @@ mod tests {
for tool in [Tool::Bone, Tool::Bind, Tool::Warp, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] {
found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool));
}
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "mixedbones", "warp", "sound", "envelope", "audiokeys", "audiokeysevent", "lipsync", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "layeropacity", "pivot", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "richtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] {
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "mixedbones", "warp", "sound", "envelope", "audiokeys", "audiokeysevent", "lipsync", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "layeropacity", "pivot", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "richtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush", "videoimport"] {
found.extend(check(panel, |a, _| a.open_panel(Some(panel))));
}
// Every panel in front where it docks, and floating (ADR 0075); the other workspaces.
+105 -2
View File
@@ -563,6 +563,12 @@ pub struct App {
pub find: crate::find_panel::FindState,
/// File › Publish Settings and the publish running or last run (ADR 0060).
pub publish: crate::publish_panel::PublishState,
/// File › Import › Import Video while its window is open (ADR 0116).
pub video_import: Option<crate::video_import::VideoImport>,
/// The reference videos' pictures for the stage: decoded on demand, within a memory budget.
pub video: anicraft_engine::video::Cache,
/// Why a reference video can't be shown, as last said in the status bar (said once).
pub video_failed: Option<String>,
/// Window › Movie Explorer, the Library dock's other tab (ADR 0058).
pub explorer: crate::movie_explorer::ExplorerView,
pub actions: crate::actions_panel::State,
@@ -864,6 +870,9 @@ impl App {
output_log: Vec::new(),
find: Default::default(),
publish: Default::default(),
video_import: None,
video: Default::default(),
video_failed: None,
explorer: Default::default(),
actions: crate::actions_panel::State::default(),
test_movie: None,
@@ -1358,6 +1367,47 @@ impl App {
}
}
/// A reference video under a tracing layer (ADR 0116), for screenshots: a two-second test
/// film made here with the ffmpeg on this computer, imported as a reference layer, with a
/// few traced strokes on the layer above; its first pictures are waited for (at most a few
/// seconds) so the stage shows them. Without ffmpeg the status bar says so.
#[cfg(not(target_arch = "wasm32"))]
fn open_reference_video(&mut self) {
let clip = std::env::temp_dir().join("anicraft-reference-shot.mkv");
let made = std::process::Command::new(anicraft_engine::video::program(None))
.args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc2=duration=2:size=640x360:rate=24", "-c:v", "mpeg4", "-q:v", "3"])
.arg(&clip)
.stdin(std::process::Stdio::null())
.output()
.is_ok_and(|o| o.status.success());
if !made {
self.status_err(tr!("AniCraft reads video with ffmpeg, which is not on this computer: install it from ffmpeg.org."));
return;
}
self.perform_here("file.import_video", json!({"path": clip.display().to_string(), "mode": "reference"}));
// Traced over it, on the layer above: an outline in ink, as a rotoscoper draws.
self.run("timeline.new_layer", json!({"name": "Tracing"}));
let stage = self.s.doc.stage;
let (cx, cy) = (stage.width as f32 * 0.5, stage.height as f32 * 0.5);
let ring: Vec<[f32; 2]> = (0..=72).map(|i| (i as f32 * 5.0).to_radians()).map(|a| [cx + a.cos() * 118.0, cy + a.sin() * 118.0]).collect();
self.run("draw.freehand", json!({"points": ring, "stroke_width": 4, "stroke": "#ff3d7f"}));
let cross: Vec<[f32; 2]> = (0..=40).map(|i| [cx - 150.0 + i as f32 * 7.5, cy + (i as f32 * 0.3).sin() * 6.0]).collect();
self.run("draw.freehand", json!({"points": cross, "stroke_width": 4, "stroke": "#ff3d7f"}));
self.run("timeline.goto", json!({"frame": 6}));
self.s.mark_saved();
// The frame under the playhead, decoded before the picture is taken.
let doc = self.s.doc.clone();
let frame = self.s.doc.scene_start(self.s.scene) + self.s.frame;
let _ = anicraft_engine::video::shown(&self.video, &doc, frame, true);
self.video.wait_idle(std::time::Duration::from_secs(10));
}
/// A web page can't start ffmpeg (ADR 0036).
#[cfg(target_arch = "wasm32")]
fn open_reference_video(&mut self) {
self.status_err(crate::i18n::t(platform::unavailable("file.import_video").unwrap_or("")));
}
/// `--open` at start-up: shows a panel, for visual checks and documentation screenshots.
/// Imports a two-second beat made here (decaying 220 Hz pulses every half second) to the
/// stage, for screenshots; whether it worked.
@@ -1808,6 +1858,17 @@ impl App {
// Layer Properties (ADR 0061) on the active layer.
crate::layer_props::open(self, None);
}
Some("videoimport") => {
// File › Import › Import Video (ADR 0116) with a film described: the two ways
// to take it, the options and what it will cost (no ffmpeg needed to show it).
let probe = anicraft_engine::video::Probe { width: 1920, height: 1080, duration: Some(8.0), fps: Some(29.97), audio: true };
crate::video_import::open_with(self, PathBuf::from("walk-cycle.mp4"), probe);
if let Some(d) = &mut self.video_import {
d.mode = crate::video_import::Mode::Frames;
d.step = 2;
}
}
Some("video") => self.open_reference_video(),
Some("frameview") => self.tl_frame_view_open = true,
Some("layercolour") => self.tl_color_open = Some(self.s.layer),
Some("timelinepolish") => {
@@ -3254,7 +3315,7 @@ impl App {
/// Any modal (prompt, confirmation, close guard) is open: global shortcuts pause.
pub fn modal_open(&self) -> bool {
self.prompt.is_some() || self.convert.is_some() || self.shape_dialog.is_some() || self.audio_keys.is_some() || self.confirm.is_some() || self.tabs.asking() || self.plugin_dialog.is_some() || self.templates.save.is_some()
self.prompt.is_some() || self.convert.is_some() || self.shape_dialog.is_some() || self.audio_keys.is_some() || self.confirm.is_some() || self.tabs.asking() || self.plugin_dialog.is_some() || self.templates.save.is_some() || self.video_import.is_some()
}
/// The single entry point for user-initiated commands: asks first when the engine says the
@@ -3299,6 +3360,14 @@ impl App {
crate::publish_panel::start(self, &params);
return None;
}
if id == "file.import_video" && params.get("mode").is_none() && !platform::WEB {
// From the menu, with only the file chosen: the Import Video window asks how to
// take it, and decodes with progress and Cancel (ADR 0116).
if let Some(path) = params.get("path").and_then(Value::as_str) {
crate::video_import::open(self, PathBuf::from(path));
return None;
}
}
let selected = self.s.selection.len();
// A browser's autosaved copy opens as a file (ADR 0036): it is a restore all the same.
let restored = autosave::restored_session(id, &params);
@@ -3400,6 +3469,35 @@ impl App {
trn!("Replaced {n} place — {undo} to undo", "Replaced {n} places — {undo} to undo", n, undo = self.undo_key())
});
}
"file.import_video" => {
let undo = self.undo_key();
let n = v["frames"].as_u64().unwrap_or(0);
let from = v["from"].as_u64().unwrap_or(0) + 1;
let mut said = if v["mode"] == "reference" {
// The pictures come from the file as the playhead moves.
self.video.retry();
trn!("The video is on a locked guide layer at the bottom, for {n} frame. Draw on the layers above it; it is never exported. {undo} to undo.", "The video is on a locked guide layer at the bottom, for {n} frames. Draw on the layers above it; it is never exported. {undo} to undo.", n, undo = undo)
} else if v["sound"].is_null() {
trn!("{n} video frame is on a new layer from frame {from}. {undo} to undo.", "{n} video frames are on a new layer from frame {from}. {undo} to undo.", n, from = from, undo = undo)
} else {
trn!("{n} video frame is on a new layer from frame {from}, with its sound on the layer below. {undo} to undo.", "{n} video frames are on a new layer from frame {from}, with their sound on the layer below. {undo} to undo.", n, from = from, undo = undo)
};
if v["truncated"] == true {
said.push(' ');
said.push_str(tr!("The video was longer than one import takes: the rest was left out."));
}
if let Some(note) = v["note"].as_str() {
said.push(' ');
said.push_str(&crate::i18n::t_dyn(note));
}
self.status_ok(said);
}
"layer.set_video" => {
// Another file (or the same one, back): its pictures are read afresh.
self.video.retry();
self.video_failed = None;
self.status_ok(if v["video"].is_null() { tr!("Removed the reference video — {undo} to undo", undo = self.undo_key()) } else { tr!("The reference video is relinked — {undo} to undo", undo = self.undo_key()) });
}
"file.import" => {
if let Some(b) = self.s.doc.bitmaps.last().filter(|b| v["bitmap"].as_u64() == Some(b.id.0)) {
self.library_sel = Some(LibraryItem::Bitmap(b.id));
@@ -3677,6 +3775,10 @@ impl App {
"file.export_audio" => Some((tr_noop!("Export audio (the movie's soundtrack as a WAV)"), "path", "soundtrack.wav".to_string())),
"file.import_to_library" => Some((tr_noop!("Import to library (WAV, OGG or MP3 sound; PNG or JPEG image)"), "path", "sound.wav".to_string())),
"file.import" => Some((tr_noop!("Import to stage (SVG, PNG or JPEG; WAV, OGG or MP3 onto a new layer)"), "path", "drawing.svg".to_string())),
// A video, read by the ffmpeg on this computer (ADR 0116); or another file for the
// active layer's reference video.
"file.import_video" => Some((tr_noop!("Import video (frames in the document, or a reference layer for tracing)"), "path", "video.mp4".to_string())),
"layer.set_video" => Some((tr_noop!("Relink the reference video (choose the video file)"), "path", "video.mp4".to_string())),
"plugin.install" => Some((tr_noop!("Install plug-in (.wasm file)"), "path", "plugin.wasm".to_string())),
// Saved commands (ADR 0097): run a file, or copy one into your commands.
"macro.run" => Some((tr_noop!("Run a saved command (a .json file)"), "path", "command.json".to_string())),
@@ -3693,7 +3795,7 @@ impl App {
_ => None,
};
if let Some((title, key, text)) = prompt {
let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || matches!(id, "plugin.install" | "macro.run" | "macro.import" | "brush.preset_export" | "brush.preset_import" | "filter.preset_export" | "filter.preset_import" | "swatch.export" | "swatch.import"));
let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || matches!(id, "layer.set_video" | "plugin.install" | "macro.run" | "macro.import" | "brush.preset_export" | "brush.preset_import" | "filter.preset_export" | "filter.preset_import" | "swatch.export" | "swatch.import"));
if is_file && platform::WEB && platform::reads_file(id) {
// The browser's file picker (ADR 0036). The file arrives on a later frame
// (`open_picked`); a save or export asks for the download's name below.
@@ -4603,6 +4705,7 @@ impl App {
crate::find_panel::show(self, &ctx);
crate::brush_panel::show(self, &ctx);
crate::publish_panel::show(self, &ctx);
crate::video_import::window(self, &ctx);
crate::test_movie::show(self, &ctx);
crate::envelope::show(self, &ctx);
crate::ease_editor::show(self, &ctx);
+3
View File
@@ -212,6 +212,9 @@ pub const COMMAND_TOPICS: &[(&str, &str)] = &[
("file.new", "getting-started.md#the-start-screen"),
("file.export", "exporting-and-publish.md#exporting-one-format"),
("file.import", "images-and-sound.md#importing-images"),
("file.import_video", "images-and-sound.md#importing-video"),
("file.video_info", "images-and-sound.md#importing-video"),
("layer.set_video", "images-and-sound.md#importing-video"),
("file.publish", "exporting-and-publish.md#publish"),
("file.recovery", "getting-started.md#autosave-and-crash-recovery"),
("filter.", "drawing.md#filters-and-blend-modes"),
+1 -1
View File
@@ -211,7 +211,7 @@ impl Entry {
/// Commands the palette can run without extra input (everything optional, or prompted).
fn runnable(c: &CommandSpec) -> bool {
if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install") {
if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.import_video" | "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install") {
return true;
}
let inner = c.params.trim().trim_start_matches('{').trim_end_matches('}');
+34 -2
View File
@@ -6,7 +6,7 @@
use crate::a11y::Named;
use crate::app::App;
use crate::theme::{FORM_LABEL_DIALOG, Type, form_row, text, to_color32};
use crate::theme::{FORM_LABEL_DIALOG, T, Type, form_row, text, to_color32};
use anicraft_engine::doc::{LayerId, LayerKind, MAX_LAYER_HEIGHT, Rgba};
use egui::Key;
use serde_json::{Value, json};
@@ -100,6 +100,9 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
(i.and_then(|i| tl.mask_above(i)).is_some(), i.and_then(|i| tl.guide_above(i)).is_some(), kind)
};
let fixed = matches!(kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature);
// A reference video (ADR 0116): its file, and whether it is still there.
let video = app.s.timeline().layer(d.layer).and_then(|l| l.video.as_deref()).map(|v| (v.path.clone(), !crate::platform::WEB && !std::path::Path::new(&v.path).is_file()));
let (mut relink, mut remove_video) = (false, false);
let (mut submit, mut cancel) = (false, false);
crate::windows::new(ctx, tr!("Layer Properties")).id(egui::Id::new("layer_props")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
ui.set_min_width(420.0);
@@ -175,6 +178,24 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
ui.add(egui::DragValue::new(&mut d.opacity).range(0.0..=100.0).suffix(" %").speed(1.0).max_decimals(0)).on_hover_text(tip).set_name(tr!("Layer opacity (percent)"));
});
}
if let Some((path, missing)) = &video {
form_row(ui, FORM_LABEL_DIALOG, tr!("Reference video"), |ui| {
ui.vertical(|ui| {
ui.add(egui::Label::new(text(Type::Data, path.as_str())).truncate()).on_hover_text(path.as_str());
if *missing {
ui.label(text(Type::Caption, tr!("This file is missing. Relink it to show the video again.")).color(T.error));
}
ui.horizontal(|ui| {
if ui.button(tr!("Relink…")).on_hover_text(tr!("Choose the video file again: where it moved to, or another video")).clicked() {
relink = true;
}
if ui.button(tr!("Remove Video")).on_hover_text(tr!("The layer stays; it no longer shows a video")).clicked() {
remove_video = true;
}
});
});
});
}
form_row(ui, FORM_LABEL_DIALOG, tr!("Layer height"), |ui| {
egui::ComboBox::from_id_salt("layer_props_height")
.width(96.0)
@@ -199,7 +220,18 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
}
});
});
if submit {
if relink || remove_video {
// The dialog's other changes are dropped, as Cancel drops them: the video command is
// its own undo step.
let layer = app.layer_props.take().map(|d| d.layer.0);
if remove_video {
app.perform("layer.set_video", json!({"layer": layer, "remove": true}));
} else {
// The file dialog's answer goes to the active layer.
app.run("layer.select", json!({"layer": layer}));
app.invoke("layer.set_video");
}
} else if submit {
accept(app);
} else if cancel {
app.layer_props = None;
+2 -1
View File
@@ -97,6 +97,7 @@ mod start;
mod startup;
mod templates;
mod test_movie;
mod video_import;
mod theme;
mod theme_file;
mod timeline;
@@ -299,7 +300,7 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
/// `--help` (the console's text, in English).
#[cfg(not(target_arch = "wasm32"))]
// i18n-exempt: the --help console text
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme dark|light|high-contrast|<file>.json] [--check-theme <file>.json] [--scale <percent>] [--lang <code>|auto|pseudo] [--control <port>] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|shapecommands|expandfill|softenfill|origins|pivot|layeropacity|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme dark|light|high-contrast|<file>.json] [--check-theme <file>.json] [--scale <percent>] [--lang <code>|auto|pseudo] [--control <port>] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|shapecommands|expandfill|softenfill|origins|pivot|layeropacity|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel|video|videoimport]\n\
--renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\
--theme a built-in look, or a theme file of your own, for this run only\n\
--check-theme says whether a theme file would be used (exit 0) or why it is refused (exit 1)\n\
+4 -1
View File
@@ -619,6 +619,7 @@ pub fn unavailable(cmd: &str) -> Option<&'static str> {
}
match cmd {
"file.export_video" => Some(tr_noop!("Video export runs ffmpeg, which a web browser can't start: use the desktop app, or export an animated GIF or a PNG sequence")),
"file.import_video" | "file.video_info" | "layer.set_video" => Some(tr_noop!("Importing video runs ffmpeg, which a web browser can't start: use the desktop app, or import the frames as PNG images")),
"plugin.install" | "plugin.remove" | "plugin.reload" => Some(tr_noop!("Plug-ins are installed into a folder on your computer: use the desktop app")),
"desktop.integrate" | "desktop.remove" | "desktop.status" => Some(tr_noop!("The applications menu belongs to an AppImage on Linux: use the desktop app")),
"file.save_as_template" => Some(tr_noop!("Your templates are kept in a folder on your computer: use the desktop app (the built-in templates work here)")),
@@ -982,6 +983,8 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) {
"file.export_audio" => (tr_noop!("WAV sound"), &["wav"]),
"file.export_sprite_sheet" => (tr_noop!("PNG sprite sheet"), &["png"]),
"file.export_video" => (tr_noop!("Video (WebM or MP4)"), &["webm", "mp4"]),
// Whatever the ffmpeg on this computer reads (ADR 0116); these are the common ones.
"file.import_video" | "layer.set_video" => (tr_noop!("Video"), &["mp4", "mov", "m4v", "webm", "mkv", "avi", "mpg", "mpeg", "wmv", "flv", "ogv", "gif"]),
// Opening also imports .fla archives and .xfl packages.
"file.open" => (tr_noop!("Documents"), &["anicraft", "fla", "xfl"]),
"plugin.install" => (tr_noop!("WebAssembly plug-in"), &["wasm"]),
@@ -996,7 +999,7 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) {
/// Commands that read a file the user picks (the others write one, or a folder of them).
pub fn reads_file(cmd: &str) -> bool {
matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_to_library" | "brush.preset_import" | "filter.preset_import" | "swatch.import" | "macro.run" | "macro.import")
matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_video" | "layer.set_video" | "file.import_to_library" | "brush.preset_import" | "filter.preset_import" | "swatch.import" | "macro.run" | "macro.import")
}
/// Shows the platform's own dialog (Windows common dialog, macOS panel, Linux XDG portal), with
+8 -3
View File
@@ -1029,7 +1029,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
let start = app.s.doc.scene_start(app.s.scene);
let frame = app.s.frame;
// Inside a symbol open in place, onion skin composes the symbol's own frames (ADR 0051).
let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview).inside(pic.front.clone()); (t, j) }).collect();
// Reference videos (ADR 0116): their pictures for this frame, on the stage alone. The
// ones not decoded yet are on their way, and bring a repaint.
let reference = crate::video_import::stage_frames(app, ui.ctx(), &pic.doc, pic.frame, true);
let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview).inside(pic.front.clone()).with_reference(reference.clone()); (t, j) }).collect();
let keys: Vec<u64> = jobs.iter().map(|(_, j)| j.key).collect();
let missing: Vec<usize> = (0..jobs.len()).filter(|&i| !app.stage_cache.has(keys[i])).collect();
@@ -1094,10 +1097,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
let n = app.s.frame_count().max(1);
for d in 1..=LOOKAHEAD.min(n - 1) {
let f = (frame + d) % n;
ahead.extend(jobs.iter().map(|(t, _)| make_job_for(raster, state, &app.s.doc, start + f, t.view, None).through_camera(preview)));
// With the pictures already decoded for that frame (none are asked for).
let then = anicraft_engine::video::shown(&app.video, &app.s.doc, start + f, false).frames;
ahead.extend(jobs.iter().map(|(t, _)| make_job_for(raster, state, &app.s.doc, start + f, t.view, None).through_camera(preview).with_reference(then.clone())));
}
} else {
ahead.extend(tiles_for(z, stage_px, px, 1, bg, pasteboard).into_iter().filter(|t| !jobs.iter().any(|(v, _)| v.rect == t.rect)).map(|t| make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview)));
ahead.extend(tiles_for(z, stage_px, px, 1, bg, pasteboard).into_iter().filter(|t| !jobs.iter().any(|(v, _)| v.rect == t.rect)).map(|t| make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview).with_reference(reference.clone())));
}
svc.prefetch(ahead);
}
+420
View File
@@ -0,0 +1,420 @@
//! File › Import › Import Video (ADR 0116): what the video is, how to take it (frames in the
//! document, or a reference layer to trace over), what that costs before anything starts, then
//! a progress window with Cancel while ffmpeg decodes on another thread. The document changes
//! once, at the end, through `file.import_video` (one undo step); a cancel or a failure leaves
//! it as it was. Reference videos' pictures for the stage come from [`stage_frames`].
use crate::a11y::Named;
use crate::app::App;
use crate::theme::{FORM_LABEL_DIALOG, T, TARGET, Type, form_note, form_row, text};
use anicraft_engine::EngineError;
use anicraft_engine::publish::Control;
use anicraft_engine::video::{self, Options, Prepared, Probe, RefFrame};
use egui::Key;
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, TryRecvError, channel};
/// How the video comes in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
Frames,
Reference,
}
/// What is running on the other thread.
enum Work {
/// ffmpeg is describing the file.
Probing(Receiver<Result<Probe, EngineError>>),
/// ffmpeg is decoding: the import's params, its Cancel and frame count, and the result.
Importing { params: Value, control: Arc<Control>, done: Receiver<Result<Prepared, EngineError>> },
}
/// What the window shows this frame.
enum View {
Importing(Arc<Control>),
Reading,
Failed(String),
Ready(Probe),
}
/// The Import Video window while it is open.
pub struct VideoImport {
pub path: PathBuf,
/// What ffmpeg says the file holds, or why it couldn't say.
pub info: Option<Result<Probe, String>>,
pub mode: Mode,
/// One picture every `step` frames of the document.
pub step: u32,
/// Longest edge of the pictures, in pixels.
pub max_edge: u32,
pub audio: bool,
/// Seconds into the video to begin at, and seconds to take (0: to the end).
pub start: f64,
pub length: f64,
work: Option<Work>,
/// The tab the import is for: a result arriving on another document is dropped.
tab: usize,
}
/// Memory an embedded video may take before the window suggests a reference layer instead.
const COMFORTABLE: u64 = 256 << 20;
fn megabytes(bytes: u64) -> String {
let mb = bytes as f64 / (1024.0 * 1024.0);
if mb >= 1000.0 { format!("{:.1} GB", mb / 1024.0) } else { format!("{:.0} MB", mb.max(1.0)) }
}
fn file_name(path: &std::path::Path) -> String {
path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned())
}
/// Opens the window for the video at `path`; ffmpeg describes the file on another thread.
pub fn open(app: &mut App, path: PathBuf) {
app.playing = false;
let (tx, rx) = channel();
let file = path.clone();
let started = std::thread::Builder::new().name("anicraft-video-probe".into()).spawn(move || {
let _ = tx.send(video::probe(&video::program(None), &file));
});
let mut d = VideoImport { path, info: None, mode: Mode::Frames, step: 1, max_edge: video::DEFAULT_EDGE, audio: true, start: 0.0, length: 0.0, work: Some(Work::Probing(rx)), tab: app.tabs.active() };
if started.is_err() {
d.work = None;
d.info = Some(Err(tr!("The video could not be read: this computer would not start another thread.").to_string()));
}
app.video_import = Some(d);
}
/// The window with a description already in hand (screenshots and tests: no ffmpeg needed).
pub fn open_with(app: &mut App, path: PathBuf, probe: Probe) {
let mut d = VideoImport { path, info: None, mode: Mode::Frames, step: 1, max_edge: video::DEFAULT_EDGE, audio: probe.audio, start: 0.0, length: 0.0, work: None, tab: app.tabs.active() };
described(app, &mut d, probe);
app.video_import = Some(d);
}
/// The options as the engine takes them.
fn options(d: &VideoImport) -> Options {
Options { step: d.step, max_edge: d.max_edge, start: d.start, length: (d.length > 0.0).then_some(d.length), max_frames: video::MAX_EMBED_FRAMES }
}
/// What the import would take, with the document as it is.
fn plan(app: &App, d: &VideoImport, probe: &Probe) -> video::Plan {
let stage = app.s.doc.stage;
video::plan(probe, stage.fps, (stage.width, stage.height), &options(d))
}
/// ffmpeg described the file: a long or large video starts as a reference layer, which costs
/// nothing in the document; a short one as frames, as Animate embeds a video.
fn described(app: &App, d: &mut VideoImport, probe: Probe) {
d.audio = probe.audio;
let p = plan(app, d, &probe);
d.mode = if probe.duration.is_some() && (p.truncated || p.memory > COMFORTABLE) { Mode::Reference } else { Mode::Frames };
d.info = Some(Ok(probe));
}
/// The params `file.import_video` gets for what the window shows.
pub fn params(d: &VideoImport) -> Value {
let mut p = json!({"path": d.path.display().to_string(), "mode": if d.mode == Mode::Frames { "frames" } else { "reference" }});
if d.start > 0.0 {
p["start"] = json!(d.start);
}
if d.mode == Mode::Frames {
p["step"] = json!(d.step);
p["max_edge"] = json!(d.max_edge);
p["audio"] = json!(d.audio);
if d.length > 0.0 {
p["length"] = json!(d.length);
}
}
p
}
/// Import was pressed: ffmpeg decodes on another thread, counted and cancellable.
fn begin(app: &mut App) {
let Some(p) = app.video_import.as_ref().map(params) else { return };
let req = match video::request(&app.s, &p) {
Ok(r) => r,
Err(e) => {
let why = crate::i18n::t_dyn(&e.to_string()).into_owned();
app.status_err(why);
return;
}
};
let control = Arc::new(Control::default());
let (tx, rx) = channel();
let job = control.clone();
let started = std::thread::Builder::new().name("anicraft-video-import".into()).spawn(move || {
let _ = tx.send(video::prepare(&req, Some(&job)));
});
if started.is_err() {
app.status_err(tr!("The video could not be imported: this computer would not start another thread."));
return;
}
if let Some(d) = &mut app.video_import {
d.work = Some(Work::Importing { params: p, control, done: rx });
}
}
/// Takes what the other thread finished. The document changes here, in one command.
fn poll(app: &mut App, ctx: &egui::Context) {
let Some(mut d) = app.video_import.take() else { return };
let Some(work) = d.work.take() else {
app.video_import = Some(d);
return;
};
ctx.request_repaint_after(std::time::Duration::from_millis(50));
match work {
Work::Probing(rx) => {
match rx.try_recv() {
Ok(Ok(probe)) => described(app, &mut d, probe),
Ok(Err(e)) => d.info = Some(Err(crate::i18n::t_dyn(&e.to_string()).into_owned())),
Err(TryRecvError::Empty) => d.work = Some(Work::Probing(rx)),
Err(TryRecvError::Disconnected) => d.info = Some(Err(tr!("The video could not be read.").to_string())),
}
app.video_import = Some(d);
}
Work::Importing { params, control, done } => {
let result = match done.try_recv() {
Ok(r) => r,
Err(TryRecvError::Empty) => {
d.work = Some(Work::Importing { params, control, done });
app.video_import = Some(d);
return;
}
Err(TryRecvError::Disconnected) => Err(EngineError::State("the video could not be read".into())),
};
// Done, one way or another: the window closes.
match result {
// Another document is in front now: this one stays as it is.
Ok(_) if app.tabs.active() != d.tab => app.status_err(tr!("The video was not imported: another document was opened while it was being read. Import it again.")),
Ok(prepared) => {
app.s.staged_video = Some(prepared);
app.perform_here("file.import_video", params);
app.s.staged_video = None;
}
Err(EngineError::Cancelled) => app.status_ok(tr!("Import cancelled. Nothing was changed.")),
Err(e) => {
let why = crate::i18n::t_dyn(&e.to_string()).into_owned();
app.status_err(why);
}
}
}
}
}
/// Cancels the import that is running: ffmpeg stops at its next frame, nothing changes.
pub fn cancel(app: &mut App) {
match app.video_import.as_ref().and_then(|d| d.work.as_ref()) {
Some(Work::Importing { control, .. }) => control.cancel(),
_ => app.video_import = None,
}
}
/// Whether the window is open (it takes the keyboard, as a dialog does).
pub fn is_open(app: &App) -> bool {
app.video_import.is_some()
}
pub fn window(app: &mut App, ctx: &egui::Context) {
poll(app, ctx);
let Some(mut d) = app.video_import.take() else { return };
let importing = matches!(d.work, Some(Work::Importing { .. }));
let title = if importing { tr!("Importing Video") } else { tr!("Import Video") };
let view = match (&d.work, &d.info) {
(Some(Work::Importing { control, .. }), _) => View::Importing(control.clone()),
(Some(Work::Probing(_)), _) | (None, None) => View::Reading,
(None, Some(Err(why))) => View::Failed(why.clone()),
(None, Some(Ok(probe))) => View::Ready(probe.clone()),
};
let (mut submit, mut close) = (false, false);
let mut open = true;
let shown = crate::windows::new(ctx, title).id(egui::Id::new("video_import")).open(&mut open).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -60.0]).show(ctx, |ui| {
ui.set_min_width(460.0);
ui.set_max_width(520.0);
ui.label(text(Type::Body, file_name(&d.path)).strong());
match view {
View::Importing(control) => progress(ui, &control, &mut close),
View::Reading => {
ui.horizontal(|ui| {
ui.spinner();
ui.label(text(Type::Body, tr!("Reading the video with ffmpeg…")));
});
buttons(ui, None, &mut submit, &mut close);
}
View::Failed(why) => {
// No ffmpeg, or a file it can't read: what happened and what to do, in words.
ui.label(text(Type::Body, why).color(T.error));
ui.label(text(Type::Caption, tr!("AniCraft reads video with the ffmpeg on this computer and holds no video decoder of its own. ffmpeg is free: install it from ffmpeg.org (or with your system's package manager), then import again.")).color(T.text_dim));
buttons(ui, None, &mut submit, &mut close);
}
View::Ready(probe) => {
form(app, ui, &mut d, &probe);
buttons(ui, Some(if d.mode == Mode::Frames { tr!("Import") } else { tr!("Add Reference Layer") }), &mut submit, &mut close);
}
}
});
crate::a11y::name_title_bar(&shown, title);
if !open {
close = true;
}
app.video_import = Some(d);
if submit {
begin(app);
} else if close {
cancel(app);
}
}
/// OK and Cancel (`ok`: the first button's label; `None`: only Close).
fn buttons(ui: &mut egui::Ui, ok: Option<&str>, submit: &mut bool, close: &mut bool) {
ui.add_space(6.0);
ui.horizontal(|ui| {
if let Some(ok) = ok {
let r = ui.add(egui::Button::new(ok).min_size(egui::vec2(96.0, TARGET)));
if r.clicked() || ui.input(|i| i.key_pressed(Key::Enter)) {
*submit = true;
}
}
let label = if ok.is_some() { tr!("Cancel") } else { tr!("Close") };
if ui.add(egui::Button::new(label).min_size(egui::vec2(96.0, TARGET))).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) {
*close = true;
}
});
}
/// The decode's progress, with Cancel.
fn progress(ui: &mut egui::Ui, control: &Control, close: &mut bool) {
let (done, total) = control.progress();
let frac = if total > 0 { (done as f32 / total as f32).clamp(0.0, 1.0) } else { 0.0 };
ui.label(text(Type::Body, tr!("Reading frames with ffmpeg. The document changes when it is done.")));
ui.add(egui::ProgressBar::new(frac).desired_width(ui.available_width()).text(text(Type::DataSmall, format!("{done} / {total}")))).named(tr!("Frames read"));
ui.add_space(6.0);
ui.horizontal(|ui| {
let cancelling = control.cancelled();
if ui.add_enabled(!cancelling, egui::Button::new(tr!("Cancel")).min_size(egui::vec2(96.0, TARGET))).on_hover_text(tr!("Stop reading the video. The document stays as it is")).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) {
*close = true;
}
if cancelling {
ui.label(text(Type::Caption, tr!("Stopping…")));
}
});
}
/// The video, the two ways to take it, their options, and what it will cost.
fn form(app: &App, ui: &mut egui::Ui, d: &mut VideoImport, probe: &Probe) {
// What the file is: numbers in the data face.
let mut facts = format!("{} × {}", probe.width, probe.height);
if let Some(s) = probe.duration {
facts.push_str(&format!(" · {s:.2} s"));
}
if let Some(f) = probe.fps {
facts.push_str(&format!(" · {f:.2} fps"));
}
ui.horizontal(|ui| {
ui.label(text(Type::Data, facts).color(T.text_dim));
ui.label(text(Type::Caption, if probe.audio { tr!("with sound") } else { tr!("no sound") }).color(T.text_dim));
});
ui.add_space(4.0);
form_row(ui, FORM_LABEL_DIALOG, tr!("Import as"), |ui| {
ui.vertical(|ui| {
if ui.radio(d.mode == Mode::Frames, tr!("Frames in the document")).on_hover_text(tr!("The video's frames become bitmaps on a new layer, one keyframe each at the document's frame rate, with its sound. They are saved in the document and export with the movie")).clicked() {
d.mode = Mode::Frames;
}
let can = probe.duration.is_some();
let r = ui.add_enabled(can, egui::RadioButton::new(d.mode == Mode::Reference, tr!("Reference layer for tracing")));
let r = if can {
r.on_hover_text(tr!("A locked guide layer under your artwork shows the video as you scrub and play. The video stays a file on this computer and is never in the movie or an export"))
} else {
r.on_disabled_hover_text(tr!("This file doesn't say how long it is, so it can only come in as frames"))
};
if r.clicked() {
d.mode = Mode::Reference;
}
});
});
let last = probe.duration.map_or(86_400.0, |s| (s - 0.01).max(0.0));
form_row(ui, FORM_LABEL_DIALOG, tr!("Start at"), |ui| {
ui.add(egui::DragValue::new(&mut d.start).range(0.0..=last).speed(0.05).max_decimals(2).suffix(" s")).on_hover_text(tr!("Seconds into the video to begin at")).named(tr!("Start at (seconds)"));
});
if d.mode == Mode::Frames {
form_row(ui, FORM_LABEL_DIALOG, tr!("Length"), |ui| {
ui.add(egui::DragValue::new(&mut d.length).range(0.0..=86_400.0).speed(0.05).max_decimals(2).suffix(" s")).on_hover_text(tr!("Seconds of video to take. 0 takes it to its end")).named(tr!("Length (seconds, 0 for all)"));
if d.length <= 0.0 {
ui.label(text(Type::Caption, tr!("to the end")).color(T.text_dim));
}
});
form_row(ui, FORM_LABEL_DIALOG, tr!("Frame step"), |ui| {
ui.add(egui::DragValue::new(&mut d.step).range(1..=video::MAX_STEP).speed(0.1)).on_hover_text(tr!("One picture every this many frames of the document. 2 animates on twos: half the pictures, each held for two frames")).named(tr!("Frame step"));
});
form_row(ui, FORM_LABEL_DIALOG, tr!("Largest size"), |ui| {
ui.add(egui::DragValue::new(&mut d.max_edge).range(16..=video::MAX_DECODE_EDGE).speed(8.0).suffix(" px")).on_hover_text(tr!("The pictures' longest edge. A smaller video is never enlarged; smaller pictures make a smaller document")).named(tr!("Largest size (pixels)"));
});
form_row(ui, FORM_LABEL_DIALOG, tr!("Sound"), |ui| {
ui.add_enabled_ui(probe.audio, |ui| {
let mut on = d.audio && probe.audio;
crate::theme::checkbox(ui, &mut on, tr!("Import the sound track")).on_hover_text(tr!("The video's sound goes on a layer of its own as a stream sound, in time with the frames"));
if probe.audio {
d.audio = on;
}
});
});
}
// Told up front: what comes in, what it costs, and where it is cut short.
let p = plan(app, d, probe);
let from = app.s.frame + 1;
ui.add_space(4.0);
match d.mode {
Mode::Frames => {
let n = p.frames.unwrap_or(p.limit);
let size = format!("{} × {}", p.width, p.height);
let line = if p.frames.is_some() {
trn!("{n} picture of {size} from frame {from}, about {memory} in memory while you edit.", "{n} pictures of {size} from frame {from}, about {memory} in memory while you edit.", u64::from(n), size = size, from = from, memory = megabytes(p.memory))
} else {
trn!("Up to {n} picture of {size} from frame {from}, at most {memory} in memory while you edit.", "Up to {n} pictures of {size} from frame {from}, at most {memory} in memory while you edit.", u64::from(n), size = size, from = from, memory = megabytes(p.memory))
};
form_note(ui, FORM_LABEL_DIALOG, text(Type::Caption, line));
if p.truncated {
let secs = format!("{:.1}", f64::from(n) * f64::from(d.step) / f64::from(app.s.doc.stage.fps.max(1.0)));
form_note(
ui,
FORM_LABEL_DIALOG,
text(Type::Caption, trn!("The video is longer than one import takes: only the first {n} picture ({secs} s) comes in. Raise the frame step, lower the size, shorten the length, or use a reference layer.", "The video is longer than one import takes: only the first {n} pictures ({secs} s) come in. Raise the frame step, lower the size, shorten the length, or use a reference layer.", u64::from(n), secs = secs)).color(T.error),
);
} else if p.memory > COMFORTABLE {
form_note(ui, FORM_LABEL_DIALOG, text(Type::Caption, tr!("That is a large document. A reference layer shows the same video without keeping its frames.")).color(T.text_dim));
}
}
Mode::Reference => {
let frames = probe.duration.map_or(0.0, |s| ((s - d.start).max(0.0) * f64::from(app.s.doc.stage.fps)).ceil());
form_note(
ui,
FORM_LABEL_DIALOG,
text(Type::Caption, tr!("A locked guide layer at the bottom shows the video for {frames} frames from frame {from}. Nothing is added to the document but the file's name; frames are read as you go and kept within {memory}.", frames = frames, from = from, memory = megabytes(video::DEFAULT_CACHE_BYTES))),
);
}
}
}
/// The reference videos' pictures for movie frame `frame` of the stage picture `doc`, asking
/// for the ones that aren't decoded yet when `ask` (the frame on screen; frames rendered ahead
/// only take what is there). Pictures on their way bring a repaint; a video that can't be
/// shown is said once in the status bar.
pub fn stage_frames(app: &mut App, ctx: &egui::Context, doc: &anicraft_engine::doc::Document, frame: u32, ask: bool) -> Option<Arc<Vec<RefFrame>>> {
let shown = video::shown(&app.video, doc, frame, ask);
if !ask {
return shown.frames;
}
if shown.pending {
ctx.request_repaint_after(std::time::Duration::from_millis(30));
}
match shown.failed {
Some((_, why)) if app.video_failed.as_deref() != Some(why.as_str()) => {
app.status_err(tr!("The reference video can't be shown: {why}", why = crate::i18n::t_dyn(&why)));
app.video_failed = Some(why);
}
Some(_) => {}
None => app.video_failed = None,
}
shown.frames
}