GitCorner

Code

ossartcraftfilmcraft🌐
f67d38b35cc5
//! FilmCraft headless CLI: every engine command is one shell call away, for scripts and AI agents.
//!
//! Run `filmcraft-cli help` for the full reference (also in docs/agents.md).

#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]

/// `println!` that doesn't panic when stdout is closed (`filmcraft-cli commands | head`) with
/// "failed printing to stdout: Broken pipe (os error 32)". Once stdout has failed, later output is
/// dropped and the work goes on: see `stdout_failed`.
macro_rules! outln {
    ($($arg:tt)*) => {{
        use std::io::Write as _;
        if !$crate::stdout_gone() {
            if let Err(e) = writeln!(std::io::stdout(), $($arg)*) {
                $crate::stdout_failed(e);
            }
        }
    }};
}

/// `print!` counterpart of `outln!`.
macro_rules! out {
    ($($arg:tt)*) => {{
        use std::io::Write as _;
        if !$crate::stdout_gone() {
            if let Err(e) = write!(std::io::stdout(), $($arg)*) {
                $crate::stdout_failed(e);
            }
        }
    }};
}

mod args;
mod probe;
mod project_lock;

use args::{Args, parse_value};
use filmcraft_automation::BridgeClient;
use filmcraft_engine::Session;
use serde_json::{Value, json};
use std::sync::atomic::{AtomicBool, Ordering};

/// Set once a write to stdout has failed; later output is dropped.
static STDOUT_GONE: AtomicBool = AtomicBool::new(false);
/// Set when stdout failed for a reason other than a closed reader: the exit status becomes 1.
static STDOUT_ERROR: AtomicBool = AtomicBool::new(false);

fn stdout_gone() -> bool {
    STDOUT_GONE.load(Ordering::Relaxed)
}

/// stdout went away. The program doesn't stop there: the rest of `exec`/`run`/`import` (later
/// script lines, `--save`, `--save-as`) still runs and the exit status still tells how it went, so
/// `exec … --save | head -1` keeps the edit. A reader that stopped early (a closed pipe) is not an
/// error, as in ripgrep; any other write error is reported and makes the exit status 1.
fn stdout_failed(e: std::io::Error) {
    if STDOUT_GONE.swap(true, Ordering::Relaxed) || e.kind() == std::io::ErrorKind::BrokenPipe {
        return;
    }
    diag(format_args!("filmcraft-cli: can't write to stdout: {e}"));
    STDOUT_ERROR.store(true, Ordering::Relaxed);
}

const HELP: &str = "\
filmcraft-cli: drive FilmCraft from the shell (headless engine, or the live app with --bridge)

USAGE
  filmcraft-cli [OPTIONS] <SUBCOMMAND> [ARGS]

