diff --git a/MCP.md b/MCP.md index 4c9dbc8..b8c7266 100644 --- a/MCP.md +++ b/MCP.md @@ -228,9 +228,9 @@ in **bold**; optional ones follow the name. | `project_collect` | folder | copies every file the project plays into `folder` (default `_media` beside the project file, made if missing) and points the project at the copies; one undo step, unsaved until `project_save`. Skips generated sources, names and skips missing files, leaves sources already in the folder, renames clashes to `name-2.ext`, reuses identical bytes already there. A failed copy changes nothing. The window's File > Collect media does the same, with progress and cancel | | `project_export_timeline` | format, path? | writes the active sequence for another editor: `otio` (OpenTimelineIO: tracks, clips with absolute file paths, gaps, transitions, markers), `fcpxml` (Final Cut Pro XML 1.10, read by Final Cut Pro, Resolve and Premiere) or `edl` (CMX3600: V1 and audio on A1/A2, dissolves as `D`, `FROM CLIP NAME` comments). Default path: beside the project file. Subtitles are left out and the reply says so. Only the file is written; the project does not change. The window's File > Export timeline as does the same into the default export folder | | `project_import_timeline` | path | reads an `.otio` file as a new sequence of the project and makes it the active one; each clip is relinked by its path, and a missing file becomes an offline clip. One undo step, unsaved until `project_save`. The window takes the same file from File > Import timeline (OTIO) or from the command line | -| `project_status` | — | path, saved or dirty, canvas size, fps, duration, lanes with clip counts, sources, the colour looks (a `looks:` line naming the built-in looks and the saved ones, the names the `look` op takes; `structuredContent` has them as `looks.builtin` and `looks.saved`), undo and redo depth, running exports, settings (and the notes, when there are any); an `OFFLINE: src:N ` line per offline source, and the fixes an open made to load (dirty until saved) | -| `project_settings` | resolution, fps, tonemap, notes, still_secs, proxies, auto_proxies, encoder, limiter, captions | the `ProjectSettings` knobs. An fps change keeps clips, captions and titles at the same seconds; their frame numbers and addresses change. `notes` is free text (several lines; `""` clears it), saved with the project as format v52; `still_secs` is how long a still is placed for, 0.5 to 600 s, 5 s by default, and only stills placed after the change take it. Both are one undo step each | -| `templates` | (none) | lists the project templates: the built-ins (YouTube 1080p 30, Vertical 1080×1920 30, Square 1080 30) and the ones saved from the window with File > Save as template, each marked built-in or saved and whether it keeps clips | +| `project_status` | history (false) | path, saved or dirty, canvas size, fps, duration, lanes with clip counts, sources, the colour looks (a `looks:` line naming the built-in looks and the saved ones, the names the `look` op takes; `structuredContent` has them as `looks.builtin` and `looks.saved`), undo and redo depth, running exports, settings (and the notes, when there are any); an `OFFLINE: src:N ` line per offline source, and the fixes an open made to load (dirty until saved). `history: true` also lists every undo step and every redo step, newest first, each with the `steps` count that `undo` or `redo` needs to reach it (`undo {steps: 3}` takes back the three newest) | +| `project_settings` | resolution, fps, tonemap, notes, still_secs, sample_rate, proxies, auto_proxies, encoder, limiter, captions | the `ProjectSettings` knobs. An fps change keeps clips, captions and titles at the same seconds; their frame numbers and addresses change. `notes` is free text (several lines; `""` clears it), saved with the project as format v52; `still_secs` is how long a still is placed for, 0.5 to 600 s, 5 s by default, and only stills placed after the change take it. `sample_rate` is the sound mix's rate: `"source"` (the default: the highest rate among the sources, 48 kHz when all are below 44.1 kHz), `44100`, `48000` or `96000`, the same rows the GUI offers. Each is one undo step | +| `templates` | save | lists the project templates: the built-ins (YouTube 1080p 30, Vertical 1080×1920 30, Square 1080 30) and the ones saved from the window with File > Save as template, each marked built-in or saved and whether it keeps clips. `save: {name, with_clips?}` saves the open project as a template of that name (replacing one of the same name; a built-in's name is refused). `with_clips: true` keeps the clips and their sources too; the default keeps the settings only. The project does not change | | `checkpoint` | **name** | save the whole project under a name (letters, digits, `-`, `_`), as a copy in `/checkpoints//` (the project's path, from `project_new {path}` or `project_save`; with no path at all, the temp dir, lost on reboot) | | `restore` | **name** | replace the open project with a checkpoint, from this run or an earlier one; first saves the open project as `before-restore-` (a suffix when that name is taken), so the state before the restore stays on disk; the project is dirty afterwards and its undo and redo history is cleared | | `checkpoints` | — | the checkpoints on disk in this project's checkpoint folder, by name, including those made by earlier server runs | @@ -335,7 +335,7 @@ prints it live, and `help {topic:""}` gives one op's entry. The recipes and | three-point | `insert {source, in?, out?, at, to?, length?, lanes?}` · `overwrite {source, in?, out?, at, to?, length?, lanes?}` (`src` also spells `source`; the source range `in..out`, else the whole file, goes at `at`; `to` is a timeline out mark and `length` a duration, either sets the length from `in` instead of `out`; the take lands on `lanes`, at most one V and one A, else the first unlocked V and A lanes the source has, linked as one take; a still takes a V lane and `length` (default 5 s), a song an A lane. `insert` cuts the clip `at` falls inside and ripples what follows on those lanes only; it never moves or splits a lane outside the take, and refuses by name when that would pull a linked take apart. `overwrite` replaces what is there, trimming or splitting it, and nothing moves. Captions and titles keep their time; a locked lane refuses; one undo step each) | | cut | `split {at, lanes?}` · `trim {clip, edge: in\|out, to, scope?}` [group] · `roll {clip, by\|to, edge?}` [group] (move the cut between two clips) · `slip {clip, by}` [group] (shift the source in/out, same slot) · `slide {clip, by}` [group] (move the clip between its neighbours) · `move {clip, at, to_lane?, insert?, titles?, split_captions?}` [group] (`insert:true` is a ripple move) · `delete {clip}` [group] · `lift {clip}` · `ripple_delete {clip}` · `close_gaps {lane}` · `cut_regions {regions:[[from,to]…], lanes?}` (accepts `silence` output verbatim) · `insert_time {at, duration, lanes?}` (ripples empty time in; a clip `at` falls inside is cut first) · `remove_time {at, duration, lanes?}` (the `cut_regions` cut for one span; a title wholly inside the span is removed, and one straddling an edge is trimmed to the part outside; the reply names both) · `swap {a, b}` (two clips on one lane trade places; a clip in a linked take is refused until the take is ungrouped) | | time | `speed {clip, x}` 0.25–4 [group] (x is the absolute rate, not a multiplier: re-sending 0.5 on a clip already at 0.5 changes nothing) · `reverse {clip, on?}` [group] (plays the clip backward, picture and sound, or forward again; `on` omitted toggles; composes with speed and ramps; a still refuses; `clip_info` and `timeline` say `reversed`) · `speed_ramp {clip, keys:[{at, speed}…], ripple?, lanes?}` [group] (up to 8 keys at clip-relative times, speed 0.25–4 linear between them and held outside them; `keys:[]` clears the ramp) · `fade {clip, in?, out?}` (int = frames, `"0.5s"` = time) · `dissolve {clip, frames}` (video transition into the next clip) · `transition {clip, kind?=dissolve, length?, direction?}` (the same overlap with a look: `dissolve`, `dip-black`, `dip-white`, `wipe`, `slide`, `push` or `zoom`; `wipe`/`slide`/`push` move `left` (default), `right`, `up` or `down`, the way things move, so `wipe-left` shows the next clip from the right edge; `length` or `frames` is the overlap, kept when omitted; `dissolve` accepts `kind` too; the picture changes with the kind, the sound is always the crossfade; `timeline` flags and `clip_info.transition_kind` show it) · `crossfade {clip, frames}` (audio) · `freeze {at, duration, lane?=V1, insert?=true}` (holds the composed frame at `at` as a still; needs a project path, saved or not; see below) | -| look | `color {clip, brightness?, contrast?, saturation?, tint?, reset?}` · `transform {clip, x?, y?, corner?, margin?, scale?, rotate?, crop?:[l,r,t,b], opacity?, reset?}` (`corner` is centre, top-left, top-right, bottom-left or bottom-right: the engine sets x and y from the picture's own size (after crop and quarter turn), the scale given and a `margin` in pixels (default 32) from the two edges it touches; giving x or y with corner is refused, and so is margin without corner; picture in picture is `corner:"bottom-right", scale:0.3`) · `transform_keys {clip, keys?:[{at, x?, y?, scale?, rotate?, opacity?, ease?}…], clear?}` (animates the transform over the clip's own time) · `opacity_keys {clip, keys?:[{at, opacity, ease?}…], clear?}` (opacity 0..1 over the clip's own time, fades multiply on top) · `color_keys {clip, keys?:[{at, brightness?, contrast?, saturation?, tint?, ease?}…], clear?}` (the grade over the clip's own time, interpolated per frame) · `look {clip, name}` (the whole grade becomes a look, one undo step: a built-in `Warm`, `Cool`, `Teal & orange`, `Bleach bypass`, `Black & white`, `Faded film`, `High contrast` or `Vintage`, or a saved one from the colour card's "Save current as look" (`$XDG_DATA_HOME/edith/looks/.look`); an unknown name is refused with the list; `help {topic:"looks"}` lists them) · `auto_color {clip}` (reads the clip's middle frame as shot: grey-world white balance into the wheels' channel gains, then brightness and contrast so the 0.5 % and 99.5 % luma percentiles land near 0.02 and 0.98; saturation, tint, curves and LUT kept; the reply gives the values set; one undo step) · · `wheels {clip, lift?, gamma?, gain?, reset?}` (each `[master, red, green, blue]`, -1..1, or one number for the master) · `curves {clip, master?, red?, green?, blue?, reset?}` (each up to 16 `[input, output]` points in 0..1, monotone cubic; `[]` straightens one) · `lut {clip, path?, mix?, clear?}` / `lut {relink, path}` (a `.cube` file, 1D or 3D up to 65, tetrahedral, mix 0..1; a broken file is refused; relink moves every clip naming a file, one undo step). The grade runs wheels → curves → LUT → the four sliders, in Rec. 709 R'G'B' for the first three; colour keys animate the sliders and the look holds under them; saved as v43 `wheels`/`curve`/`lut` lines. Recipe: `edit {ops:[{op:"lut", clip:"V1@0", path:"~/luts/warm.cube", mix:0.8}]}`, then `scopes {at:"2s"}` to read the shift · `copy_look {from, to | to_lane, what?}` (copies colour, transform, fit, effects, EQ, gain or speed onto other clips, one undo step) · `replace {clip, source, in?}` (the replace edit: overwrite the clip and its linked half with another source, same place and length) · `nudge {clips, by}` [group] (move clips by a signed distance, all or nothing) · `fit {clip, policy: fit\|fill\|stretch\|center}` · `deinterlace {clip, mode: frame\|field\|off\|ivtc-auto\|ivtc}` (how a video clip's interlaced source is made progressive, frame by default; only matters for an interlaced source, which `media_probe` reports; field and off are stored, the render acts on frame for now; `ivtc` removes 3:2 pulldown from telecined 29.97i H.264 and MPEG-2, giving the 23.976p film frames (best cadence found in the first 60 pictures, one cadence for the whole file), `ivtc-auto` does so only when that cadence is clear and otherwise deinterlaces as frame; put the project on 23.976 (`set_frame_rate`) for one timeline frame per film frame; soft pulldown (MPEG-2 repeat_first_field, H.264 pic_struct) in a transport stream is always presented as 23.976p; saved as v46 `deint` lines) · `visualizer {clip, on?, style?, fast?}` (the clip becomes a sound picture: style fill\|ribbon\|ring\|wave, fill by default; `fast` paints from a 0.2 s window; `on:false` turns it off, from the waveform picture or from the sound clip). On a sound clip, `on:true` places a waveform picture on the next free top picture lane (V2 or V3), grouped with the sound and covering the picture under it where they overlap; place it with `transform` (x, y move its centre, -1 to 1; scale; opacity). A picture address (`V1@…`) is mapped to its linked sound clip, which gets the picture; a picture with no linked sound is refused · `reframe {clip, aspect?=fit, smoothness?=0.5}` (auto reframe: a cheap saliency per sampled frame -- what moved since the last sample, local contrast, a pull to the middle, no models -- gives the subject's path, which is smoothed (`0.25 + 1.75 × smoothness` s), held still inside a dead zone and thinned to the keys where it turns; the keys scale the clip to cover the canvas and pan the subject to the middle, clamped so no edge ever shows; sets `fit` to fit and replaces the clip's `transform_keys` in one undo step, so no format change; it analyses before it answers; `aspect` is a guard that the project canvas has that shape; `engine::reframe`) · `stabilize {clip, on?, strength?=0.5, crop?=zoom, off?, cancel?}` (takes the camera shake out of a video clip: corners tracked frame to frame by pyramidal Lucas-Kanade, a shift-turn-zoom fitted by RANSAC, the camera path smoothed by a Gaussian of strength × 2 s (a steady pan is kept), each frame moved to the smoothed path before the clip's transform; `crop` `zoom` enlarges just enough that no frame shows an edge (≤1.5×), `full` keeps the frame and shows black edges; the analysis runs in the background, is cached per source and file-frame range under `~/.cache/edith/stabilise`, follows the footage through trims, speed, ramps and reverse; an export measures a missing analysis itself, which `export_status` shows as its `Measuring shake` stage with its own percent, while `frame` and `contact_sheet` never wait: they start it, draw the clip unstabilised and say the analysis is pending; `engine::stabilise`, format v44) | +| look | `color {clip, brightness?, contrast?, saturation?, tint?, reset?}` · `transform {clip, x?, y?, corner?, margin?, scale?, rotate?, crop?:[l,r,t,b], opacity?, reset?}` (`corner` is centre, top-left, top-right, bottom-left or bottom-right: the engine sets x and y from the picture's own size (after crop and quarter turn), the scale given and a `margin` in pixels (default 32) from the two edges it touches; giving x or y with corner is refused, and so is margin without corner; picture in picture is `corner:"bottom-right", scale:0.3`) · `transform_keys {clip, keys?:[{at, x?, y?, scale?, rotate?, opacity?, ease?}…], clear?}` (animates the transform over the clip's own time) · `opacity_keys {clip, keys?:[{at, opacity, ease?}…], clear?}` (opacity 0..1 over the clip's own time, fades multiply on top) · `color_keys {clip, keys?:[{at, brightness?, contrast?, saturation?, tint?, ease?}…], clear?}` (the grade over the clip's own time, interpolated per frame) · `look {clip, name}` (the whole grade becomes a look, one undo step: a built-in `Warm`, `Cool`, `Teal & orange`, `Bleach bypass`, `Black & white`, `Faded film`, `High contrast` or `Vintage`, or a saved one from the colour card's "Save current as look" (`$XDG_DATA_HOME/edith/looks/.look`); an unknown name is refused with the list; `help {topic:"looks"}` lists them) · `look {clip, save:""}` (the reverse: the clip's grade is saved as a look of that name, as the grading card's "Save current as look" does; the project does not change, so no undo step; a built-in's name is refused) · `auto_color {clip}` (reads the clip's middle frame as shot: grey-world white balance into the wheels' channel gains, then brightness and contrast so the 0.5 % and 99.5 % luma percentiles land near 0.02 and 0.98; saturation, tint, curves and LUT kept; the reply gives the values set; one undo step) · · `wheels {clip, lift?, gamma?, gain?, reset?}` (each `[master, red, green, blue]`, -1..1, or one number for the master) · `curves {clip, master?, red?, green?, blue?, reset?}` (each up to 16 `[input, output]` points in 0..1, monotone cubic; `[]` straightens one) · `lut {clip, path?, mix?, clear?}` / `lut {relink, path}` (a `.cube` file, 1D or 3D up to 65, tetrahedral, mix 0..1; a broken file is refused; relink moves every clip naming a file, one undo step). The grade runs wheels → curves → LUT → the four sliders, in Rec. 709 R'G'B' for the first three; colour keys animate the sliders and the look holds under them; saved as v43 `wheels`/`curve`/`lut` lines. Recipe: `edit {ops:[{op:"lut", clip:"V1@0", path:"~/luts/warm.cube", mix:0.8}]}`, then `scopes {at:"2s"}` to read the shift · `copy_look {from, to | to_lane, what?}` (copies colour, transform, fit, effects, EQ, gain or speed onto other clips, one undo step) · `replace {clip, source, in?}` (the replace edit: overwrite the clip and its linked half with another source, same place and length) · `nudge {clips, by}` [group] (move clips by a signed distance, all or nothing) · `fit {clip, policy: fit\|fill\|stretch\|center}` · `deinterlace {clip, mode: frame\|field\|off\|ivtc-auto\|ivtc}` (how a video clip's interlaced source is made progressive, frame by default; only matters for an interlaced source, which `media_probe` reports; field and off are stored, the render acts on frame for now; `ivtc` removes 3:2 pulldown from telecined 29.97i H.264 and MPEG-2, giving the 23.976p film frames (best cadence found in the first 60 pictures, one cadence for the whole file), `ivtc-auto` does so only when that cadence is clear and otherwise deinterlaces as frame; put the project on 23.976 (`set_frame_rate`) for one timeline frame per film frame; soft pulldown (MPEG-2 repeat_first_field, H.264 pic_struct) in a transport stream is always presented as 23.976p; saved as v46 `deint` lines) · `visualizer {clip, on?, style?, fast?}` (the clip becomes a sound picture: style fill\|ribbon\|ring\|wave, fill by default; `fast` paints from a 0.2 s window; `on:false` turns it off, from the waveform picture or from the sound clip). On a sound clip, `on:true` places a waveform picture on the next free top picture lane (V2 or V3), grouped with the sound and covering the picture under it where they overlap; place it with `transform` (x, y move its centre, -1 to 1; scale; opacity). A picture address (`V1@…`) is mapped to its linked sound clip, which gets the picture; a picture with no linked sound is refused · `reframe {clip, aspect?=fit, smoothness?=0.5}` (auto reframe: a cheap saliency per sampled frame -- what moved since the last sample, local contrast, a pull to the middle, no models -- gives the subject's path, which is smoothed (`0.25 + 1.75 × smoothness` s), held still inside a dead zone and thinned to the keys where it turns; the keys scale the clip to cover the canvas and pan the subject to the middle, clamped so no edge ever shows; sets `fit` to fit and replaces the clip's `transform_keys` in one undo step, so no format change; it analyses before it answers; `aspect` is a guard that the project canvas has that shape; `engine::reframe`) · `stabilize {clip, on?, strength?=0.5, crop?=zoom, off?, cancel?}` (takes the camera shake out of a video clip: corners tracked frame to frame by pyramidal Lucas-Kanade, a shift-turn-zoom fitted by RANSAC, the camera path smoothed by a Gaussian of strength × 2 s (a steady pan is kept), each frame moved to the smoothed path before the clip's transform; `crop` `zoom` enlarges just enough that no frame shows an edge (≤1.5×), `full` keeps the frame and shows black edges; the analysis runs in the background, is cached per source and file-frame range under `~/.cache/edith/stabilise`, follows the footage through trims, speed, ramps and reverse; an export measures a missing analysis itself, which `export_status` shows as its `Measuring shake` stage with its own percent, while `frame` and `contact_sheet` never wait: they start it, draw the clip unstabilised and say the analysis is pending; `engine::stabilise`, format v44) | | generated | `generator_add {kind: solid\|gradient\|countdown\|bars\|rectangle\|ellipse\|line\|arrow, color?, color2?, angle?, from?, fill?, stroke?, width?, radius?, lane?=V1, at?, duration?=5s}` (shapes `rectangle`, `ellipse`, `line` and `arrow` draw on a transparent canvas and composite over the lanes below: `fill` and `stroke` are `"#rrggbb"` or `"none"`, `width` the stroke in pixels 0..400, `radius` rounds a rectangle 0..2000; a line and an arrow are all stroke, a line runs left to right and an arrow points right; a shape lands at 40% scale and its size and place are the clip's `transform`; a clip made from numbers instead of a file: `color` is `"#ff3366"`, `angle` 0..359 degrees with 0 left to right and 90 top to bottom, `from` the countdown's whole seconds 1..3600, which is also its default duration; `at` defaults to the end of the lane; the lane must exist; a param the kind does not take, an unknown kind or a bad colour is refused by name; it overwrites what it lands on like a still, and is an ordinary clip afterwards, so trim, move, split, `color`, `transform` and effects all work) · `generator_set {clip, color?, color2?, angle?, from?, fill?, stroke?, width?, radius?}` (params merged onto a generator clip, place and length kept; a clip that plays a file is refused) · `adjustment_add {lane?=V2, at?, duration?=5s}` (a clip with no picture whose grade and effects reach everything composed beneath it; with no lane, V2, added when there is only V1; a transform on it moves the whole composite below, so uncovered area goes black, while crop only limits where it reaches and cropped-away areas keep the untouched picture; adjacent layers hard-cut) · `label {clip \| clips, value}` (a name from the label palette in any case, 1..8, or `none`) · `enable {clip \| clips, on}` (`on:false` keeps the clip but skips its picture and sound; an off adjustment layer stops adjusting). One undo step each; `timeline` and `clip_info` show `generator solid #ff3366`, `adjustment layer`, `label Rose` and `disabled`, and `media_list` does not call a generator an offline file. A generator's source is a pseudo-path `/edith-gen/.gen` (`engine::generate`), so the library, trims and saves treat it as a still. Format v48 (older formats still load): written only when a project has a generator, a label or a switched-off clip, so other projects keep their older version | | sequences | `nest {clips:[addr…], name?}` (folds the picked clips and their linked partners into a new sequence and leaves one compound clip, on the lowest picked video and sound lanes, linked; refuses when an unpicked clip sits between picked ones; one undo step) · `break_apart {clips}` (puts a compound clip's contents back, trimmed to the stretch it played, one undo step) · `place_sequence {sequence, at, lane?=V1}` (a sequence as a compound clip; a cycle is refused). A compound clip's source is `1<<30 + sequence id`; the render inlines it into the flat timeline, so a nested render equals the flat one; it has no speed, ramp or reverse (refused) and its own colour/effects/transform are not applied. Format v45 (`MAGIC_V44` still loads): the active sequence is the body as before, then `seqactive `, `seqorder ` and one `seq ` … `endseq` block per parked sequence holding a complete document; only written when there is more than one sequence or a compound clip, so other projects stay v44 or older. The frame rate is locked then | | multicam | `angle {clip, at?, angle?, audio?}` (switches a multicam clip's angle from `at` on: the clip is cut there when `at` is inside it, and the right part shows `angle`, a number from 1 or a name; the sound follows the picture unless `audio` is `"follow"` or an angle, which keeps it there; `clip` may be the picture or its linked sound clip; one undo step; refused for a clip that is not multicam, an angle that does not exist, or no change). A multicam clip is a compound clip (`source = 1<<30 + id`) with an `Angle {video, audio?}` on the clip; the sequence it plays is flagged multicam and holds angle `n` as its `n`th video lane and `n`th audio lane, so the render inlines exactly that angle's lane (`expand`), `break_apart` and `multicam_flatten` do the same. `timeline` rows read `multicam "Name" angle 2 "cam_b"`. Format v47 (`MAGIC_V46` and older still load; the version lives in `edith.rs` `MAGIC`/`NEWEST_VERSION`): `mcam ` lines in angle order after `seqorder`, and `angle ` per clip that is not on angle 1 (angles counted from 1); written only when a project has a multicam source or a switched clip, so other projects keep their older version | @@ -408,10 +408,12 @@ Piper's stderr is reported on failure. |---|---|---| | `export_start` | **out**, preset (an `export_presets` id; explicit args override it), loudness (-30 to -5 LUFS, the integrated target; the true peak holds at the preset's ceiling or -1 dBTP, the gain is cut back and never a limiter), format (mp4, av1, av1-mp4, hevc, hevc-mp4, webm, wav, flac, mp3, ogg, m4a, opus, prores, png_sequence, still, gif), gif_width (320/480/640/720, default 480), gif_fps (1-60, default 15), gif_loop (default true), range, size, fit, bitrate_kbps, audio_kbps (128/192/256/320), bit_depth (8\|10; 10 is AV1 and HEVC only), prores_profile (proxy\|lt\|standard\|hq\|4444\|4444xq; format `prores`, a `.mov`), hdr (off\|pq\|hlg; HEVC only, implies 10-bit), hevc_speed (default\|fast\|faster; HEVC only: fast is about 1.2-1.6x quicker for 0-3% more bits, faster about 1.5-2x quicker for up to 27% more), audio_bit_depth (16\|24; ProRes sound), chapters (default true; `"markers"` writes the comment markers as the chapters), intra_only, seat (auto\|hardware\|software), subtitles, burn_captions, overwrite | starts an export; returns `job:` at once. The reply counts the chapters written (`3 chapters`) and, for an AV1 or HEVC file, its depth (`output 10-bit, from the source`) · `queue` (true: line the export up behind the others -- it keeps its own copy of the timeline as it is now, so later edits do not change it, and starts when every earlier export has finished, one encode at a time, polled or not; `export_status` shows it as `waiting`; default false starts at once beside any others) | | `export_presets` | – | lists the export presets (id, label, format, bitrate_kbps, audio_kbps, size, bit_depth, prores_profile, hdr, loudness): youtube_1080p/1080p60/1080p_hevc/4k/4k60/4k_hevc, shorts_reels, podcast, podcast_ogg and podcast_opus (-16 LUFS, -1 dBTP), archive (10-bit AV1 mkv), archive_prores (ProRes 422 HQ .mov), hdr10_hevc (10-bit HEVC mp4 tagged PQ), archive_flac, archive_wav | -| `export_captions` | format (`srt` or `vtt`, required), path, overwrite | writes the timeline's captions (every cue on the subtitle lanes, in start order) as SRT or WebVTT; picture and empty cues are left out. Without `path`: ` edit.` in the Videos folder. Refuses an existing file unless `overwrite` is true, and writes nothing when there are no captions | +| `export_captions` | format (`srt` or `vtt`, required unless chapters), path, overwrite, chapters | writes the timeline's captions (every cue on the subtitle lanes, in start order) as SRT or WebVTT; picture and empty cues are left out. Without `path`: ` edit.` in the Videos folder. Refuses an existing file unless `overwrite` is true, and writes nothing when there are no captions. `chapters: true` writes nothing and returns the chapter markers as the YouTube description listing (`00:00 Intro`, one line each), the text File > Copy chapters copies, as the reply text and as JSON (`chapters` lines, `text`, `warnings`) | +| `proxies` | action (`status`, the default, `make`, `cancel` or `delete`), source (`src:`, a list or `"all"`) | the editing copies (proxies) of sources. `status` shows each source's state (ready, making with its percent, off, not needed for a sound or still, or why a stand-in failed). `make` starts one in the background and turns that film's switch back on; a film that plays at speed on this machine needs none, and says so. `cancel` stops one being made and leaves the film off, as the Proxies switch on a library row does. `delete` removes the stand-in and keeps the film off. With `auto_proxies` on, each `media_import` starts its stand-ins the same way | +| `speech_model` | download (false), model (`tiny`, `base` or `small`; default `base`), cancel (false) | the speech model that `transcript`, `find_words` and `auto_captions` run on: no argument shows which models are installed and the download in progress. `download: true` fetches a model in the background (the GUI's Download model fetches `base`); `cancel: true` stops it and keeps the files fetched so far. Nothing is downloaded unless `download` is true | | `export_status` | job, out | a queued job (`export_start {queue:true}`) reads `waiting` with the number of exports ahead of it; progress, elapsed, ETA, encoder, outcome of one job; while a stabilised clip is measured before it can encode, the line and `stage`/`stage_progress` name that stage (`Measuring shake`) with its own percent; `out` reports a file this session did not start; omitted, every export so far, with its size when done (decimal: 12,139,083 bytes is 12.1 MB) and the integrated loudness (LUFS) and true peak of the written file (`integrated_lufs`, `true_peak_dbtp`, measured once from the file with the `loudness` measurement), or its error when failed. When a job finishes, a peak over the format's ceiling gets a warning line: -1 dBTP for lossless (wav, flac), -2 dBTP for lossy (the rest, since encoding can overshoot the mix) | -| `export_cancel` | **job** | cancels a running job; a waiting (queued) job is removed from the queue and never starts | -| `render_preview` | range (`"all"`, the default, or `{from, to}`), cancel | pre-renders a stretch of the timeline at preview size into the render cache, so playback over it reads finished frames instead of compositing them (heavy sections: stacked effects, titles over video, colour, speed, multicam). One render at a time, in the background; `project_status` shows the progress and the cached ranges. A render is keyed by a hash of everything that changes its pixels (the clips overlapping it and their neighbours, their sources, titles, captions, tone, rate), so an edit inside a cached range drops it and playback composes live there again. `cancel: true` stops the running render and removes its partial file. The sound is not rendered; the live mix always plays | +| `export_cancel` | job, all | cancels a running job; a waiting (queued) job is removed from the queue and never starts. `all: true` cancels every unfinished export at once (the queued ones and the running one), as the export queue's Cancel all does. The queue's Pause and Start are not offered here: the MCP queue starts each job as the one before it ends, with no pause state to reach | +| `render_preview` | range (`"all"`, the default, or `{from, to}`), cancel, clear | `clear: true` deletes every render file in the cache (finished or half written) and says how many went, as File > Delete render files does; refused while a render is running. Pre-renders a stretch of the timeline at preview size into the render cache, so playback over it reads finished frames instead of compositing them (heavy sections: stacked effects, titles over video, colour, speed, multicam). One render at a time, in the background; `project_status` shows the progress and the cached ranges. A render is keyed by a hash of everything that changes its pixels (the clips overlapping it and their neighbours, their sources, titles, captions, tone, rate), so an edit inside a cached range drops it and playback composes live there again. `cancel: true` stops the running render and removes its partial file. The sound is not rendered; the live mix always plays | `format` is one of `mp4`, `av1`, `av1-mp4`, `hevc`, `hevc-mp4`, `webm`, `wav`, `flac`, `mp3`, `ogg`, `m4a` (AAC in an mp4 box, audio only), `opus` (Opus in Ogg, audio only, 48 kHz). Without `format` the extension of `out` decides, `.m4a` included. An diff --git a/crates/app/src/export_ui.rs b/crates/app/src/export_ui.rs index c9bea99..4ea8c10 100644 --- a/crates/app/src/export_ui.rs +++ b/crates/app/src/export_ui.rs @@ -60,7 +60,7 @@ pub(crate) const FRAME_RATES: [f64; 8] = [ /// beside them: a source's own rate is not a number this list has to name to /// offer it, since [`Choice::SampleRate`]`(None)` -- "source" -- already means /// exactly that, whatever the number turns out to be. -pub(crate) const SAMPLE_RATES: [u32; 3] = [44_100, 48_000, 96_000]; +pub(crate) use engine::playback::SAMPLE_RATES; /// The sound-rate list's rows: "source" first -- the derived rate, and the /// row in force with nothing picked -- then every rate on offer, the one in diff --git a/crates/app/src/player/export.rs b/crates/app/src/player/export.rs index e6a7cc6..80a0648 100644 --- a/crates/app/src/player/export.rs +++ b/crates/app/src/player/export.rs @@ -622,28 +622,7 @@ impl Player { /// inside the chosen range uses. A file only clips outside the range use does not count. pub(crate) fn export_missing(&self) -> Vec { let Some(session) = &self.session else { return Vec::new() }; - let offline = session.offline_sources(); - if offline.is_empty() { - return Vec::new(); - } - let span = self.export_span(); - let mut out: Vec = Vec::new(); - for lane in session.lanes() { - for clip in session.lane_clips(lane) { - let (start, end) = (clip.start, clip.start.saturating_add(clip.frames())); - if let Some((from, to)) = span - && (end <= from || start >= to) - { - continue; - } - if let Some((_, path)) = offline.iter().find(|(i, _)| *i == clip.source) - && !out.contains(path) - { - out.push(path.clone()); - } - } - } - out + session.offline_in_span(self.export_span()).into_iter().map(|(_, path)| path).collect() } /// Why the Export button is off, in a short plain phrase -- `None` when it can start. diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 5950a1c..c4467da 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -819,6 +819,10 @@ pub struct ImportProbe { rate: Rate, } +/// The project sound rates a person can pick, slowest first: the export sheet and the MCP +/// `project_settings sample_rate` both offer these. "Source" (no pick) is `None`, not a row here. +pub const SAMPLE_RATES: [u32; 3] = [44_100, 48_000, 96_000]; + /// How long one scrub snippet plays ([`PlaybackSession::scrub_audio`]): long enough to hear /// what a word or a beat is, short enough that a drag across a second of sound is a run of /// clicks rather than a smear. @@ -3295,6 +3299,34 @@ impl PlaybackSession { self.project.lanes() } + /// The offline sources an export of `span` reads, as `(index, path)`, each source once and + /// in the order the timeline meets them. `span` is the marked range, `None` for the whole + /// timeline. A clip wholly outside the span does not count, so a file only such clips use + /// does not stop the export. + pub fn offline_in_span(&self, span: Option<(u32, u32)>) -> Vec<(usize, PathBuf)> { + let offline = self.offline_sources(); + let mut out: Vec<(usize, PathBuf)> = Vec::new(); + if offline.is_empty() { + return out; + } + for lane in self.lanes() { + for clip in self.lane_clips(lane) { + let (start, end) = (clip.start, clip.start.saturating_add(clip.frames())); + if let Some((from, to)) = span + && (end <= from || start >= to) + { + continue; + } + if let Some((i, path)) = offline.iter().find(|(i, _)| *i == clip.source) + && !out.iter().any(|(_, p)| p == path) + { + out.push((*i, path.clone())); + } + } + } + out + } + /// The sources whose files are not on disk, as `(index, saved path)`. Their /// clips stay on the timeline; a frame or an export that reads one is /// refused naming it. diff --git a/crates/mcp/src/help.rs b/crates/mcp/src/help.rs index de8bc55..1493054 100644 --- a/crates/mcp/src/help.rs +++ b/crates/mcp/src/help.rs @@ -36,14 +36,14 @@ const TOPICS: [&str; 20] = [ /// group lands under `other`, and a test fails if that happens. const GROUPS: &[(&str, &[&str])] = &[ ("project", &["project_new", "templates", "project_open", "project_save", "project_collect", "project_export_timeline", "project_import_timeline", "project_status", "project_settings"]), - ("media", &["media_probe", "media_import", "media_list", "media_remove", "media_relink", "media_bin"]), + ("media", &["media_probe", "media_import", "media_list", "media_remove", "media_relink", "media_bin", "proxies"]), ("look", &["timeline", "clip_info"]), ("see", &["frame", "contact_sheet", "scopes"]), ("scan", &["scenes", "stabilize_status", "track", "track_status"]), ("hear", &["levels", "silence", "cut_silence", "loudness", "normalize", "clean_voice"]), ("edit", &["edit", "sequence", "multicam_create", "multicam_flatten", "effect", "undo", "redo", "checkpoint", "restore", "checkpoints"]), ("export", &["export_start", "export_presets", "export_status", "export_cancel", "export_captions", "render_preview"]), - ("listen", &["transcript", "find_words", "auto_captions"]), + ("listen", &["transcript", "find_words", "auto_captions", "speech_model"]), ("captions", &["captions"]), ("speak", &["voices", "voiceover"]), ("record", &["record"]), @@ -358,10 +358,16 @@ PROJECT a name taken by another file becomes name-2.ext; the same bytes already there are reused. One undo step; unsaved until project_save. A failed copy changes nothing. project_export_timeline {format, path?} writes the active sequence for another editor: format otio (OpenTimelineIO .otio), fcpxml (Final Cut Pro XML 1.10, for Final Cut Pro, Resolve and Premiere) or edl (CMX3600: V1 and A1/A2). Subtitles are left out and the reply says so. Default path: beside the project file. Only the file is written. project_import_timeline {path} reads an .otio file as a new sequence of the project and makes it the active one, relinking each clip by its path; a missing file becomes offline. One undo step. + proxies {action:status|make|cancel|delete, source} manages editing copies: make starts one in the background (its progress shows in status), cancel stops it and leaves the film off, delete removes it and keeps the film off. With auto_proxies on, each media_import starts its stand-ins. + speech_model {download?, model?, cancel?} shows the speech models installed and any download in progress; download:true fetches one in the background (base by default). + export_captions {chapters:true} returns the chapter list as the YouTube description text, with JSON lines, writing no file. export_cancel {all:true} cancels every unfinished export. + render_preview {clear:true} deletes every render file in the cache (refused while a render runs). project_status reports the open project. project_settings sets resolution, fps, tonemap, proxies, auto_proxies, encoder, the master limiter, the notes (free text, several lines, shown by project_status when set) and the still length (still_secs, 0.5 to 600 s, 5 by default: stills placed after the change take it). Each change and each refusal is reported. - The sample rate the mix runs at is not set here: project_status shows it. Unset, it is the highest rate among the sources, or 48 kHz when every source is below 44.1 kHz. + sample_rate sets the mix's rate: \"source\" (unset: the highest rate among the sources, or 48 kHz when every source is below 44.1 kHz), 44100, 48000 or 96000, the rows the GUI offers. + project_status {history:true} also lists every undo and redo step with the steps count that undo or redo takes to reach it (undo {steps:3} takes back the three newest). + templates {save:{name, with_clips?}} saves the open project as a template (settings, and the clips too with with_clips:true); a built-in's name is refused. An fps change keeps clips, captions and titles at the same seconds; their frame numbers, and so their addresses (V1@450), change with the rate. Positions are rounded to whole frames at the new rate, so a round trip (to another fps and back) can shift a cut by up to a frame; check the cut with timeline. @@ -691,7 +697,7 @@ const OP_TEXTS: &[(&str, &str)] = &[ ), ( "look", - "look {clip, name} — the clip's whole grade becomes a look: a built-in (Warm, Cool, Teal & orange, Bleach bypass, Black & white, Faded film, High contrast, Vintage) or one saved from the colour card as \"Save current as look\". It replaces the colour sliders, wheels, curves and LUT in one undo step, and a keyed clip is refused until its keys are cleared. A name nobody has is refused with the list of looks there are. e.g. edit {ops:[{op:\"look\", clip:\"V1@0\", name:\"Teal & orange\"}]}. help {topic:\"looks\"} explains them.", + "look {clip, name} — the clip's whole grade becomes a look: a built-in (Warm, Cool, Teal & orange, Bleach bypass, Black & white, Faded film, High contrast, Vintage) or one saved from the colour card as \"Save current as look\". It replaces the colour sliders, wheels, curves and LUT in one undo step, and a keyed clip is refused until its keys are cleared. A name nobody has is refused with the list of looks there are. e.g. edit {ops:[{op:\"look\", clip:\"V1@0\", name:\"Teal & orange\"}]}. look {clip, save:\"My look\"} goes the other way: the clip's grade is saved as a look of that name (no undo step, the project does not change). help {topic:\"looks\"} explains them.", ), ( "auto_color", diff --git a/crates/mcp/src/main.rs b/crates/mcp/src/main.rs index c74db83..5f9c57a 100644 --- a/crates/mcp/src/main.rs +++ b/crates/mcp/src/main.rs @@ -69,6 +69,7 @@ fn main() { } // A queued export starts the moment the one before it ends, polled or not. tools::export::advance(&mut server); + tools::media::poll_proxies(&mut server); let line = match lines_rx.recv_timeout(Duration::from_millis(100)) { Ok(Ok(line)) => line, Ok(Err(_)) | Err(RecvTimeoutError::Disconnected) => break, diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 4f78e96..2158902 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -39,6 +39,10 @@ pub struct Server { /// the history did not survive the open. Cleared wherever a new edit lands. pub history_lost_on_open: bool, pub jobs: Vec, + /// Editing copies (proxies) being made or settled, one per source (`proxies`). + pub proxy_runs: Vec, + /// The speech model download running or finished (`speech_model`). + pub speech_download: Option, /// The render preview being made, and the frames it covers ([`engine::render_cache`]). pub render: Option<(engine::render_cache::Job, (u32, u32))>, /// Set when the open project came from a file with a newer autosave beside it that was diff --git a/crates/mcp/src/tools/edit.rs b/crates/mcp/src/tools/edit.rs index 0a9ba47..61fda90 100644 --- a/crates/mcp/src/tools/edit.rs +++ b/crates/mcp/src/tools/edit.rs @@ -303,7 +303,7 @@ fn accepted_keys(name: &str) -> Option<&'static [&'static str]> { "lut" => &["clip", "path", "mix", "clear", "relink"], "wheels" => &["clip", "lift", "gamma", "gain", "reset"], "curves" => &["clip", "master", "red", "green", "blue", "reset"], - "look" => &["clip", "name"], + "look" => &["clip", "name", "save"], "auto_color" => &["clip"], "transform" => &["clip", "x", "y", "corner", "margin", "scale", "rotate", "crop", "reset", "opacity"], "transform_keys" => &["clip", "keys", "clear"], diff --git a/crates/mcp/src/tools/edit_fx.rs b/crates/mcp/src/tools/edit_fx.rs index 48156c1..8c608f9 100644 --- a/crates/mcp/src/tools/edit_fx.rs +++ b/crates/mcp/src/tools/edit_fx.rs @@ -299,8 +299,19 @@ fn wheels(s: &mut PlaybackSession, op: &Value) -> Result { /// `look {clip, name}`: the clip's grade becomes the look `name` (a built-in, or a saved /// one from the colour card's "Save current as look"), replacing its colour, wheels, curves /// and LUT in one undo step. A name nobody has gets the list of the looks there are. +/// `look {clip, save: ""}` is the other way round: the clip's grade is saved as a look +/// of that name (the grading card's "Save current as look" does the same), and the project does +/// not change, so there is no undo step. fn look(s: &mut PlaybackSession, op: &Value) -> Result { - let (lane, idx, raw, start, _) = look_target(s, op, "look")?; + let (lane, idx, raw, start, grade) = look_target(s, op, "look")?; + if let Some(saved) = op.get("save") { + let who = format!("look {raw} save"); + let Some(name) = saved.as_str() else { + return Err(format!("{who}: `save` is the name to save the grade under, as a string")); + }; + let path = engine::looks::save(name, &grade).map_err(|e| format!("{who}: {e}"))?; + return Ok(done(format!("{who} {} → {}", name.trim(), path.display()), vec![(lane, start)])); + } let who = format!("look {raw}"); let name = req_str(op, "name")?; let keyed = s.color_keys_of(lane, idx).len(); diff --git a/crates/mcp/src/tools/export.rs b/crates/mcp/src/tools/export.rs index 2669dc2..37f58ef 100644 --- a/crates/mcp/src/tools/export.rs +++ b/crates/mcp/src/tools/export.rs @@ -42,7 +42,7 @@ pub fn tools() -> Vec { }, Tool { name: "export_captions", - description: "Write the timeline's captions (every cue on the subtitle lanes, in start order) to a text file: SRT or WebVTT. Picture cues and empty ones are left out. Writes nothing and says so when there are no captions. Refuses an existing file unless overwrite is true.", + description: "Write the timeline's captions (every cue on the subtitle lanes, in start order) to a text file: SRT or WebVTT. Picture cues and empty ones are left out. Writes nothing and says so when there are no captions. Refuses an existing file unless overwrite is true. chapters: true instead returns the chapter markers as the YouTube description listing (the text File > Copy chapters copies), with its warnings, and writes no file.", schema: captions_schema, run: export_captions, }, @@ -54,7 +54,7 @@ pub fn tools() -> Vec { }, Tool { name: "export_cancel", - description: "Cancel a running export. The worker stops at its next checkpoint and deletes the partial file.", + description: "Cancel a running export. The worker stops at its next checkpoint and deletes the partial file. all: true cancels every unfinished export at once, the queued ones (which never start) and the running one; the same as the export queue's Cancel all.", schema: cancel_schema, run: export_cancel, }, @@ -97,17 +97,37 @@ fn captions_schema() -> Value { json!({ "type": "object", "properties": { + "chapters": {"type": "boolean", "description": "true returns the timeline's chapter markers as the YouTube description listing (00:00 Intro, one line each) that File > Copy chapters copies. Writes no file; format and path are not used. The reply carries the text and the lines as JSON, plus any warnings the YouTube rules raise."}, "format": {"type": "string", "enum": ["srt", "vtt"], "description": "srt = SubRip (00:00:01,000); vtt = WebVTT with its WEBVTT header (00:00:01.000)."}, "path": {"type": "string", "description": "Path of the file to write. A leading ~/ is expanded; its folder must exist and its extension must match the format. Omitted: edit. in the Videos folder (Untitled when there are no sources)."}, "overwrite": {"type": "boolean", "description": "Replace the file when it already exists. Default false."} }, - "required": ["format"], "additionalProperties": false }) } +/// The chapter list as YouTube description text: what File > Copy chapters copies +/// (`engine::playback::PlaybackSession::youtube_chapters`), returned rather than copied. +fn chapter_list(srv: &Server) -> Reply { + let s = tri!(srv.session_ref()); + let (text, warnings) = s.youtube_chapters(); + if text.is_empty() { + return Reply::err("no chapters on the timeline: add a chapter marker first"); + } + let lines: Vec = text.lines().map(str::to_string).collect(); + let mut shown = text.clone(); + for w in &warnings { + shown.push_str(&format!("\nwarning: {w}")); + } + Reply::ok(shown).with(json!({"chapters": lines, "count": lines.len(), "text": text, "warnings": warnings})) +} + /// File > Export captions: the timeline's caption cues as SRT or WebVTT, written at `path`. +/// With `chapters: true` it returns the YouTube chapter listing instead, writing nothing. fn export_captions(srv: &mut Server, args: &Value) -> Reply { + if opt_bool(args, "chapters").unwrap_or(false) { + return chapter_list(srv); + } let format = match opt_str(args, "format") { Some(f @ ("srt" | "vtt")) => f, _ => return Reply::err("format is srt or vtt".to_string()), @@ -293,9 +313,12 @@ fn cancel_schema() -> Value { "type": "integer", "minimum": 1, "description": "The job number from export_start (job:). A waiting (queued) job is removed from the queue and never starts; a running one stops and its partial file is deleted." + }, + "all": { + "type": "boolean", + "description": "true cancels every unfinished export: waiting ones are removed, the running one stops and its partial file is deleted. Give either job or all." } - }, - "required": ["job"] + } }) } @@ -1266,19 +1289,6 @@ fn human_bytes(n: u64) -> String { fn export_start(srv: &mut Server, args: &Value) -> Reply { let out_raw = tri!(arg_str(args, "out")); let overwrite = opt_bool(args, "overwrite").unwrap_or(false); - // An offline source has no picture or sound to put in the file: refused by name, before - // anything is written. - if let Ok(s) = srv.session_ref() { - let offline = s.offline_sources(); - if !offline.is_empty() { - let names: Vec = offline.iter().map(|(i, p)| format!("src:{i} {}", p.display())).collect(); - return Reply::err(format!( - "export refused: {} source(s) offline (moved or deleted): {}; media_relink each one, or project_open with search", - offline.len(), - names.join(", ") - )); - } - } let (anchored, anchor_note) = match anchor_out(srv, out_raw) { Ok(v) => v, Err(e) => return Reply::err(e), @@ -1368,6 +1378,17 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply { Ok(None) => (None, false), Err(e) => return Reply::err(e), }; + // An offline source is refused by name only when a clip this export reads uses it: a file + // that only clips outside the range use does not stop the export (the GUI's export_missing). + let missing = s.offline_in_span(range); + if !missing.is_empty() { + let names: Vec = missing.iter().map(|(i, p)| format!("src:{i} {}", p.display())).collect(); + return Reply::err(format!( + "export refused: {} source(s) offline (moved or deleted) inside the exported range: {}; media_relink each one, or project_open with search", + missing.len(), + names.join(", ") + )); + } let ranged = range.is_some(); let captions_note = (range.is_none() && media < end).then(|| { format!( @@ -1615,6 +1636,11 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply { // The export's own copy of the timeline: a `fit` puts every picture clip on that policy in // this copy only, and the project keeps its clips. let (mut project, meta) = s.export_snapshot(); + // The export's copy drops the clips outside the range that read an offline file, as the GUI's + // export does (`drop_offline_outside`); the project keeps them. + if let Some(span) = range { + project.drop_offline_outside(span, engine::source_present); + } let fitted: Option<(FitPolicy, FitOutcome)> = fit.map(|f| (f, fit_picture_clips(&mut project, f))); // A caption burned where a title sits in the same place, on screen together: named before // the file is written, since the overlap is in the picture. @@ -2102,8 +2128,25 @@ fn took_secs(job: &Job) -> Option { } fn export_cancel(srv: &mut Server, args: &Value) -> Reply { + if opt_bool(args, "all").unwrap_or(false) { + // The GUI queue's Cancel all: every unfinished job is cancelled through the same per-job cancel. + let open: Vec = srv.jobs.iter().enumerate().filter(|(_, j)| j.outcome.is_none() && !j.is_finished()).map(|(i, _)| i).collect(); + if open.is_empty() { + return Reply::ok("no export is unfinished: nothing to cancel"); + } + let waiting = open.iter().filter(|&&i| srv.jobs[i].waiting()).count(); + for i in &open { + srv.jobs[*i].cancel(); + } + return Reply::ok(format!( + "cancelled {} export{}: {waiting} waiting removed, {} running stopped (partial files deleted)", + open.len(), + if open.len() == 1 { "" } else { "s" }, + open.len() - waiting + )); + } let Some(n) = opt_u64(args, "job") else { - return Reply::err("export_cancel needs `job`: the number from export_start (job:)"); + return Reply::err("export_cancel needs `job`: the number from export_start (job:), or all: true"); }; let i = match job_index(srv, n) { Ok(i) => i, diff --git a/crates/mcp/src/tools/listen.rs b/crates/mcp/src/tools/listen.rs index d33b732..8166de6 100644 --- a/crates/mcp/src/tools/listen.rs +++ b/crates/mcp/src/tools/listen.rs @@ -223,9 +223,98 @@ pub fn tools() -> Vec { Tool { name: "transcript", description: TRANSCRIPT_DOC, schema: transcript_schema, run: run_transcript }, Tool { name: "find_words", description: FIND_DOC, schema: find_schema, run: run_find }, Tool { name: "auto_captions", description: CAPTIONS_DOC, schema: captions_schema, run: run_captions }, + Tool { name: "speech_model", description: SPEECH_MODEL_DOC, schema: speech_model_schema, run: speech_model }, ] } +// ---- speech model ---------------------------------------------------------- + +const SPEECH_MODEL_DOC: &str = "The speech model that transcript, find_words and auto_captions run on: which are installed, and the download in progress. With no argument it is the status. download:true fetches a model in the background (model is tiny, base or small; default base, the one the GUI's Download model fetches from huggingface.co); the status shows its percent until it is installed, and a download that fails says why. cancel:true stops the download running now and keeps the files already fetched for the next try. Nothing is downloaded unless download is true."; + +/// A speech model download running in the background, and how it ended once it has. +pub struct SpeechDownload { + pub model: String, + pub job: std::sync::Arc, + pub handle: Option>>, + pub outcome: Option, +} + +fn speech_model_schema() -> Value { + json!({ + "type": "object", + "properties": { + "download": {"type": "boolean", "description": "true starts downloading the model in the background."}, + "model": {"type": "string", "enum": ["tiny", "base", "small"], "description": "The model to download. Default base."}, + "cancel": {"type": "boolean", "description": "true stops the download running now."} + }, + "additionalProperties": false + }) +} + +/// Settles a download whose thread has finished, once, into its outcome line. +fn poll_speech_download(srv: &mut Server) { + let Some(d) = srv.speech_download.as_mut() else { return }; + if !d.handle.as_ref().is_some_and(std::thread::JoinHandle::is_finished) { + return; + } + let Some(handle) = d.handle.take() else { return }; + d.outcome = Some(match handle.join() { + Ok(Ok(())) => format!("the {} speech model is installed", d.model), + Ok(Err(e)) if e == engine::speech::CANCELLED => "download cancelled; the files fetched so far are kept".into(), + Ok(Err(e)) => format!("download failed: {e}"), + Err(_) => "download failed: the download thread stopped".into(), + }); +} + +fn speech_model(srv: &mut Server, args: &Value) -> Reply { + poll_speech_download(srv); + let running = srv.speech_download.as_ref().is_some_and(|d| d.handle.is_some()); + if opt_bool(args, "cancel") == Some(true) { + return match srv.speech_download.as_ref().filter(|_| running) { + Some(d) => { + d.job.cancel.store(true, std::sync::atomic::Ordering::Relaxed); + Reply::ok(format!("stopping the {} download", d.model)) + } + None => Reply::ok("no speech model download is running"), + }; + } + if opt_bool(args, "download") == Some(true) { + if running { + return Reply::err("a speech model download is already running: speech_model shows its progress"); + } + let model = opt_str(args, "model").unwrap_or("base"); + if let Err(e) = check_model(model) { + return Reply::err(e); + } + if engine::speech::installed_models().contains(&model) { + return Reply::ok(format!("the {model} speech model is already installed")); + } + // The same call the GUI's Download model makes, on a thread of its own. + let job = std::sync::Arc::new(engine::speech::Job::default()); + let worker = job.clone(); + let name = model.to_string(); + let thread_name = name.clone(); + let handle = std::thread::spawn(move || engine::speech::download_model(&thread_name, &worker)); + srv.speech_download = Some(SpeechDownload { model: name, job, handle: Some(handle), outcome: None }); + return Reply::ok(format!("downloading the {model} speech model in the background; speech_model shows the progress")); + } + let installed = engine::speech::installed_models(); + let have = if installed.is_empty() { "none installed".to_string() } else { format!("installed: {}", installed.join(", ")) }; + let state = match srv.speech_download.as_ref() { + Some(d) if running => format!("downloading {} {:.0}%", d.model, d.job.fraction() * 100.0), + Some(d) => d.outcome.clone().unwrap_or_default(), + None => "no download started".to_string(), + }; + let text = format!("speech models: {have} (offered: {}); {state}", MODELS.join(", ")); + Reply::ok(text).with(json!({ + "installed": installed, + "offered": MODELS, + "downloading": running, + "progress": srv.speech_download.as_ref().filter(|_| running).map(|d| d.job.fraction()), + "outcome": srv.speech_download.as_ref().and_then(|d| d.outcome.clone()), + })) +} + // ---- targets -------------------------------------------------------------- /// What a `target` names. `Mix` is the whole timeline as an export renders it. diff --git a/crates/mcp/src/tools/media.rs b/crates/mcp/src/tools/media.rs index a421740..d593b0a 100644 --- a/crates/mcp/src/tools/media.rs +++ b/crates/mcp/src/tools/media.rs @@ -3,6 +3,9 @@ //! `media_probe` reads headers only and never touches the open project. //! `media_import` adds sources to the open project; it places nothing. use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::thread::{self, JoinHandle}; use engine::{probe_bitrate, probe_media, MediaFacts}; use serde_json::{json, Value}; @@ -68,6 +71,12 @@ pub fn tools() -> Vec { }, run: import, }, + Tool { + name: "proxies", + description: "The editing copies (proxies) of the sources: a smaller re-encode of a heavy film that the editor plays and cuts on. action status (the default) shows each source's state and the progress of a stand-in being made; action make with source starts one in the background (it turns the film's switch back on); action cancel stops one being made (the film stays off, as the Proxies switch on a library row leaves it); action delete removes the stand-in and keeps the film off. source is src:, a list, or \"all\". A film that plays at speed on this machine needs none, and says so. With project_settings auto_proxies on, every import starts its stand-in the same way. Example: proxies {action:\"make\", source:\"src:2\"}.", + schema: proxies_schema, + run: proxies, + }, Tool { name: "media_remove", description: "Drop an unused source (src:) from the open project. Refused, naming the clips, while any clip plays from it. The undo history is kept when the source is the last one; any other source renumbers the sources after it, which clears the undo history, so that is refused unless force is true. The project is left unsaved until project_save.", @@ -1126,6 +1135,8 @@ fn import(server: &mut Server, args: &Value) -> Reply { let mut lines: Vec = Vec::new(); let mut imported: Vec = Vec::new(); let mut failed = 0usize; + // The sources this call added: with auto_proxies on, each starts its stand-in below. + let mut added: Vec = Vec::new(); { let s = tri!(server.session()); for path in &files { @@ -1159,6 +1170,7 @@ fn import(server: &mut Server, args: &Value) -> Reply { Some(r) => (file_name(&r.spelled()), format!("image sequence, {} frames", r.count)), None => (name.clone(), duration_text(path, &probe_media(path))), }; + added.push(n); lines.push(ImportLine::Imported(format!("src:{n} {shown} ({dur})"))); lines.extend(audio_warnings(path).into_iter().map(|w| ImportLine::Note(format!(" {name}: {w}")))); imported.push(json!({ @@ -1187,6 +1199,15 @@ fn import(server: &mut Server, args: &Value) -> Reply { ))); } remember_sources(server); + // The GUI import path: with Auto proxies on, every import starts its stand-in (the engine + // decides per file whether one is wanted, and a switched-off film gets none). + let auto = server.session.as_ref().is_some_and(|s| s.auto_proxies()); + if auto { + let paths: Vec = server.session.as_ref().map(|s| added.iter().map(|&n| s.sources()[n].path.clone()).collect()).unwrap_or_default(); + for p in paths { + start_run(server, p); + } + } // Counted by the engine's push count, so an import at the undo cap still lands // on the ledger; one ledger entry for the whole call. if let Some(s) = server.session.as_ref() { @@ -1526,6 +1547,183 @@ fn resolve_sources(count: usize, raw: Option<&Value>) -> Result, Stri } } +// ---- proxies ---------------------------------------------------------------- + +/// One stand-in being made for a source. The header read (which decides whether the film needs +/// one) runs on its own thread, then the encode is a [`engine::proxy::Job`] the status polls. +pub struct ProxyRun { + pub source: PathBuf, + pub cancel: Arc, + pub reading: Option, String>>>, + pub job: Option, + /// How the run ended, once it has: ready, stopped, failed, or needs no stand-in. + pub outcome: Option, +} + +impl ProxyRun { + fn settled(&self) -> bool { + self.reading.is_none() && self.job.is_none() + } +} + +fn proxies_schema() -> Value { + schema( + json!({ + "action": {"type": "string", "enum": ["status", "make", "cancel", "delete"], "description": "What to do. Default status."}, + "source": {"type": ["string", "array"], "items": {"type": "string"}, "description": "src:, a list of them, or \"all\". status with none shows every source; make, cancel and delete need one."} + }), + &[], + ) +} + +/// Starts the stand-in of `source` in the background, unless one is already being made. The +/// film's own switch is turned on first: the engine's check (`generate_if_wanted`) answers none +/// for a film switched off by hand. +fn start_run(srv: &mut Server, source: PathBuf) { + if srv.proxy_runs.iter().any(|r| r.source == source && !r.settled()) { + return; + } + engine::proxy::set_off(&source, false); + srv.proxy_runs.retain(|r| r.source != source); + let cancel = Arc::new(AtomicBool::new(false)); + let (path, flag) = (source.clone(), cancel.clone()); + let reading = thread::spawn(move || engine::proxy::generate_if_wanted(&path, &flag).map_err(|e| e.to_string())); + srv.proxy_runs.push(ProxyRun { source, cancel, reading: Some(reading), job: None, outcome: None }); +} + +/// Moves every run on: a finished header read starts its encode (or settles as needing none), a +/// finished encode settles with its outcome. Called by the status and on every server tick. +pub fn poll_proxies(srv: &mut Server) { + for run in srv.proxy_runs.iter_mut() { + if run.reading.as_ref().is_some_and(JoinHandle::is_finished) { + let Some(handle) = run.reading.take() else { continue }; + match handle.join() { + Ok(Ok(Some(job))) => { + // A stop asked while the header was read is carried into the encode at once. + if run.cancel.load(Ordering::Acquire) { + job.cancel(); + } + run.job = Some(job); + } + Ok(Ok(None)) => run.outcome = Some("needs no stand-in: it plays at speed here".into()), + Ok(Err(e)) => run.outcome = Some(format!("failed: {e}")), + Err(_) => run.outcome = Some("failed: the reader stopped unexpectedly".into()), + } + } + if run.job.as_ref().is_some_and(engine::proxy::Job::is_finished) { + let Some(job) = run.job.take() else { continue }; + let stopped = run.cancel.load(Ordering::Acquire); + run.outcome = Some(match job.outcome() { + Some(Ok(_)) => "ready".into(), + Some(Err(_)) if stopped => "stopped".into(), + Some(Err(e)) => format!("failed: {e}"), + None => "failed: the encoder returned no result".into(), + }); + } + } +} + +/// The unfinished run for `source`, if one is going. +fn running_for(srv: &Server, source: &Path) -> Option { + srv.proxy_runs.iter().position(|r| r.source == source && !r.settled()) +} + +/// One source's proxy state in words, as the status shows it. +fn proxy_state(srv: &Server, source: &Path) -> String { + if let Some(run) = srv.proxy_runs.iter().find(|r| r.source == source && !r.settled()) { + return if run.cancel.load(Ordering::Acquire) { + "stopping".into() + } else if let Some(job) = &run.job { + format!("making, {:.0}% done", job.progress() * 100.0) + } else { + "reading the file".into() + }; + } + if engine::proxy::cached(source).is_some() { + return "ready: edited and played through the proxy".into(); + } + if engine::is_audio(source) || engine::is_image(source) { + return "not needed: a sound or a still".into(); + } + if let Some(run) = srv.proxy_runs.iter().rev().find(|r| r.source == source) + && let Some(outcome) = &run.outcome + { + return outcome.clone(); + } + if engine::proxy::is_off(source) { "off: the film itself plays".into() } else { "none made".into() } +} + +/// `proxies {action, source}`: the status of each source's stand-in, or make, cancel or delete one. +fn proxies(srv: &mut Server, args: &Value) -> Reply { + poll_proxies(srv); + let action = opt_str(args, "action").unwrap_or("status"); + if !matches!(action, "status" | "make" | "cancel" | "delete") { + return Reply::err(format!("action `{action}` is not one of status, make, cancel, delete")); + } + let s = tri!(srv.session_ref()); + let count = s.sources().len(); + let picked = match (action, args.get("source")) { + ("status", None | Some(Value::Null)) => (0..count).collect(), + (_, None | Some(Value::Null)) => return Reply::err(format!("{action} needs `source`: src:, a list, or \"all\"")), + (_, Some(v)) => match resolve_sources(count, Some(v)) { + Ok(list) => list, + Err(e) => return Reply::err(e), + }, + }; + let paths: Vec<(usize, PathBuf)> = picked.iter().map(|&i| (i, s.sources()[i].path.clone())).collect(); + let mut lines: Vec = Vec::new(); + for (i, path) in &paths { + let name = file_name(path); + match action { + "make" => { + if engine::is_audio(path) || engine::is_image(path) { + lines.push(format!("src:{i} {name}: no stand-in needed (a sound or a still)")); + } else if running_for(srv, path).is_some() { + lines.push(format!("src:{i} {name}: already being made")); + } else if engine::proxy::cached(path).is_some() { + lines.push(format!("src:{i} {name}: already ready")); + } else { + start_run(srv, path.clone()); + lines.push(format!("src:{i} {name}: making in the background; proxies status shows the progress")); + } + } + "cancel" | "delete" => { + if let Some(k) = running_for(srv, path) { + let run = &srv.proxy_runs[k]; + run.cancel.store(true, Ordering::Release); + if let Some(job) = &run.job { + job.cancel(); + } + engine::proxy::set_off(path, true); + lines.push(format!("src:{i} {name}: stopping the stand-in; the film stays off")); + } else if action == "cancel" { + lines.push(format!("src:{i} {name}: no stand-in is being made")); + } + if action == "delete" { + match engine::proxy::delete(path) { + Ok(gone) => { + engine::proxy::set_off(path, true); + lines.push(match gone { + true => format!("src:{i} {name}: stand-in deleted; the film stays off and plays original"), + false => format!("src:{i} {name}: no stand-in to delete; the film stays off"), + }); + } + Err(e) => lines.push(format!("src:{i} {name}: could not delete the stand-in, it is still in use: {e}")), + } + } + } + _ => lines.push(format!("src:{i} {name}: {}", proxy_state(srv, path))), + } + } + let states: Vec = paths + .iter() + .map(|(i, path)| json!({"src": i, "path": path.display().to_string(), "state": proxy_state(srv, path)})) + .collect(); + let running = srv.proxy_runs.iter().filter(|r| !r.settled()).count(); + let text = if lines.is_empty() { "no sources in the project".to_string() } else { format!("{}\n{running} stand-in(s) being made", lines.join("\n")) }; + Reply::ok(text).with(json!({"sources": states, "making": running})) +} + /// `media_bin`: the library's bins and favourites. fn bin(server: &mut Server, args: &Value) -> Reply { let action: String = opt_str(args, "action").unwrap_or_default().to_owned(); diff --git a/crates/mcp/src/tools/project.rs b/crates/mcp/src/tools/project.rs index dd11738..955299a 100644 --- a/crates/mcp/src/tools/project.rs +++ b/crates/mcp/src/tools/project.rs @@ -43,8 +43,24 @@ pub fn tools() -> Vec { }, Tool { name: "templates", - description: "The project templates: the built-ins and the ones saved with File > Save as template, each with whether it keeps clips. Pass a name as project_new's template.", - schema: || schema(json!({}), &[]), + description: "The project templates: the built-ins and the ones saved with File > Save as template, each with whether it keeps clips. Pass a name as project_new's template. With save: {name, with_clips?} it saves the open project as a template of that name (replacing one of the same name, and refusing a built-in's name): its settings always, its clips and their sources when with_clips is true and the project has sources. The project does not change.", + schema: || { + schema( + json!({ + "save": { + "type": "object", + "description": "Save the open project as a template.", + "properties": { + "name": {"type": "string", "description": "The template's name: 1 to 40 characters, no slashes, not a built-in's name."}, + "with_clips": {"type": "boolean", "description": "Keep the clips and their sources too. Default false: settings only."} + }, + "required": ["name"], + "additionalProperties": false + } + }), + &[], + ) + }, run: templates_list, }, Tool { @@ -121,8 +137,15 @@ pub fn tools() -> Vec { }, Tool { name: "project_status", - description: "Project path, saved or dirty, canvas size, frame rate, duration, lanes with clip counts, sources, undo and redo steps, running exports, the colour looks (built-in and saved, by name, for the look op), and settings.", - schema: || schema(json!({}), &[]), + description: "Project path, saved or dirty, canvas size, frame rate, duration, lanes with clip counts, sources, undo and redo steps, running exports, the colour looks (built-in and saved, by name, for the look op), and settings. history: true also lists every undo step and every redo step, newest first, each with the number undo {steps} or redo {steps} takes to reach it (1 is the newest undo step, and undo {steps: N} takes back the N newest).", + schema: || { + schema( + json!({ + "history": {"type": "boolean", "description": "List every undo and redo step with its index, so undo {steps} can target any point. Default false."} + }), + &[], + ) + }, run: project_status, }, Tool { @@ -137,6 +160,7 @@ pub fn tools() -> Vec { "tonemap": {"type": "string", "enum": ["reference", "standard", "vivid"], "description": "HDR to SDR rendition."}, "notes": {"type": "string", "examples": ["Cut the intro to 30 s"], "description": "The project's notes: free text, several lines allowed (a newline is \\n in JSON). An empty string clears them. Saved with the project; one undo step."}, "still_secs": {"type": "number", "description": "How long a still image is placed for, in seconds: 0.5 to 600 (default 5). Stills placed after this change take it; clips already placed keep theirs. Saved with the project; one undo step."}, + "sample_rate": {"description": "The project's sound mix rate: \"source\" (the default: the highest rate among the sources, 48 kHz when all are below 44.1 kHz), or 44100, 48000 or 96000 in Hz. Saved with the project; one undo step.", "enum": ["source", 44100, 48000, 96000]}, "proxies": {"type": "boolean", "description": "Play and edit through proxy files."}, "auto_proxies": {"type": "boolean", "description": "Make proxies automatically for heavy sources."}, "encoder": {"type": "string", "enum": ["auto", "hardware", "software"], "description": "Which encoder export uses."}, @@ -665,7 +689,10 @@ fn new_over_autosave_refusal(path: &Path, overwrite: bool) -> Option { } /// `templates`: every template, the built-ins first. -fn templates_list(server: &mut Server, _args: &Value) -> Reply { +fn templates_list(server: &mut Server, args: &Value) -> Reply { + if let Some(spec) = args.get("save") { + return templates_save(server, spec); + } let Some(dir) = server.templates_dir() else { return Reply::err("there is no data folder to keep templates in"); }; @@ -683,6 +710,28 @@ fn templates_list(server: &mut Server, _args: &Value) -> Reply { Reply::ok(text).with(json!({"templates": items})) } +/// `templates {save: {name, with_clips?}}`: the open project saved as a template, the same +/// `engine::templates::save` call File > Save as template makes, with no export preset kept. +fn templates_save(server: &mut Server, spec: &Value) -> Reply { + let Some(name) = opt_str(spec, "name") else { + return Reply::err("templates save needs `name`: 1 to 40 characters, no slashes, not a built-in's name"); + }; + let with_clips = opt_bool(spec, "with_clips").unwrap_or(false); + let Some(dir) = server.templates_dir() else { + return Reply::err("there is no data folder to keep templates in"); + }; + let s = tri!(server.session_ref()); + let clips = with_clips && !s.sources().is_empty(); + match engine::templates::save(&dir, s, name, with_clips, None) { + Ok(replaced) => { + let verb = if replaced { "Replaced" } else { "Saved" }; + let kept = if clips { " with its clips and sources" } else { " (settings only)" }; + Reply::ok(format!("{verb} template {}{kept}", name.trim())).with(json!({"template": name.trim(), "replaced": replaced, "clips": clips})) + } + Err(e) => Reply::err(format!("not saved: {e}")), + } +} + fn project_new(server: &mut Server, args: &Value) -> Reply { let path = tri!(path_arg(args, "path")); let discard = opt_bool(args, "discard").unwrap_or(false); @@ -2059,8 +2108,43 @@ fn caption_json(cs: engine::captionanim::CaptionStyle) -> Value { }) } -fn project_status(server: &mut Server, _args: &Value) -> Reply { - status_reply(server) +fn project_status(server: &mut Server, args: &Value) -> Reply { + if opt_bool(args, "history") != Some(true) { + return status_reply(server); + } + // Trimmed first, as undo trims before it reads the ledger, so the list is the one undo would use. + server.trim_ledger(); + let reply = status_reply(server); + history_reply(server, reply) +} + +/// Adds every undo and redo label to a status reply, each with the `steps` count that reaches it. +fn history_reply(server: &Server, reply: Reply) -> Reply { + let undo: Vec<(usize, String)> = server.ledger.iter().rev().enumerate().map(|(i, e)| (i + 1, e.label.clone())).collect(); + let redo: Vec<(usize, String)> = server.redo_ledger.iter().rev().enumerate().map(|(i, e)| (i + 1, e.label.clone())).collect(); + let mut text = reply.text.clone(); + text.push_str("\nundo history, newest first (undo {steps: N} takes back the N newest):"); + if undo.is_empty() { + text.push_str("\n (none)"); + } + for (n, label) in &undo { + text.push_str(&format!("\n {n}: {label}")); + } + text.push_str("\nredo history, next first (redo {steps: N} brings back the N next):"); + if redo.is_empty() { + text.push_str("\n (none)"); + } + for (n, label) in &redo { + text.push_str(&format!("\n {n}: {label}")); + } + let undo_json: Vec = undo.iter().map(|(n, label)| json!({"steps": n, "label": label})).collect(); + let redo_json: Vec = redo.iter().map(|(n, label)| json!({"steps": n, "label": label})).collect(); + let mut structured = reply.structured.as_deref().cloned().unwrap_or_else(|| json!({})); + if let Some(obj) = structured.as_object_mut() { + obj.insert("undo_history".into(), Value::Array(undo_json)); + obj.insert("redo_history".into(), Value::Array(redo_json)); + } + Reply { text, structured: Some(Box::new(structured)), is_error: reply.is_error, images: reply.images } } fn status_reply(server: &Server) -> Reply { @@ -2273,6 +2357,24 @@ fn on_off(on: bool) -> &'static str { if on { "on" } else { "off" } } +/// `sample_rate`: "source" for no pick (`None`), or one of the rates the GUI offers +/// (`engine::playback::SAMPLE_RATES`), as a number or a numeric string. +fn parse_sample_rate(v: &Value) -> Result, String> { + let offered = || engine::playback::SAMPLE_RATES.iter().map(|r| r.to_string()).collect::>().join(", "); + match v { + Value::String(word) if word == "source" => Ok(None), + Value::Number(n) => match n.as_u64().and_then(|r| u32::try_from(r).ok()) { + Some(r) if engine::playback::SAMPLE_RATES.contains(&r) => Ok(Some(r)), + _ => Err(format!("use source, {}", offered())), + }, + Value::String(word) => match word.parse::() { + Ok(r) if engine::playback::SAMPLE_RATES.contains(&r) => Ok(Some(r)), + _ => Err(format!("`{word}` is not a rate; use source, {}", offered())), + }, + _ => Err(format!("use source, {}", offered())), + } +} + pub(crate) fn project_settings(server: &mut Server, args: &Value) -> Reply { let before = tri!(server.session_ref()).history_pushes(); let force = opt_bool(args, "force").unwrap_or(false); @@ -2445,6 +2547,28 @@ pub(crate) fn project_settings(server: &mut Server, args: &Value) -> Reply { } } + if let Some(v) = args.get("sample_rate") { + asked += 1; + match parse_sample_rate(v) { + Err(why) => { + refused += 1; + lines.push(format!("sample_rate: refused ({why})")); + } + Ok(want) => { + let cur = s.sample_rate(); + let label = |r: Option| r.map_or("source".to_string(), |r| format!("{r} Hz")); + if cur == want { + lines.push(format!("sample rate already {}", label(want))); + } else { + s.set_sample_rate(want); + changed += 1; + named.push(format!("sample rate {}→{}", label(cur), label(want))); + lines.push(format!("sample rate {} -> {}", label(cur), label(want))); + } + } + } + } + if let Some(raw) = opt_str(args, "encoder") { asked += 1; match EncoderSeat::from_name(raw.as_bytes()) { @@ -2958,6 +3082,16 @@ mod tests { assert_eq!(moved_edges(&[0, 30], &[0, 30], 30.0, 30.0), 0); } + /// The sample rate argument takes "source" or one of the rates the GUI offers, and refuses the rest. + #[test] + fn sample_rate_takes_source_or_a_gui_rate() { + assert_eq!(parse_sample_rate(&json!("source")), Ok(None)); + assert_eq!(parse_sample_rate(&json!(48000)), Ok(Some(48_000))); + assert_eq!(parse_sample_rate(&json!("96000")), Ok(Some(96_000))); + assert!(parse_sample_rate(&json!(22050)).is_err()); + assert!(parse_sample_rate(&json!("fast")).is_err()); + } + #[test] fn status_formats_the_duration_once_and_counts_ledger_steps() { quiet(); diff --git a/crates/mcp/src/tools/render.rs b/crates/mcp/src/tools/render.rs index eb5a13e..270dd74 100644 --- a/crates/mcp/src/tools/render.rs +++ b/crates/mcp/src/tools/render.rs @@ -10,7 +10,7 @@ use crate::tools::export::parse_range; pub fn tools() -> Vec { vec![Tool { name: "render_preview", - description: "Pre-render part of the timeline into the render cache, so playback over it reads finished frames instead of compositing them: use it over heavy sections (stacked effects, titles over video, colour, speed, multicam) that drop frames live. `range` is \"all\" (the default, the whole timeline) or {from, to} as export takes it. The render runs in the background; project_status shows its progress and the cached ranges. Any edit inside a cached range drops that render, and playback composes live again there. `cancel: true` stops the render running now and removes its partial file. One render runs at a time. The sound is not rendered: the live mix always plays.", + description: "Pre-render part of the timeline into the render cache, so playback over it reads finished frames instead of compositing them: use it over heavy sections (stacked effects, titles over video, colour, speed, multicam) that drop frames live. `range` is \"all\" (the default, the whole timeline) or {from, to} as export takes it. The render runs in the background; project_status shows its progress and the cached ranges. Any edit inside a cached range drops that render, and playback composes live again there. `cancel: true` stops the render running now and removes its partial file. `clear: true` deletes every cached render file on disk (finished or half written) and says how many went; it is refused while a render is running. One render runs at a time. The sound is not rendered: the live mix always plays.", schema, run: render_preview, }] @@ -25,12 +25,16 @@ fn schema() -> Value { "description": "\"all\" for the whole timeline (the default), or {\"from\": \"