SUBCOMMANDS
  exec <id> [key=value ...]     run one command; prints its result as JSON
  exec <id> '<json params>'     same, params as one JSON object
  run <script.jsonl | ->        run commands, one {\"id\",\"params\"} per line (# comments ok), in
                                order: file.exportMedia waits for its file before the next line
                                (and before exit) unless its params say \"wait\": false
  commands [filter] [--json]    list commands (id, label, shortcut, params)
  describe <id>                 one command as JSON (menu, shortcut, params, enabled now)
  inspect [project|sequence]    project tree or active sequence as JSON (default: both)
  import <file>...              import media into the project
  export <out> [--preset name] [--format f] [--range r] [--start s --end s] [--settings json]
         [--gpu-rendering auto|off]
         [--scale f] [--quality 0-100] [--no-audio] [--queue] [--allow-offline]
                                export the active sequence and wait for it to finish: with an
                                export preset (`export --list-presets`; built-in or the user's), or
                                a format (h264|hevc|prores|dnxhr|apv|mjpeg|mxf-op1a|mxf-opatom|png|tiff|bmp|gif|wav|aiff|aac|mp3, guessed
                                from the extension); --range entire|inOut|workArea, or a custom
                                range in seconds; --settings is ExportSettings JSON merged over the
                                preset; --scale renders at a fraction of the frame size (0.5 =
                                half); --quality 0-100 for the formats that take one; --no-audio
                                leaves the sound out; --queue adds to the export queue and runs it
                                instead. Offline media (missing, made offline, unreadable) renders
                                as placeholder frames: the export then lists it in `offlineMedia`,
                                warns on stderr and exits 1, unless --allow-offline accepts it
  export --list-presets [query] list export presets (name, category, format) as JSON
  render --seconds S --out f.png [--scale 0.5] [--allow-offline]
                                render one Program frame to PNG (offline media: as for export)
  probe <media> [--image-sequence]
                                media info as JSON, with MXF / Ogg / BWF details; with
                                --image-sequence <media> is the first numbered still of a sequence
  bench-decode <media> [--frames N]
  mcp                           MCP server on stdio (headless, or --bridge to the live app)
  help                          this text
  --version                     print the version

OPTIONS
  --project <p.fcproj>          open this project first (headless)
  --demo                        open the built-in demo project (headless)
  --save                        save the project back to --project when done; runs saving one
                                project take turns, so each edits what the last one saved
  --save-as <p.fcproj>          save the project to this path when done
  --bridge <127.0.0.1:PORT>     send commands to the running app (`filmcraft --control PORT`)
  --data-dir <dir>              FilmCraft data directory for user export presets (headless;
                                default: the app's data directory)
  --keep-going                  `run`: report failing lines and continue
  --compact                     one-line JSON output

VALUES
  key=value parses value as JSON when it can (3.5, true, [1,2], {\"a\":1}), else as a string:
  `exec timeline.razor seconds=3.5`, `exec file.newBin name=Selects`.
  Times: 254016000000 ticks per second; most commands also take seconds=, frame= or timecode=.

EXIT STATUS
  0 success · 1 a command failed, or export/render drew offline media without --allow-offline
  · 2 usage error
";

/// Writes one diagnostic line to `w`, dropping any write error. `eprintln!` panics (exit 101) when stderr's
/// reader is gone, which would turn a usage error, a failure or a finished export into a crash.
fn write_diag(w: &mut dyn std::io::Write, msg: std::fmt::Arguments) {
    let _ = writeln!(w, "{msg}");
}

fn diag(msg: std::fmt::Arguments) {
    write_diag(&mut std::io::stderr(), msg);
}

fn usage(msg: impl std::fmt::Display) -> ! {
    diag(format_args!("filmcraft-cli: {msg}\nRun `filmcraft-cli help` for usage."));
    std::process::exit(2)
}

/// Read a file off the runtime thread: `cli` is async because MCP, bridge calls and control
/// commands await, so a blocking `std::fs` read would stall every other task on that thread.
async fn read_file(path: impl Into<std::path::PathBuf>) -> std::io::Result<Vec<u8>> {
    let path = path.into();
    tokio::task::spawn_blocking(move || std::fs::read(path)).await.map_err(std::io::Error::other)?
}

/// `read_file` for UTF-8 text.
async fn read_text(path: impl Into<std::path::PathBuf>) -> std::io::Result<String> {
    let path = path.into();
    tokio::task::spawn_blocking(move || std::fs::read_to_string(path)).await.map_err(std::io::Error::other)?
}

/// Write a file off the runtime thread; see `read_file`.
async fn write_file(path: impl Into<std::path::PathBuf>, data: Vec<u8>) -> std::io::Result<()> {
    let path = path.into();
    tokio::task::spawn_blocking(move || std::fs::write(path, data)).await.map_err(std::io::Error::other)?
}

fn fail(msg: impl std::fmt::Display) -> ! {
    diag(format_args!("filmcraft-cli: {msg}"));
    std::process::exit(1)
}

/// Where commands go: an in-process session, or the desktop app's control channel.
enum Backend {
    Local(Box<Session>),
    Bridge(BridgeClient),
}

impl Backend {
    fn open(a: &Args) -> Self {
        if let Some(addr) = a.opt("--bridge") {
            if a.opt("--project").is_some() || a.flag("--demo") {
                usage("--bridge drives the running app; open projects there (exec file.open path=…)");
            }
            return Backend::Bridge(BridgeClient::new(addr).unwrap_or_else(|e| usage(e)));
        }
        let mut s = Session::default();
        // user export presets (and other per-user libraries) from the data directory
        if let Some(dir) = a.opt("--data-dir").map(std::path::PathBuf::from).or_else(filmcraft_engine::autosave::default_data_dir) {
            s.export_presets.set_dir(&dir);
        }
        if let Some(p) = a.opt("--project") {
            if let Err(e) = s.execute("file.open", json!({"path": p})) {
                fail(e);
            }
        } else if a.flag("--demo") {
            let _ = s.execute("file.openDemoProject", json!({}));
        }
        Backend::Local(Box::new(s))
    }

    async fn exec(&mut self, id: &str, mut params: Value) -> Result<Value, String> {
        match self {
            // this process exits after the command, so a background export would never be written:
            // long commands wait unless the caller says otherwise (#2342)
            Backend::Local(s) => {
                // mask tracking is applied when its job finishes, which this process never sees (#3302)
                if (filmcraft_automation::long_job::LONG_COMMANDS.contains(&id) || id == "masks.track")
                    && let Some(p) = params.as_object_mut()
                {
                    // anything but an explicit `false` (missing, null, a typo'd value) waits
                    if p.get("wait").and_then(Value::as_bool) != Some(false) {
                        p.insert("wait".into(), json!(true));
                    }
                }
                s.execute(id, params).map_err(|e| e.to_string())
            }
            // a blocking export runs as an app job polled by the client (#91, #92)
            Backend::Bridge(b) => b.execute(id, params).await.map_err(|e| e.to_string()),
        }
    }

    /// Save to the --project path (`--save`) or to `--save-as`. Bridge mode saves in the app.
    async fn finish(&mut self, a: &Args) {
        let r = if let Some(p) = a.opt("--save-as") {
            Some(self.exec("file.saveAs", json!({"path": p})).await)
        } else if a.flag("--save") {
            match a.opt("--project") {
                Some(p) => Some(self.exec("file.save", json!({"path": p})).await),
                None => Some(self.exec("file.save", json!({})).await),
            }
        } else {
            None
        };
        if let Some(Err(e)) = r {
            fail(format!("saving: {e}"));
        }
    }
}

fn print(a: &Args, v: &Value) {
    let s = if a.flag("--compact") { serde_json::to_string(v) } else { serde_json::to_string_pretty(v) };
    outln!("{}", s.unwrap_or_default());
}

/// Export format from the output file's extension.
fn format_for(path: &str) -> Option<&'static str> {
    let ext = path.rsplit_once('.')?.1.to_ascii_lowercase();
    Some(match ext.as_str() {
        "mp4" | "m4v" => "h264",
        "mov" => "prores",
        "mxf" => "mxf-op1a",
        "png" => "png",
        "gif" => "gif",
        "wav" => "wav",
        "tif" | "tiff" => "tiff",
        "bmp" => "bmp",
        "aif" | "aiff" => "aiff",
        "m4a" | "aac" => "aac",
        "mp3" => "mp3",
        _ => return None,
    })
}

/// OS hardware video decoders (VideoToolbox on macOS, Media Foundation on Windows) in front of our
/// own, as in the desktop app. Also what `mcp` and the headless commands decode with.
/// The GPU export frame renderer (filmcraft-gpu's off-screen compositor behind filmcraft-export's
/// frame-renderer hook): exports with GPU rendering Auto composite on the GPU and fall back to the
/// CPU reference renderer wherever it cannot.
struct GpuFrameRenderer(filmcraft_gpu::ExportRenderer);

impl filmcraft_export::FrameRenderer for GpuFrameRenderer {
    fn render(
        &mut self,
        project: &filmcraft_project::Project,
        seq: filmcraft_project::ItemId,
        t: filmcraft_time::Tick,
        opts: filmcraft_render::RenderOptions,
        sources: &dyn filmcraft_render::SourceProvider,
    ) -> Option<filmcraft_render::Image> {
        self.0.render(project, seq, t, opts, sources)
    }

    fn caps(&self) -> filmcraft_render::plan::DeviceCaps {
        self.0.caps()
    }
}

fn register_gpu_frame_renderer() {
    filmcraft_export::register_frame_renderer(|| {
        filmcraft_gpu::ExportRenderer::new().map(|r| Box::new(GpuFrameRenderer(r)) as Box<dyn filmcraft_export::FrameRenderer>)
    });
}

fn register_hardware_decoders() -> filmcraft_platform::Availability {
    filmcraft_platform::register()
}

/// `path` made absolute against the working directory, as the project stores it. Unlike
/// `canonicalize`, `std::path::absolute` keeps symlinks and adds no Windows verbatim `\\?\`
/// prefix (#850). A path it cannot resolve is kept as given.
fn absolute(path: &str) -> String {
    std::path::absolute(path).ok().and_then(|p| p.into_os_string().into_string().ok()).unwrap_or_else(|| path.to_string())
}

#[tokio::main]
async fn main() {
    cli().await;
    if STDOUT_ERROR.load(Ordering::Relaxed) {
        std::process::exit(1);
    }
}

async fn cli() {
    // `std::env::args` panics on an argument that is not Unicode (a Linux file name in Latin-1)
    let a = Args::parse(std::env::args_os().skip(1).map(|a| a.to_string_lossy().into_owned()));
    // `--help` anywhere (`filmcraft-cli --help`, `filmcraft-cli export --help`) prints the reference:
    // the parser takes it as a flag option, so it never reaches the subcommand match.
    if a.flag("--help") {
        out!("{HELP}");
        return;
    }
    // `--version` anywhere and `-V` as the subcommand, also after global options (`--demo --version`, #710).
    if a.wants_version() {
        outln!("filmcraft-cli {}", env!("CARGO_PKG_VERSION"));
        return;
    }
    register_hardware_decoders();
    register_gpu_frame_renderer();
    let Some(cmd) = a.pos(0) else { usage("missing subcommand") };
    match cmd {
        "help" | "-h" => out!("{HELP}"),
        "version" => outln!("filmcraft-cli {}", env!("CARGO_PKG_VERSION")),
        "probe" => cli_probe(&a).await,
        "bench-decode" => cli_bench_decode(&a).await,
        "commands" | "describe" => cli_commands(&a, cmd).await,
        "exec" => cli_exec(&a).await,
        "run" => cli_run(&a).await,
        "inspect" => cli_inspect(&a).await,
        "import" => cli_import(&a).await,
        "export" => cli_export(&a).await,
        "render" => cli_render(&a).await,
        "mcp" => cli_mcp(&a).await,
        other => usage(format!("unknown subcommand `{other}`")),
    }
}
async fn cli_probe(a: &Args) {
    let path = a.pos(1).unwrap_or_else(|| usage("probe <media> [--image-sequence]"));
    match probe::probe(path, a.flag("--image-sequence")) {
        Ok(v) => print(a, &v),
        Err(e) => fail(e),
    }
}

async fn cli_bench_decode(a: &Args) {
    let path = a.pos(1).unwrap_or_else(|| usage("bench-decode <media>"));
    let n: i64 = a.opt("--frames").and_then(|v| v.parse().ok()).unwrap_or(120);
    let src = filmcraft_codecs::open_bytes(path, read_file(path).await.unwrap_or_else(|e| fail(e)).into()).unwrap_or_else(|e| fail(e));
    let rate = src.info().frame_rate();
    let t0 = std::time::Instant::now();
    for f in 0..n {
        src.video_frame(filmcraft_media::FrameRequest::full(rate.tick_of(f))).unwrap_or_else(|e| fail(e));
    }
    let dt = t0.elapsed().as_secs_f64();
    outln!("{n} frames in {dt:.2}s → {:.1} fps (sequential, via Mp4Source)", n as f64 / dt);
    let t1 = std::time::Instant::now();
    let f = src.video_frame(filmcraft_media::FrameRequest::full(rate.tick_of(n / 2))).unwrap_or_else(|e| fail(e));
    let (w, h, _) = f.to_linear_f32_decimated(2);
    outln!("½-res linear conversion {w}x{h}: {:.1} ms", t1.elapsed().as_secs_f64() * 1000.0);
}

async fn cli_commands(a: &Args, cmd: &str) {
    let mut b = Backend::open(a);
    let list = b.exec("command.list", json!({})).await.unwrap_or_else(|e| fail(e));
    let list = list.as_array().cloned().unwrap_or_default();
    if cmd == "describe" {
        let id = a.pos(1).unwrap_or_else(|| usage("describe <id>"));
        match list.iter().find(|c| c["id"] == id) {
            Some(c) => print(a, c),
            None => fail(format!("unknown command `{id}` (try `filmcraft-cli commands {id}`)")),
        }
        return;
    }
    let f = a.pos(1).map(str::to_ascii_lowercase).unwrap_or_default();
    let hit = |c: &Value| {
        let id = c["id"].as_str().unwrap_or("").to_ascii_lowercase();
        let label = c["label"].as_str().unwrap_or("").to_ascii_lowercase();
        f.is_empty() || id.contains(&f) || label.contains(&f)
    };
    let list: Vec<Value> = list.into_iter().filter(hit).collect();
    if a.flag("--json") {
        print(a, &Value::Array(list));
    } else {
        for c in &list {
            let s = |k: &str| c[k].as_str().unwrap_or("").to_string();
            outln!("{:<32} {:<34} {:<14} {}", s("id"), s("label"), s("shortcut"), s("params"));
        }
    }
}

async fn cli_exec(a: &Args) {
    let id = a.pos(1).unwrap_or_else(|| usage("exec <id> [key=value ...]"));
    let params = a.params_from(2).unwrap_or_else(|e| usage(e));
    let _lock = project_lock::for_save(a);
    let mut b = Backend::open(a);
    match b.exec(id, params).await {
        Ok(v) => print(a, &v),
        Err(e) => fail(format!("{id}: {e}")),
    }
    b.finish(a).await;
}

async fn cli_run(a: &Args) {
    let script = a.pos(1).unwrap_or_else(|| usage("run <script.jsonl | ->"));
    let text = if script == "-" {
        std::io::read_to_string(std::io::stdin()).unwrap_or_else(|e| fail(e))
    } else {
        read_text(script).await.unwrap_or_else(|e| fail(format!("{script}: {e}")))
    };
    let _lock = project_lock::for_save(a);
    let mut b = Backend::open(a);
    let mut failed = 0;
    for (n, line) in text.lines().enumerate().filter(|(_, l)| !l.trim().is_empty() && !l.trim_start().starts_with('#')) {
        let v: Value = serde_json::from_str(line).unwrap_or_else(|e| usage(format!("line {}: {e}", n + 1)));
        let id = v["id"].as_str().unwrap_or_else(|| usage(format!("line {}: missing \"id\"", n + 1)));
        match b.exec(id, v.get("params").cloned().unwrap_or(json!({}))).await {
            Ok(r) => outln!("{}", json!({"line": n + 1, "id": id, "ok": true, "result": r})),
            Err(e) => {
                outln!("{}", json!({"line": n + 1, "id": id, "ok": false, "error": e}));
                failed += 1;
                if !a.flag("--keep-going") {
                    std::process::exit(1);
                }
            }
        }
    }
    b.finish(a).await;
    if failed > 0 {
        std::process::exit(1);
    }
}

async fn cli_inspect(a: &Args) {
    let mut b = Backend::open(a);
    let what = a.pos(1).unwrap_or("all");
    let mut get = async |id: &str| b.exec(id, json!({})).await.unwrap_or_else(|e| fail(e));
    let v = match what {
        "project" => get("project.inspect").await,
        "sequence" => get("sequence.inspect").await,
        "all" => json!({"project": get("project.inspect").await, "sequence": get("sequence.inspect").await}),
        other => usage(format!("inspect: unknown `{other}` (project | sequence)")),
    };
    print(a, &v);
}

async fn cli_import(a: &Args) {
    let paths: Vec<String> = a.positionals.get(1..).unwrap_or_default().iter().map(|p| absolute(p)).collect();
    if paths.is_empty() {
        usage("import <file>...");
    }
    let _lock = project_lock::for_save(a);
    let mut b = Backend::open(a);
    match b.exec("file.import", json!({"paths": paths})).await {
        Ok(v) => print(a, &v),
        Err(e) => fail(format!("import: {e}")),
    }
    b.finish(a).await;
}

async fn cli_export(a: &Args) {
    if a.flag("--list-presets") {
        let mut b = Backend::open(a);
        let q = a.pos(1).map(|q| json!({"query": q})).unwrap_or(json!({}));
        match b.exec("export.presets.list", q).await {
            Ok(v) => print(a, &v["presets"]),
            Err(e) => fail(format!("export: {e}")),
        }
        return;
    }
    let out = a.pos(1).unwrap_or_else(|| usage("export <out> [--preset name | --format f]"));
    let mut p = json!({"path": out, "wait": true});
    match (a.opt("--preset"), a.opt("--format")) {
        (Some(preset), f) => {
            p["preset"] = json!(preset);
            if let Some(f) = f {
                p["format"] = json!(f);
            }
        }
        (None, f) => {
            let format = f.or_else(|| format_for(out)).unwrap_or_else(|| usage("export: give --preset or --format (unknown extension)"));
            p["format"] = json!(format);
        }
    }
    for (k, key) in [("--scale", "scale"), ("--quality", "quality")] {
        if let Some(v) = a.opt(k) {
            p[key] = parse_value(v);
        }
    }
    if let Some(r) = a.opt("--range") {
        p["range"] = json!(r);
    }
    set_custom_bounds(&mut p, a.opt("--start"), a.opt("--end"));
    if let Some(js) = a.opt("--settings") {
        p["settings"] = serde_json::from_str(js).unwrap_or_else(|e| usage(format!("--settings: {e}")));
    }
    if a.flag("--no-audio") {
        p["audio"] = json!(false);
    }
    if let Some(v) = a.opt("--gpu-rendering") {
        p["gpuRendering"] = json!(v); // off | auto (validated by the export command)
    }
    let mut b = Backend::open(a);
    let t0 = std::time::Instant::now();
    let r = if a.flag("--queue") {
        let mut q = p.clone();
        q["start"] = json!(true);
        b.exec("export.queue.add", q).await.and_then(|v| {
            let failed: Vec<&Value> = v["items"].as_array().map(|i| i.iter().filter(|x| x["status"] != "done").collect()).unwrap_or_default();
            if failed.is_empty() { Ok(v) } else { Err(format!("queue: {}", Value::Array(failed.into_iter().cloned().collect()))) }
        })
    } else {
        b.exec("file.exportMedia", p).await
    };
    match r {
        Ok(v) => {
            print(a, &v);
            let written = written_paths(&v, out).join(", ");
            for warning in v.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
                diag(format_args!("filmcraft-cli: warning: {warning} (CLI: --range entire)"));
            }
            for warning in export_warnings(&v) {
                diag(format_args!("filmcraft-cli: warning: {warning}"));
            }
            check_offline(a, &offline_media(&v), &format!("export: {written}"));
            diag(format_args!("exported {written} in {:.1}s", t0.elapsed().as_secs_f64()));
        }
        Err(e) => fail(format!("export: {e}")),
    }
}

async fn cli_render(a: &Args) {
    if a.opt("--bridge").is_some() {
        usage("render is headless; with --bridge use the MCP `render_frame` tool or `exec` ui commands");
    }
    let Backend::Local(mut s) = Backend::open(a) else { usage("render is headless") };
    let secs: f64 = finite_opt(a, "--seconds").unwrap_or(0.0);
    let scale: f32 = finite_opt(a, "--scale").unwrap_or(1.0);
    let out = a.opt("--out").unwrap_or("frame.png");
    s.set_playhead(filmcraft_time::Tick::from_seconds_f64(secs));
    let t0 = std::time::Instant::now();
    let (img, offline) = render_at_playhead(&s, scale).unwrap_or_else(|e| fail(e));
    let dt = t0.elapsed();
    let png = filmcraft_automation::png_rgba(img.w as u32, img.h as u32, img.over_black_rgba8(), 0).unwrap_or_else(|e| fail(e));
    write_file(out, png).await.unwrap_or_else(|e| fail(format!("{out}: {e}")));
    let offline: Vec<Value> = offline.iter().filter_map(|o| serde_json::to_value(o).ok()).collect();
    check_offline(a, &offline, &format!("render: {out}"));
    diag(format_args!("rendered {}x{} in {:.1} ms → {out}", img.w, img.h, dt.as_secs_f64() * 1000.0));
}

async fn cli_mcp(a: &Args) {
    if let Some(opt) = a.unknown_opt(&["--bridge", "--project", "--demo", "--data-dir"]) {
        usage(format!("unknown mcp option `{opt}`"));
    }
    let server = match a.opt("--bridge") {
        Some(addr) => filmcraft_automation::FilmcraftMcp::bridge(addr).unwrap_or_else(|e| usage(e)),
        None => match Backend::open(a) {
            Backend::Local(s) => filmcraft_automation::FilmcraftMcp::headless(*s),
            Backend::Bridge(_) => usage("mcp: use --bridge ADDR to drive a running app"),
        },
    };
    if let Err(e) = server.serve_stdio().await {
        fail(format!("mcp: {e}"));
    }
}

/// The files an export wrote, from its result: `path` of a direct export, or each queued item's
/// `path` (the format may have changed the extension: `out.mp4` exported as APV is `out.mp4.mov`).
/// `requested` when the result names none.
fn written_paths(result: &Value, requested: &str) -> Vec<String> {
    let paths: Vec<String> = match result.get("path").and_then(Value::as_str) {
        // an image sequence: its first and last stills
        Some(p) => vec![match result.get("lastPath").and_then(Value::as_str) {
            Some(last) => format!("{p} to {last}"),
            None => p.to_string(),
        }],
        None => result
            .get("items")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
            .filter_map(|i| i.get("path").and_then(Value::as_str))
            .map(str::to_string)
            .collect(),
    };
    if paths.is_empty() { vec![requested.to_string()] } else { paths }
}

/// The offline items an export result reports (`offlineMedia` of a direct export, or of each
/// queued item), once each.
fn offline_media(result: &Value) -> Vec<Value> {
    let lists = std::iter::once(result).chain(result.get("items").and_then(Value::as_array).into_iter().flatten());
    let mut out: Vec<Value> = Vec::new();
    for o in lists.filter_map(|r| r.get("offlineMedia").and_then(Value::as_array)).flatten() {
        if !out.iter().any(|x| x.get("item") == o.get("item")) {
            out.push(o.clone());
        }
    }
    out
}

/// What the exports in a result reported about how they ran (hardware encoding asked for, but the
/// software encoder ran): the warnings of a direct export's report (`result`), or of each queued
/// item's. `export.queue.add` answers with the whole queue, so only the items it `added` count: one
/// that finished earlier (in the app, with `--bridge`) is not this export's.
fn export_warnings(result: &Value) -> Vec<&str> {
    let added: Vec<&Value> = result.get("added").and_then(Value::as_array).into_iter().flatten().collect();
    let queued = result.get("items").and_then(Value::as_array).into_iter().flatten().filter(|i| i.get("id").is_some_and(|id| added.contains(&id)));
    let reports = std::iter::once(result).chain(queued).filter_map(|r| r.get("result"));
    reports.filter_map(|r| r.get("warnings").and_then(Value::as_array)).flatten().filter_map(Value::as_str).collect()
}

/// One stderr line per offline item that rendered as placeholder frames (#1054).
fn offline_warning(offline: &[Value]) -> String {
    let s = |o: &Value, k: &str| o.get(k).and_then(Value::as_str).unwrap_or("").to_string();
    let mut msg = format!("filmcraft-cli: warning: {} offline media item(s) rendered as placeholder frames:", offline.len());
    for o in offline {
        let id = o.get("item").and_then(Value::as_u64).map(|i| i.to_string()).unwrap_or_default();
        msg.push_str(&format!("\n  item {id} {} ({}): {}", s(o, "name"), s(o, "status"), s(o, "path")));
    }
    msg
}

/// Warn about offline media on stderr; without `--allow-offline` that fails the run (exit 1), after
/// the output (`what`) was written, so scripts don't take placeholder frames for the real picture.
fn check_offline(a: &Args, offline: &[Value], what: &str) {
    if offline.is_empty() {
        return;
    }
    diag(format_args!("{}", offline_warning(offline)));
    if !a.flag("--allow-offline") {
        fail(format!("{what} has placeholder frames for offline media; relink it (exec media.relink …) or pass --allow-offline"));
    }
}

/// A numeric option, or a usage error when it is not a finite number (so a typo never silently
/// falls back to a default).
fn finite_opt<T: std::str::FromStr + Copy + Into<f64>>(a: &Args, name: &str) -> Option<T> {
    let v = a.opt(name)?;
    match v.parse::<T>() {
        Ok(n) if n.into().is_finite() => Some(n),
        _ => usage(format!("{name}: expected a finite number, got `{v}`")),
    }
}

/// The active sequence at the playhead with the offline items it drew, or the reason it cannot be
/// rendered (no sequence, bad scale).
fn render_at_playhead(s: &Session, scale: f32) -> Result<(filmcraft_engine::render::Image, Vec<filmcraft_engine::media_pool::OfflineMedia>), String> {
    s.try_render_program_with_offline_at(scale, s.playhead()).map_err(|e| e.to_string())
}

/// `--start` / `--end` ask for a custom range. A lone bound is forwarded too, so the engine reports the missing one
/// instead of the export silently running over the whole sequence.
fn set_custom_bounds(p: &mut Value, start: Option<&str>, end: Option<&str>) {
    if start.is_none() && end.is_none() {
        return;
    }
    p["range"] = json!("custom");
    if let Some(s0) = start {
        p["startSeconds"] = parse_value(s0);
    }
    if let Some(s1) = end {
        p["endSeconds"] = parse_value(s1);
    }
}

#[cfg(test)]
mod format_tests {
    #[test]
    fn render_reports_the_real_reason() {
        let mut s = filmcraft_engine::Session::default();
        assert!(super::render_at_playhead(&s, 0.5).unwrap_err().contains("sequence"));
        s.execute("file.newSequence", serde_json::json!({"width": 16, "height": 16})).unwrap();
        for scale in [0.0, -1.0, f32::NAN] {
            let e = super::render_at_playhead(&s, scale).unwrap_err();
            assert!(e.contains("finite and positive"), "{e}");
        }
        assert_eq!(super::render_at_playhead(&s, 0.5).unwrap().0.w, 8);
    }

    /// The CLI (and MCP / headless runs, which share its entry point) registers the hardware
    /// decoders at start-up.
    #[test]
    fn startup_registers_the_hardware_decoders() {
        let hardware = super::register_hardware_decoders();
        // always on macOS and Windows; on Linux when a VA-API driver or NVIDIA's driver (NVDEC) is there
        let expected = cfg!(any(target_os = "macos", target_os = "windows"))
            || (cfg!(target_os = "linux") && matches!(hardware, filmcraft_platform::Availability::Available(_)));
        assert_eq!(filmcraft_platform::registered(), expected, "{hardware:?}");
    }

    #[test]
    fn a_failing_diagnostic_stream_does_not_panic() {
        struct Closed;
        impl std::io::Write for Closed {
            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
                Err(std::io::ErrorKind::BrokenPipe.into())
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Err(std::io::ErrorKind::BrokenPipe.into())
            }
        }
        super::write_diag(&mut Closed, format_args!("exported {}", "a.wav"));
        let mut ok = Vec::new();
        super::write_diag(&mut ok, format_args!("hi"));
        assert_eq!(ok, b"hi\n");
    }

    #[test]
    fn export_message_names_the_written_files() {
        use serde_json::json;
        let direct = json!({"job": 1, "path": "out-apv.mp4.mov", "result": {"path": "out-apv.mp4.mov"}});
        assert_eq!(super::written_paths(&direct, "out-apv.mp4"), ["out-apv.mp4.mov"]);
        let queued = json!({"added": [1, 2], "items": [{"path": "a.mp4.mov"}, {"path": "b.wav"}]});
        assert_eq!(super::written_paths(&queued, "a.mp4"), ["a.mp4.mov", "b.wav"]);
        assert_eq!(super::written_paths(&json!({}), "x.mov"), ["x.mov"]);
        assert_eq!(super::written_paths(&json!({"items": []}), "x.mov"), ["x.mov"]);
    }

    #[test]
    fn offline_media_from_direct_and_queued_results() {
        use serde_json::json;
        let a = json!({"item": 8, "name": "a.mp4", "path": "/m/a.mp4", "status": "missing", "error": ""});
        let b = json!({"item": 9, "name": "b.mov", "path": "/m/b.mov", "status": "offline", "error": ""});
        assert_eq!(super::offline_media(&json!({"path": "x.mp4", "offlineMedia": [a]})), std::slice::from_ref(&a));
        let queued = json!({"items": [{"offlineMedia": [a, b]}, {"offlineMedia": [a]}, {"offlineMedia": []}]});
        assert_eq!(super::offline_media(&queued), [a.clone(), b.clone()]);
        assert!(super::offline_media(&json!({"path": "x.mp4"})).is_empty());
        let w = super::offline_warning(&[a, b]);
        assert!(w.contains("2 offline media item(s)") && w.contains("item 8 a.mp4 (missing): /m/a.mp4") && w.contains("item 9 b.mov (offline)"), "{w}");
    }

    #[test]
    fn export_warnings_from_direct_and_queued_results() {
        use serde_json::json;
        let fell_back = "hardware encoding declined (NVENC: two-pass VBR); the software H.264 encoder ran";
        // `export.queue.add` answers with the whole queue; `added` names the items this call queued
        let older = json!({"id": 1, "status": "done", "result": {"encoder": "software", "warnings": [fell_back]}});
        let cases: [(&str, serde_json::Value, &[&str]); 8] = [
            ("direct", json!({"path": "a.mp4", "result": {"encoder": "software", "warnings": [fell_back]}}), &[fell_back]),
            ("direct, nothing to say", json!({"path": "a.mp4", "result": {"encoder": "NVENC"}}), &[]),
            (
                "queued, one of two",
                json!({"added": [1, 2], "items": [{"id": 1, "status": "done", "result": {"warnings": [fell_back]}}, {"id": 2, "status": "done", "result": {"encoder": "software"}}]}),
                &[fell_back],
            ),
            ("queued, failed", json!({"added": [1], "items": [{"id": 1, "status": "failed", "result": null}]}), &[]),
            // an item finished earlier is not this export's: NVENC ran for the new one
            ("queued after an older fallback", json!({"added": [2], "items": [older, {"id": 2, "status": "done", "result": {"encoder": "NVENC"}}]}), &[]),
            (
                "queued, falls back after an older one did",
                json!({"added": [2], "items": [older, {"id": 2, "status": "done", "result": {"encoder": "software", "warnings": [fell_back]}}]}),
                &[fell_back],
            ),
            // the range advisory is printed on its own, with its CLI hint
            ("range warning only", json!({"warnings": ["In/Out range is 1 frame"], "result": {}}), &[]),
            ("no result", json!({}), &[]),
        ];
        for (name, result, want) in cases {
            assert_eq!(super::export_warnings(&result), want, "{name}");
        }
    }

    #[test]
    fn export_lone_bound_is_forwarded_as_custom_range() {
        use serde_json::json;
        let mut p = json!({});
        super::set_custom_bounds(&mut p, Some("0.25"), None);
        assert_eq!(p["range"], "custom");
        assert_eq!(p["startSeconds"], 0.25);
        assert!(p.get("endSeconds").is_none());
        let mut p = json!({});
        super::set_custom_bounds(&mut p, None, Some("0.25"));
        assert_eq!(p["range"], "custom");
        assert_eq!(p["endSeconds"], 0.25);
        let mut p = json!({});
        super::set_custom_bounds(&mut p, None, None);
        assert!(p.get("range").is_none());
    }

    /// `import` used `canonicalize`, which resolves symlinks and on Windows stores `\\?\C:\…`
    /// verbatim paths in the project (#850).
    #[test]
    fn imported_paths_are_absolute_without_resolving_links() {
        let cwd = std::env::current_dir().unwrap();
        assert_eq!(super::absolute("clip.mov"), cwd.join("clip.mov").to_string_lossy());
        assert!(!super::absolute("clip.mov").starts_with(r"\\?\"));
        assert_eq!(super::absolute(""), "");
        #[cfg(unix)]
        {
            let dir = std::env::temp_dir().join(format!("filmcraft-cli-abs-{}", std::process::id()));
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join("real.mov"), b"x").unwrap();
            let link = dir.join("link.mov");
            let _ = std::fs::remove_file(&link);
            std::os::unix::fs::symlink(dir.join("real.mov"), &link).unwrap();
            assert_eq!(super::absolute(&link.to_string_lossy()), link.to_string_lossy());
            std::fs::remove_dir_all(&dir).unwrap();
        }
    }

    #[test]
    fn export_format_from_extension() {
        assert_eq!(super::format_for("out/clip.MXF"), Some("mxf-op1a"));
        assert_eq!(super::format_for("a.mov"), Some("prores"));
        assert_eq!(super::format_for("noext"), None);
    }
}