FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Merge transcripts (M10.5) and clip/project commands (M3.10); clip schema renumbered to v10
Brandon Thomase222d025cf57
diff --cc crates/edit/src/through.rsindex d0203355a,000000000..658fcded3mode 100644,000000..100644--- a/crates/edit/src/through.rs+++ b/crates/edit/src/through.rs@@@ -1,263 -1,0 +1,267 @@@+//! Through edits, gaps and range copies.+//!+//! - A **through edit** is a cut between two adjacent pieces of the same source that continue each+//! other in media time (what Add Edit leaves behind). The timeline can mark them (Sequence ▸ Show+//! Through Edits) and Join Through Edits heals them; the left piece's attributes win.+//! - A **gap** is empty time followed by material: on one track, or on every track at once (Sequence+//! ▸ Go to Gap).+//! - [`clip_item_to`] trims a copy of an item to a time range (Make Subsequence).++use filmcraft_project::{ClipId, Sequence, Track, TrackId, TrackItem};+use filmcraft_time::{Tick, TimeRange};++use crate::remove_orphan_transitions;++/// Media-time slack when comparing the pieces of a cut (speed changes round each piece's source+/// range to whole ticks).+const MEDIA_SLACK: i64 = 2;++/// Whether the cut between adjacent items `a` (left) and `b` (right) is a through edit: same+/// source, same speed and direction, and `b` continues `a` in media time.+pub fn is_through_edit(a: &TrackItem, b: &TrackItem) -> bool {+ if a.end() != b.start || a.item != b.item || a.speed != b.speed || a.reverse != b.reverse || a.multicam != b.multicam {+ return false;+ }+ match (a.frame_hold, b.frame_hold) {+ (None, None) => {}+ (Some(x), Some(y)) => return x == y,+ _ => return false,+ }+ let diff = if a.reverse { b.source_out() - a.source_in } else { b.source_in - a.source_out() };+ diff.0.abs() <= MEDIA_SLACK+}++/// One through edit on a track.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct ThroughEdit {+ pub track: TrackId,+ pub left: ClipId,+ pub right: ClipId,+ pub time: Tick,+}++/// Through edits on one track, left to right.+pub fn track_through_edits(track: &Track) -> Vec<ThroughEdit> {+ track+ .items+ .windows(2)+ .filter(|w| is_through_edit(&w[0], &w[1]))+ .map(|w| ThroughEdit { track: track.id, left: w[0].id, right: w[1].id, time: w[1].start })+ .collect()+}++/// Through edits on every video and audio track.+pub fn through_edits(seq: &Sequence) -> Vec<ThroughEdit> {+ seq.all_tracks().flat_map(track_through_edits).collect()+}++/// Join through edits on unlocked tracks. With `only` non-empty, just the edits whose left or right+/// piece is listed. The left piece absorbs the right one (keeping its own effects and attributes);+/// a transition sitting on the cut is removed. Returns the number of edits joined.+pub fn join_through_edits(seq: &mut Sequence, only: &[ClipId]) -> usize {+ let mut n = 0;+ for tr in seq.all_tracks_mut() {+ if tr.locked {+ continue;+ }+ let mut i = 0;+ while i + 1 < tr.items.len() {+ let (a, b) = (&tr.items[i], &tr.items[i + 1]);+ let wanted = only.is_empty() || only.contains(&a.id) || only.contains(&b.id);+ if !(wanted && is_through_edit(a, b)) {+ i += 1;+ continue;+ }+ let (aid, bid) = (a.id, b.id);+ let (dur, b_source_in) = (b.duration, b.source_in);+ let left = &mut tr.items[i];+ left.duration += dur;+ if left.reverse {+ // reversed: the right piece shows the earlier media+ left.source_in = b_source_in;+ }+ tr.items.remove(i + 1);+ tr.transitions.retain(|t| !(t.from == Some(aid) && t.to == Some(bid)));+ for t in &mut tr.transitions {+ if t.from == Some(bid) {+ t.from = Some(aid);+ }+ if t.to == Some(bid) {+ t.to = Some(aid);+ }+ }+ n += 1;+ }+ remove_orphan_transitions(tr);+ }+ n+}++/// Start times of the gaps on one track: empty time from 0 or from the end of an item up to the+/// next item (trailing empty time after the last item is not a gap).+pub fn track_gaps(track: &Track) -> Vec<TimeRange> {+ gaps_of(track.items.iter().map(TrackItem::range))+}++/// Gaps of the whole sequence: time where no video or audio track has material, followed by+/// material.+pub fn sequence_gaps(seq: &Sequence) -> Vec<TimeRange> {+ let mut spans: Vec<TimeRange> = seq.all_tracks().flat_map(|t| t.items.iter().map(TrackItem::range)).collect();+ spans.sort_by_key(|r| r.start);+ gaps_of(spans.into_iter())+}++/// Gaps between `spans` (sorted by start), from time 0.+fn gaps_of(spans: impl Iterator<Item = TimeRange>) -> Vec<TimeRange> {+ let mut out = Vec::new();+ let mut covered = Tick::ZERO;+ for r in spans {+ if r.start > covered {+ out.push(TimeRange::from_bounds(covered, r.start));+ }+ covered = covered.max(r.end());+ }+ out+}++/// A copy of `it` trimmed to the timeline `range` (None when they don't overlap). Media time+/// follows the trim, so the copy shows the same frames at the same timeline times.+pub fn clip_item_to(it: &TrackItem, range: TimeRange) -> Option<TrackItem> {+ let a = it.start.max(range.start);+ let b = it.end().min(range.end());+ if b <= a {+ return None;+ }+ let mut c = it.clone();+ let head = a - it.start;+ let tail = it.end() - b;+ let speed = it.speed.abs();+ let src = |d: Tick| Tick((d.0 as f64 * speed).round() as i64);+ if it.frame_hold.is_none() {+ if it.reverse {+ c.source_in += src(tail);+ } else {+ c.source_in += src(head);+ }+ }+ c.start = a;+ c.duration = b - a;+ Some(c)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{EditCtx, razor};+ use filmcraft_project::{ItemId, Label, SequenceSettings, TrackKind};++ fn item(id: u64, start: i64, dur: i64, src: i64) -> TrackItem {+ TrackItem {+ id: ClipId(id),+ item: ItemId(1),+ name: "c".into(),+ label: Label::Iris,+ start: Tick(start),+ duration: Tick(dur),+ source_in: Tick(src),+ speed: 1.0,+ reverse: false,+ enabled: true,+ link: None,+ group: None,+ effects: vec![],+ markers: vec![],+ gain_db: 0.0,+ frame_hold: None,+ scale_to_frame: false,+ essential: None,+ multicam: None,++ time_interpolation: Default::default(),++ hold_filters: false,++ field_options: None,++ source_channels: Vec::new(),+ }+ }++ fn seq_with(items: Vec<TrackItem>) -> Sequence {+ let mut p = filmcraft_project::Project::new("t");+ let id = p.new_sequence("s", SequenceSettings::default(), 1, 1, None);+ let mut q = p.sequence(id).unwrap().clone();+ q.video_tracks[0].items = items;+ q+ }++ fn ctx(next: &mut u64) -> EditCtx<'_> {+ EditCtx { next_id: next, media_duration: &|_| None, min_duration: Tick(1) }+ }++ #[test]+ fn razor_makes_a_through_edit_and_join_heals_it() {+ let mut q = seq_with(vec![item(10, 0, 100, 500)]);+ let orig = q.clone();+ let mut n = 1000;+ razor(&mut q, &[], Tick(40), &mut ctx(&mut n));+ let te = through_edits(&q);+ assert_eq!(te.len(), 1);+ assert_eq!(te[0].time, Tick(40));+ assert_eq!(join_through_edits(&mut q, &[]), 1);+ assert_eq!(q.video_tracks[0].items, orig.video_tracks[0].items);+ }++ #[test]+ fn reversed_and_speed_changed_pieces_join() {+ for (speed, reverse) in [(1.0, true), (1.5, false), (0.7, true)] {+ let mut it = item(10, 0, 99, 500);+ it.speed = speed;+ it.reverse = reverse;+ let mut q = seq_with(vec![it.clone()]);+ let mut n = 1000;+ razor(&mut q, &[], Tick(37), &mut ctx(&mut n));+ assert_eq!(through_edits(&q).len(), 1, "speed {speed} reverse {reverse}");+ join_through_edits(&mut q, &[]);+ let j = &q.video_tracks[0].items[0];+ assert_eq!((j.start, j.duration), (it.start, it.duration));+ assert!((j.source_in - it.source_in).0.abs() <= MEDIA_SLACK, "speed {speed} reverse {reverse}: {:?} vs {:?}", j.source_in, it.source_in);+ }+ }++ #[test]+ fn discontinuous_neighbours_are_not_through_edits() {+ let q = seq_with(vec![item(10, 0, 40, 500), item(11, 40, 60, 600)]);+ assert!(through_edits(&q).is_empty());+ let mut other = item(11, 40, 60, 540);+ other.item = ItemId(2);+ let q = seq_with(vec![item(10, 0, 40, 500), other]);+ assert!(through_edits(&q).is_empty());+ }++ #[test]+ fn join_only_listed_edits() {+ let mut q = seq_with(vec![item(10, 0, 30, 0), item(11, 30, 30, 30), item(12, 60, 30, 60)]);+ assert_eq!(join_through_edits(&mut q, &[ClipId(12)]), 1);+ assert_eq!(q.video_tracks[0].items.len(), 2);+ assert_eq!(q.video_tracks[0].items[1].duration, Tick(60));+ }++ #[test]+ fn gaps_on_tracks_and_sequence() {+ let mut q = seq_with(vec![item(10, 10, 20, 0), item(11, 50, 10, 0)]);+ q.audio_tracks[0].items = vec![item(20, 0, 15, 0), item(21, 40, 15, 0)];+ assert_eq!(track_gaps(&q.video_tracks[0]), vec![TimeRange::from_bounds(Tick(0), Tick(10)), TimeRange::from_bounds(Tick(30), Tick(50))]);+ assert_eq!(sequence_gaps(&q), vec![TimeRange::from_bounds(Tick(30), Tick(40))]);+ assert_eq!(q.audio_tracks[0].kind, TrackKind::Audio);+ }++ #[test]+ fn clip_to_range_keeps_frames_in_place() {+ let it = item(10, 100, 100, 1000);+ let c = clip_item_to(&it, TimeRange::from_bounds(Tick(120), Tick(150))).unwrap();+ assert_eq!((c.start, c.duration, c.source_in), (Tick(120), Tick(30), Tick(1020)));+ assert_eq!(c.source_time_at(Tick(130)), it.source_time_at(Tick(130)));+ let mut r = it.clone();+ r.reverse = true;+ let c = clip_item_to(&r, TimeRange::from_bounds(Tick(120), Tick(150))).unwrap();+ assert_eq!(c.source_time_at(Tick(130)), r.source_time_at(Tick(130)));+ assert!(clip_item_to(&it, TimeRange::from_bounds(Tick(0), Tick(100))).is_none());+ }+}diff --cc crates/edit/src/transcript/tests.rsindex b44e139e8,000000000..2db93824amode 100644,000000..100644--- a/crates/edit/src/transcript/tests.rs+++ b/crates/edit/src/transcript/tests.rs@@@ -1,292 -1,0 +1,296 @@@+//! Deterministic tests of the transcript → sequence mapping and the text-based edits, on the+//! hand-made interview transcript (`tests/fixtures/interview.transcript.json`, 10 s, two speakers,+//! a 2 s pause after "show.", fillers "Um," and "uh", phrase "you know.").++use super::*;+use filmcraft_project::{Label, Project, SequenceSettings, TrackItem};+use filmcraft_time::FrameRate;++const R: FrameRate = FrameRate { num: 25, den: 1 };+const MEDIA: ItemId = ItemId(1);++fn s(x: f64) -> Tick {+ Tick((x * TICKS_PER_SECOND as f64).round() as i64)+}++fn fixture() -> Transcript {+ let mut t: Transcript = serde_json::from_str(include_str!("../../tests/fixtures/interview.transcript.json")).unwrap();+ t.normalize();+ t.check().unwrap();+ t+}++fn transcripts() -> Transcripts {+ let mut m = Transcripts::new();+ m.insert(MEDIA, Arc::new(fixture()));+ m+}++fn seq() -> Sequence {+ let mut p = Project::new("t");+ let id = p.new_sequence("s", SequenceSettings { frame_rate: R, ..Default::default() }, 1, 2, None);+ p.sequence(id).unwrap().clone()+}++fn clip(id: u64, start: f64, dur: f64, src_in: f64) -> TrackItem {+ TrackItem {+ id: ClipId(id),+ item: MEDIA,+ name: "interview".into(),+ label: Label::Iris,+ start: s(start),+ duration: s(dur),+ source_in: s(src_in),+ speed: 1.0,+ reverse: false,+ enabled: true,+ link: None,+ group: None,+ effects: vec![],+ markers: vec![],+ gain_db: 0.0,+ frame_hold: None,+ scale_to_frame: false,+ essential: None,+ multicam: None,++ time_interpolation: Default::default(),++ hold_filters: false,++ field_options: None,++ source_channels: Vec::new(),+ }+}++fn texts(w: &[SeqWord]) -> Vec<&str> {+ w.iter().map(|w| w.text.as_str()).collect()+}++fn media_dur(_: ItemId) -> Option<Tick> {+ Some(s(10.0))+}++fn whole() -> Sequence {+ let mut q = seq();+ q.audio_tracks[0].items.push(clip(100, 0.0, 10.0, 0.0));+ q+}++#[test]+fn words_map_through_the_clip() {+ let mut q = seq();+ // media 3.5 s – 6.5 s at timeline 2 s+ q.audio_tracks[0].items.push(clip(100, 2.0, 3.0, 3.5));+ let w = sequence_words(&q, &transcripts());+ assert_eq!(texts(&w), ["Um,", "today", "we", "talk", "about", "rivers."]);+ assert_eq!(w[0].start, s(2.2));+ assert_eq!(w[0].end, s(2.5));+ assert_eq!(w[5].end, s(4.4));+ assert!(w.iter().all(|x| x.clip == ClipId(100) && x.item == MEDIA && x.track == 0));+ assert_eq!(w[0].index, 4);+ assert_eq!(w[0].speaker.as_deref(), Some("Speaker 1"));+}++#[test]+fn a_cut_word_is_kept_by_its_midpoint_and_clamped() {+ let mut q = seq();+ // cut inside "show." (1.20–1.70, midpoint 1.45): the clip starts at media 1.4+ q.audio_tracks[0].items.push(clip(100, 0.0, 1.0, 1.4));+ let w = sequence_words(&q, &transcripts());+ assert_eq!(texts(&w), ["show."]);+ assert_eq!(w[0].start, Tick::ZERO);+ assert_eq!(w[0].end, s(0.3));+}++#[test]+fn speed_scales_word_times() {+ let mut q = seq();+ let mut c = clip(100, 0.0, 5.0, 0.0);+ c.speed = 2.0;+ q.audio_tracks[0].items.push(c);+ let w = sequence_words(&q, &transcripts());+ assert_eq!(w.len(), 20);+ assert_eq!((w[3].start, w[3].end), (s(0.6), s(0.85)));+}++#[test]+fn duplicate_tracks_read_once_and_disabled_or_reversed_clips_are_silent() {+ let mut q = whole();+ q.audio_tracks[1].items.push(clip(101, 0.0, 10.0, 0.0));+ let w = sequence_words(&q, &transcripts());+ assert_eq!(w.len(), 20);+ assert!(w.iter().all(|x| x.track == 0));+ q.audio_tracks[0].items[0].enabled = false;+ let w = sequence_words(&q, &transcripts());+ assert_eq!(w.len(), 20);+ assert!(w.iter().all(|x| x.track == 1));+ q.audio_tracks[1].items[0].reverse = true;+ assert!(sequence_words(&q, &transcripts()).is_empty());+}++#[test]+fn two_clips_of_the_same_media_repeat_words_in_edit_order() {+ let mut q = seq();+ // "rivers." twice: media 5.3–5.9 at 0 s and again at 1 s+ q.audio_tracks[0].items.push(clip(100, 0.0, 1.0, 5.2));+ q.audio_tracks[0].items.push(clip(101, 1.0, 1.0, 5.2));+ let w = sequence_words(&q, &transcripts());+ assert_eq!(texts(&w), ["rivers.", "rivers."]);+ assert_eq!(w[1].start, s(1.1));+ assert_eq!(w[1].clip, ClipId(101));+}++#[test]+fn search_word_at_and_paragraphs() {+ let w = sequence_words(&whole(), &transcripts());+ assert_eq!(search(&w, "rivers"), vec![9..10, 17..18]);+ assert_eq!(search(&w, "YOU kn"), vec![18..20]);+ assert_eq!(search(&w, "talk about"), vec![7..9]);+ assert!(search(&w, " ").is_empty());+ assert_eq!(word_at(&w, s(4.2)), Some(5));+ assert_eq!(word_at(&w, s(2.5)), None); // in the pause+ assert_eq!(word_at(&w, s(0.1)), None);+ // pause ≥ 1.5 s after "show.", speaker change before "Thanks"+ assert_eq!(paragraphs(&w, s(1.5)), vec![0..4, 4..10, 10..20]);+}++#[test]+fn word_ranges_snap_outward() {+ let w = sequence_words(&whole(), &transcripts());+ // "Welcome to the show." 0.50–1.70 → frames 12..43 (0.48–1.72)+ let r = word_range(&w, 3, 0, R).unwrap();+ assert_eq!((r.start, r.end()), (s(0.48), s(1.72)));+ let m = media_word_range(&fixture(), 4, 9, R).unwrap();+ assert_eq!((m.start, m.end()), (s(3.68), s(5.92)));+ assert!(word_range(&w, 0, 99, R).is_none());+}++#[test]+fn extract_text_closes_the_gap() {+ let mut q = whole();+ let w = sequence_words(&q, &transcripts());+ let r = word_range(&w, 0, 3, R).unwrap();+ let mut next = 1000;+ let mut ctx = EditCtx { next_id: &mut next, media_duration: &media_dur, min_duration: R.frame_duration() };+ let tracks: Vec<TrackId> = q.all_tracks().map(|t| t.id).collect();+ crate::extract(&mut q, &tracks, r, &mut ctx);+ q.check().unwrap();+ let w2 = sequence_words(&q, &transcripts());+ assert_eq!(w2.len(), 16);+ assert_eq!(w2[0].text, "Um,");+ assert_eq!(w2[0].start, s(3.70) - r.duration);+}++#[test]+fn pauses_are_found_and_removed_in_one_pass() {+ let mut q = whole();+ let w = sequence_words(&q, &transcripts());+ // only the 2 s pause after "show." is ≥ 1 s; 0.1 s is kept on each side+ let p = find_pauses(&w, s(1.0), s(0.1), R);+ assert_eq!(p.len(), 1);+ assert_eq!((p[0].start, p[0].end()), (s(1.80), s(3.60)));+ // 0.4 s threshold also finds 5.90→6.40 and 7.60→8.00+ let p2 = find_pauses(&w, s(0.4), s(0.1), R);+ assert_eq!(p2.len(), 3);+ let mut next = 1000;+ let mut ctx = EditCtx { next_id: &mut next, media_duration: &media_dur, min_duration: R.frame_duration() };+ let removed = ripple_delete_ranges(&mut q, p2.clone(), &mut ctx);+ q.check().unwrap();+ assert_eq!(removed, p2.iter().map(|r| r.duration).fold(Tick::ZERO, |a, b| a + b));+ let w2 = sequence_words(&q, &transcripts());+ assert_eq!(texts(&w2), texts(&w));+ // the long pause is now 0.2 s+ assert_eq!(w2[4].start - w2[3].end, s(0.2));+ assert_eq!(w2.last().unwrap().end, s(10.0) - removed);+ assert!(find_pauses(&w2, s(0.4), s(0.1), R).is_empty());+}++#[test]+fn fillers_are_found_with_phrases_and_removed() {+ let mut q = whole();+ let w = sequence_words(&q, &transcripts());+ let defaults: Vec<String> = DEFAULT_FILLERS.iter().map(|x| x.to_string()).collect();+ let hits = find_fillers(&w, &defaults);+ assert_eq!(hits, vec![4..5, 15..16]);+ let mut more = defaults.clone();+ more.push("You know".into());+ more.push("you".into());+ assert_eq!(find_fillers(&w, &more), vec![4..5, 15..16, 18..20]);+ let ranges = filler_ranges(&w, &hits, R);+ // "Um," 3.70–4.00 → nearest frames 3.68–4.00; "uh" 8.20–8.50 → 8.20–8.48+ assert_eq!(ranges.iter().map(|r| (r.start, r.end())).collect::<Vec<_>>(), vec![(s(3.68), s(4.00)), (s(8.20), s(8.48))]);+ let mut next = 1000;+ let mut ctx = EditCtx { next_id: &mut next, media_duration: &media_dur, min_duration: R.frame_duration() };+ ripple_delete_ranges(&mut q, ranges, &mut ctx);+ q.check().unwrap();+ let w2 = sequence_words(&q, &transcripts());+ assert_eq!(w2.len(), 18);+ assert!(find_fillers(&w2, &defaults).is_empty());+ assert_eq!(q.audio_tracks[0].items.len(), 3);+}++#[test]+fn merge_ranges_joins_overlaps() {+ let r = |a: f64, b: f64| TimeRange::from_bounds(s(a), s(b));+ let m = merge_ranges(vec![r(5.0, 6.0), r(1.0, 2.0), r(1.5, 3.0), r(3.0, 4.0)]);+ assert_eq!(m, vec![r(1.0, 4.0), r(5.0, 6.0)]);+}++fn check_blocks(b: &[CaptionBlock], rules: &CaptionRules) {+ for (i, x) in b.iter().enumerate() {+ assert!(x.end > x.start, "{x:?}");+ assert_eq!(R.snap(x.start), x.start);+ assert_eq!(R.snap(x.end), x.end);+ let lines: Vec<&str> = x.text.lines().collect();+ assert!(lines.len() <= rules.lines, "{x:?}");+ assert!(lines.iter().all(|l| l.chars().count() <= rules.max_chars), "{x:?}");+ if i > 0 {+ assert!(x.start >= b[i - 1].end + Tick(R.frame_duration().0 * rules.gap_frames), "{:?} overlaps {:?}", b[i - 1], x);+ }+ }+}++#[test]+fn captions_follow_line_length_speaker_and_pause_rules() {+ let w = sequence_words(&whole(), &transcripts());+ let rules = CaptionRules::default();+ let b = caption_blocks(&w, &rules, R);+ check_blocks(&b, &rules);+ assert_eq!(+ b.iter().map(|x| x.text.as_str()).collect::<Vec<_>>(),+ ["Welcome to the show.", "Um, today we talk about rivers.", "Thanks for having me. I uh love rivers,\nyou know."]+ );+ assert_eq!((b[0].start, b[0].end), (s(0.48), s(1.72)));+ assert_eq!(b[2].speaker.as_deref(), Some("Speaker 2"));+ assert_eq!(b[2].words, 10..20);++ // single 20-character lines, two-frame gaps, 3 s minimum+ let tight = CaptionRules { max_chars: 20, lines: 1, gap_frames: 2, min_duration: s(3.0), ..Default::default() };+ let b = caption_blocks(&w, &tight, R);+ check_blocks(&b, &tight);+ assert!(b.len() >= 5);+ // the first block is extended to 3 s (room before "Um,")+ assert_eq!(b[0].end - b[0].start, s(3.0));+ // every word is shown exactly once, in order+ let all: Vec<usize> = b.iter().flat_map(|x| x.words.clone()).collect();+ assert_eq!(all, (0..20).collect::<Vec<_>>());+}++#[test]+fn captions_never_overlap_with_dense_words() {+ // 30 one-frame words back to back+ let words: Vec<SeqWord> = (0..30)+ .map(|i| SeqWord {+ text: format!("w{i}."),+ start: R.tick_of(i),+ end: R.tick_of(i + 1),+ clip: ClipId(1),+ item: MEDIA,+ index: i as usize,+ track: 0,+ speaker: if i % 3 == 0 { Some("A".into()) } else { Some("B".into()) },+ confidence: 1.0,+ })+ .collect();+ let rules = CaptionRules { gap_frames: 1, ..Default::default() };+ let b = caption_blocks(&words, &rules, R);+ check_blocks(&b, &rules);+}diff --cc crates/engine/src/clip_ops.rsindex 000000000,1420f3bc5..2ce26488amode 000000,100644..100644--- a/crates/engine/src/clip_ops.rs+++ b/crates/engine/src/clip_ops.rs@@@ -1,0 -1,1619 +1,1619 @@@+ //! Edit / Clip / File menu commands for project items and clips (M3.10): labels and Select Label+ //! Group, Paste / Remove Attributes, Select All Matching, Remove Unused, Consolidate Duplicates,+ //! Sequence From Clip, Bin From Selection, Offline File, Close Project, Save All, Make / Edit+ //! Subclip, Modify ▸ Audio Channels / Timecode, Video Options (Frame Hold Options, Add Frame Hold,+ //! Insert Frame Hold Segment, Field Options, Time Interpolation, Fit / Fill frame), Audio Options+ //! (Breakout to Mono, Extract Audio) and Replace With Clip.+ //!+ //! Every command mutates through `Session::edit` / `edit_sequence`, so it is one undo step.+ //! [`apply_layout`] places these commands (and a few existing ones) in Premiere's menu order.++ use std::collections::{BTreeMap, BTreeSet};++ use filmcraft_edit as edit;+ use filmcraft_project::{+ AudioChannelMap, AudioChannels, BinEntry, ClipId, FieldOptions, FieldProcessing, ItemId, ItemKind, Label, MediaClip, MediaRef, ParamValue, Project,+ TimeInterpolation, TrackItem, TrackKind,+ };+ use filmcraft_time::{FrameRate, TICKS_PER_SECOND, Tick, TimeRange, parse_timecode};+ use serde_json::{Value, json};++ use crate::commands::{+ CommandSpec, always, bad, bool_p, clips_p, f64_p, has_project_selection, has_selection, has_seq, item_p, place_item, source_range, str_p, time_p, u64_p,+ with_links,+ };+ use crate::{EngineError, Result, Session};++ type Run = fn(&mut Session, &Value) -> Result<Value>;+ type Enabled = fn(&Session) -> std::result::Result<(), String>;++ fn spec(+ id: &'static str,+ label: &'static str,+ menu: &'static [&'static str],+ shortcut: Option<&'static str>,+ params: &'static str,+ enabled: Enabled,+ run: Run,+ ) -> CommandSpec {+ CommandSpec { id, label, menu, shortcut, params, enabled, run, journal: true }+ }++ macro_rules! label_cmd {+ ($id:literal, $name:literal, $l:expr) => {+ CommandSpec {+ id: $id,+ label: $name,+ menu: &["Edit", "Label"],+ shortcut: None,+ params: r#"{"items":[id]?,"clips":[id]?}"#,+ enabled: can_label,+ run: |s, p| apply_label(s, p, $l),+ journal: true,+ }+ };+ }++ /// The new commands.+ pub(crate) fn commands() -> Vec<CommandSpec> {+ vec![+ // ---------------- File ----------------+ spec("file.newSequenceFromClip", "Sequence From Clip", &["File", "New"], None, r#"{"items":[id]?}"#, has_clip_items, sequence_from_clip),+ spec(+ "file.newBinFromSelection",+ "Bin From Selection",+ &["File", "New"],+ Some("Shift+B"),+ r#"{"items":[id]?,"name":str?}"#,+ has_project_selection,+ bin_from_selection,+ ),+ spec(+ "file.newOfflineFile",+ "Offline File…",+ &["File", "New"],+ None,+ r#"{"name":str?,"fileName":str?,"tapeName":str?,"video":bool=true,"audio":bool=true,"width":u32?,"height":u32?,"fps":f64?,"sampleRate":u32=48000,"channels":u32=2,"timecode":"HH:MM:SS:FF"?,"seconds":f64=10,"description":str?}"#,+ always,+ offline_file,+ ),+ spec("file.closeProject", "Close Project", &["File"], Some("Cmd+Shift+W"), r#"{"force":bool?}"#, always, close_project),+ spec("file.saveAll", "Save All", &["File"], None, "{}", always, |s, _| s.execute("file.save", json!({}))),+ // ---------------- Edit ----------------+ spec(+ "edit.pasteAttributes",+ "Paste Attributes…",+ &["Edit"],+ Some("Cmd+Alt+V"),+ r#"{"clips":[id]?,"motion":bool=true,"opacity":bool=true,"timeRemapping":bool=true,"volume":bool=true,"channelVolume":bool=true,"panner":bool=true,"effects":bool|[effectId]=true,"scaleTimes":bool=true}"#,+ can_paste_attributes,+ paste_attributes,+ ),+ spec(+ "edit.removeAttributes",+ "Remove Attributes…",+ &["Edit"],+ None,+ r#"{"clips":[id]?,"motion":bool=true,"opacity":bool=true,"timeRemapping":bool=true,"volume":bool=true,"channelVolume":bool=true,"panner":bool=true,"effects":bool|[effectId]=true}"#,+ has_selection,+ remove_attributes,+ ),+ spec("edit.selectAllMatching", "Select All Matching", &["Edit"], None, r#"{"clips":[id]?}"#, has_selection, select_all_matching),+ spec("edit.selectLabelGroup", "Select Label Group", &["Edit", "Label"], None, "{}", can_label, select_label_group),+ label_cmd!("edit.label.violet", "Violet", Label::Violet),+ label_cmd!("edit.label.iris", "Iris", Label::Iris),+ label_cmd!("edit.label.caribbean", "Caribbean", Label::Caribbean),+ label_cmd!("edit.label.lavender", "Lavender", Label::Lavender),+ label_cmd!("edit.label.cerulean", "Cerulean", Label::Cerulean),+ label_cmd!("edit.label.forest", "Forest", Label::Forest),+ label_cmd!("edit.label.rose", "Rose", Label::Rose),+ label_cmd!("edit.label.mango", "Mango", Label::Mango),+ label_cmd!("edit.label.purple", "Purple", Label::Purple),+ label_cmd!("edit.label.blue", "Blue", Label::Blue),+ label_cmd!("edit.label.teal", "Teal", Label::Teal),+ label_cmd!("edit.label.magenta", "Magenta", Label::Magenta),+ label_cmd!("edit.label.tan", "Tan", Label::Tan),+ label_cmd!("edit.label.green", "Green", Label::Green),+ label_cmd!("edit.label.brown", "Brown", Label::Brown),+ label_cmd!("edit.label.yellow", "Yellow", Label::Yellow),+ spec("edit.removeUnused", "Remove Unused", &["Edit"], None, "{}", has_project_items, remove_unused),+ spec("edit.consolidateDuplicates", "Consolidate Duplicates", &["Edit"], None, "{}", has_project_items, consolidate_duplicates),+ // ---------------- Clip ----------------+ spec(+ "clip.makeSubclip",+ "Make Subclip…",+ &["Clip"],+ Some("Cmd+U"),+ r#"{"item":id?,"clip":id?,"name":str?,"start":ticks?,"end":ticks?,"startFrame":i64?,"endFrame":i64?,"restrictTrims":bool=true}"#,+ can_make_subclip,+ make_subclip,+ ),+ spec(+ "clip.editSubclip",+ "Edit Subclip…",+ &["Clip"],+ None,+ r#"{"item":id?,"start":ticks?,"end":ticks?,"startFrame":i64?,"endFrame":i64?,"restrictTrims":bool?,"convertToMaster":bool?}"#,+ has_subclip,+ edit_subclip,+ ),+ spec(+ "clip.audioChannels",+ "Audio Channels…",+ &["Clip", "Modify"],+ Some("Shift+G"),+ r#"{"items":[id]?,"format":"mono|stereo|5.1|adaptive","clips":[[channel]]?,"channels":[channel]?}"#,+ has_audio_target,+ audio_channels,+ ),+ spec(+ "clip.modifyTimecode",+ "Timecode…",+ &["Clip", "Modify"],+ None,+ r#"{"item":id?,"timecode":"HH:MM:SS:FF"?,"frame":i64?,"tapeName":str?,"reset":bool?}"#,+ has_media_selection,+ modify_timecode,+ ),+ spec(+ "clip.frameHoldOptions",+ "Frame Hold Options…",+ &["Clip", "Video Options"],+ None,+ r#"{"clips":[id]?,"enabled":bool=true,"holdOn":"sourceTimecode|sequenceTime|in|out|playhead","time":ticks?,"timecode":str?,"holdFilters":bool=false}"#,+ has_selection,+ frame_hold_options,+ ),+ spec(+ "clip.insertFrameHoldSegment",+ "Insert Frame Hold Segment",+ &["Clip", "Video Options"],+ None,+ r#"{"clip":id?,"time":ticks?,"seconds":f64=2}"#,+ has_seq,+ insert_frame_hold_segment,+ ),+ spec(+ "clip.fieldOptions",+ "Field Options…",+ &["Clip", "Video Options"],+ None,+ r#"{"clips":[id]?,"reverseFieldDominance":bool=false,"processing":"none|alwaysDeinterlace|flickerRemoval"}"#,+ has_selection,+ field_options,+ ),+ spec(+ "clip.timeInterpolation.frameSampling",+ "Frame Sampling",+ &["Clip", "Video Options", "Time Interpolation"],+ None,+ r#"{"clips":[id]?}"#,+ has_selection,+ |s, p| set_interpolation(s, p, TimeInterpolation::FrameSampling),+ ),+ spec(+ "clip.timeInterpolation.frameBlending",+ "Frame Blending",+ &["Clip", "Video Options", "Time Interpolation"],+ None,+ r#"{"clips":[id]?}"#,+ has_selection,+ |s, p| set_interpolation(s, p, TimeInterpolation::FrameBlending),+ ),+ spec(+ "clip.timeInterpolation.opticalFlow",+ "Optical Flow",+ &["Clip", "Video Options", "Time Interpolation"],+ None,+ r#"{"clips":[id]?}"#,+ has_selection,+ |s, p| set_interpolation(s, p, TimeInterpolation::OpticalFlow),+ ),+ spec(+ "clip.setTimeInterpolation",+ "Set Time Interpolation",+ &[],+ None,+ r#"{"clips":[id]?,"mode":"frameSampling|frameBlending|opticalFlow"}"#,+ has_selection,+ |s, p| {+ let m = str_p(p, "mode").and_then(TimeInterpolation::from_name).ok_or_else(|| bad("clip.setTimeInterpolation", "need `mode`"))?;+ set_interpolation(s, p, m)+ },+ ),+ spec("clip.fitToFrame", "Fit to frame", &["Clip", "Video Options"], None, r#"{"clips":[id]?}"#, has_selection, |s, p| fit_fill(s, p, false)),+ spec("clip.fillFrame", "Fill frame", &["Clip", "Video Options"], None, r#"{"clips":[id]?}"#, has_selection, |s, p| fit_fill(s, p, true)),+ spec("clip.breakoutToMono", "Breakout to Mono", &["Clip", "Audio Options"], None, r#"{"items":[id]?}"#, has_audio_items, breakout_to_mono),+ spec("clip.extractAudio", "Extract Audio", &["Clip", "Audio Options"], None, r#"{"items":[id]?,"dir":str?}"#, has_extractable, extract_audio),+ spec("clip.replaceFromSource", "From Source Monitor", &["Clip", "Replace With Clip"], None, r#"{"clips":[id]?}"#, can_replace_from_source, |s, p| {+ replace_with(s, p, Replace::Source)+ }),+ spec(+ "clip.replaceFromSourceMatchFrame",+ "From Source Monitor, Match Frame",+ &["Clip", "Replace With Clip"],+ None,+ r#"{"clips":[id]?}"#,+ can_replace_from_source,+ |s, p| replace_with(s, p, Replace::MatchFrame),+ ),+ spec("clip.replaceFromBin", "From Bin", &["Clip", "Replace With Clip"], None, r#"{"clips":[id]?,"item":id?}"#, can_replace_from_bin, |s, p| {+ replace_with(s, p, Replace::Bin)+ }),+ ]+ }++ /// Where a run of commands goes in the menus (the registry order is the menu order).+ enum At {+ After(&'static str),+ Before(&'static str),+ }++ const LABEL_IDS: [&str; 16] = [+ "edit.label.violet",+ "edit.label.iris",+ "edit.label.caribbean",+ "edit.label.lavender",+ "edit.label.cerulean",+ "edit.label.forest",+ "edit.label.rose",+ "edit.label.mango",+ "edit.label.purple",+ "edit.label.blue",+ "edit.label.teal",+ "edit.label.magenta",+ "edit.label.tan",+ "edit.label.green",+ "edit.label.brown",+ "edit.label.yellow",+ ];++ /// Add [`commands`] to the registry and arrange the File / Edit / Clip menus in Premiere's order+ /// (moving a few existing commands into their submenus' order too).+ pub(crate) fn apply_layout(v: &mut Vec<CommandSpec>) {+ let mut pool = commands();+ let mut edit_tail: Vec<&'static str> = vec!["edit.selectLabelGroup"];+ edit_tail.extend(LABEL_IDS);+ edit_tail.extend(["edit.removeUnused", "edit.consolidateDuplicates"]);+ let layout: Vec<(At, Vec<&'static str>)> = vec![+ (At::After("file.newSequence"), vec!["file.newSequenceFromClip"]),+ (At::After("file.newBin"), vec!["file.newBinFromSelection", "file.newOfflineFile"]),+ (At::Before("file.save"), vec!["file.closeProject"]),+ (At::After("file.saveCopy"), vec!["file.saveAll"]),+ (At::After("edit.pasteInsert"), vec!["edit.pasteAttributes", "edit.removeAttributes"]),+ (At::After("edit.selectAll"), vec!["edit.selectAllMatching"]),+ (At::After("edit.duplicate"), edit_tail),+ (+ At::After("clip.rename"),+ vec![+ "clip.makeSubclip",+ "clip.editSubclip",+ "clip.audioChannels",+ "clip.interpretFootage",+ "clip.modifyTimecode",+ "clip.frameHoldOptions",+ "clip.frameHold",+ "clip.insertFrameHoldSegment",+ "clip.fieldOptions",+ "clip.timeInterpolation.frameSampling",+ "clip.timeInterpolation.frameBlending",+ "clip.timeInterpolation.opticalFlow",+ "clip.scaleToFrameSize",+ "clip.fitToFrame",+ "clip.fillFrame",+ "clip.audioGain",+ "clip.breakoutToMono",+ "clip.extractAudio",+ ],+ ),+ (At::After("source.overwrite"), vec!["clip.replaceFromSource", "clip.replaceFromSourceMatchFrame", "clip.replaceFromBin"]),+ ];+ for (at, ids) in layout {+ let mut run = Vec::new();+ for id in ids {+ if let Some(i) = v.iter().position(|c| c.id == id) {+ run.push(v.remove(i));+ } else if let Some(i) = pool.iter().position(|c| c.id == id) {+ run.push(pool.remove(i));+ }+ }+ let idx = match at {+ At::After(a) => v.iter().position(|c| c.id == a).map(|i| i + 1),+ At::Before(b) => v.iter().position(|c| c.id == b),+ }+ .unwrap_or(v.len());+ v.splice(idx..idx, run);+ }+ v.extend(pool);+ }++ // ---------------------------------------------------------------------------------------------+ // enablement+ // ---------------------------------------------------------------------------------------------++ fn can_label(s: &Session) -> std::result::Result<(), String> {+ if s.state.selection.is_empty() && s.state.project_selection.is_empty() { Err("select clips or project items".into()) } else { Ok(()) }+ }+ fn has_project_items(s: &Session) -> std::result::Result<(), String> {+ if s.project.items.values().any(|i| !matches!(i.kind, ItemKind::Graphic { .. })) { Ok(()) } else { Err("the project is empty".into()) }+ }+ fn is_clip_item(p: &Project, id: ItemId) -> bool {+ p.item(id).is_some_and(|i| matches!(i.kind, ItemKind::Media(_) | ItemKind::Subclip { .. } | ItemKind::Sequence(_) | ItemKind::AdjustmentLayer { .. }))+ }+ fn has_clip_items(s: &Session) -> std::result::Result<(), String> {+ if s.state.project_selection.iter().any(|i| is_clip_item(&s.project, *i)) { Ok(()) } else { Err("select a clip in the Project panel".into()) }+ }+ fn can_paste_attributes(s: &Session) -> std::result::Result<(), String> {+ has_selection(s)?;+ if s.state.clipboard.is_empty() { Err("copy a clip first".into()) } else { Ok(()) }+ }+ fn subclip_source(s: &Session) -> Option<ItemId> {+ s.state+ .source_item+ .filter(|i| media_root(&s.project, *i).is_some())+ .or_else(|| s.state.project_selection.iter().copied().find(|i| media_root(&s.project, *i).is_some()))+ }+ fn can_make_subclip(s: &Session) -> std::result::Result<(), String> {+ if subclip_source(s).is_some() || !s.state.selection.is_empty() { Ok(()) } else { Err("open a clip in the Source monitor or select one".into()) }+ }+ fn has_subclip(s: &Session) -> std::result::Result<(), String> {+ if s.state.project_selection.iter().any(|i| s.project.item(*i).is_some_and(|it| matches!(it.kind, ItemKind::Subclip { .. }))) {+ Ok(())+ } else {+ Err("select a subclip in the Project panel".into())+ }+ }+ fn has_media_selection(s: &Session) -> std::result::Result<(), String> {+ if s.state.project_selection.iter().any(|i| s.project.item(*i).and_then(|it| it.as_media()).is_some()) {+ Ok(())+ } else {+ Err("select a clip in the Project panel".into())+ }+ }+ fn audio_items(s: &Session) -> Vec<ItemId> {+ s.state.project_selection.iter().copied().filter(|i| s.project.item(*i).and_then(|it| it.as_media()).is_some_and(|m| m.info.has_audio())).collect()+ }+ fn has_audio_items(s: &Session) -> std::result::Result<(), String> {+ if audio_items(s).is_empty() { Err("select a clip with audio in the Project panel".into()) } else { Ok(()) }+ }+ fn selected_audio_clips(s: &Session) -> Vec<ClipId> {+ let Some(q) = s.active_sequence() else { return Vec::new() };+ s.state.selection.iter().copied().filter(|c| q.audio_tracks.iter().any(|t| t.item(*c).is_some())).collect()+ }+ fn has_audio_target(s: &Session) -> std::result::Result<(), String> {+ if audio_items(s).is_empty() && selected_audio_clips(s).is_empty() { Err("select a clip with audio".into()) } else { Ok(()) }+ }+ fn extract_items(s: &Session) -> Vec<ItemId> {+ let mut out: Vec<ItemId> = s.state.project_selection.clone();+ if out.is_empty()+ && let Some(q) = s.active_sequence()+ {+ for c in &s.state.selection {+ if let Some((_, i)) = q.find_item(*c)+ && !out.contains(&i.item)+ {+ out.push(i.item);+ }+ }+ }+ out.retain(|i| media_root(&s.project, *i).is_some_and(|(_, m, _)| m.info.has_audio()));+ out+ }+ fn has_extractable(s: &Session) -> std::result::Result<(), String> {+ if extract_items(s).is_empty() { Err("select a clip with audio".into()) } else { Ok(()) }+ }+ fn can_replace_from_source(s: &Session) -> std::result::Result<(), String> {+ has_selection(s)?;+ s.state.source_item.map(|_| ()).ok_or_else(|| "open a clip in the Source monitor".into())+ }+ fn can_replace_from_bin(s: &Session) -> std::result::Result<(), String> {+ has_selection(s)?;+ if s.state.project_selection.iter().any(|i| is_clip_item(&s.project, *i)) { Ok(()) } else { Err("select a clip in the Project panel".into()) }+ }++ // ---------------------------------------------------------------------------------------------+ // helpers+ // ---------------------------------------------------------------------------------------------++ /// The media item behind `id` (subclips resolve to their parent) and the subclip range.+ fn media_root(p: &Project, id: ItemId) -> Option<(ItemId, &MediaClip, Option<TimeRange>)> {+ match &p.item(id)?.kind {+ ItemKind::Media(m) => Some((id, m, None)),+ ItemKind::Subclip { parent, range, .. } => media_root(p, *parent).map(|(i, m, _)| (i, m, Some(*range))),+ _ => None,+ }+ }++ /// Frame rate of an item, resolving subclips to their media.+ fn item_rate(p: &Project, id: ItemId) -> FrameRate {+ match media_root(p, id) {+ Some((_, m, _)) => m.frame_rate(),+ None => p.item(id).map(|i| i.frame_rate()).unwrap_or_default(),+ }+ }++ fn items_p(s: &Session, p: &Value) -> Vec<ItemId> {+ match p.get("items").and_then(Value::as_array) {+ Some(a) => a.iter().filter_map(|v| v.as_u64().map(ItemId)).collect(),+ None => item_p(p, "item").map(|i| vec![i]).unwrap_or_else(|| s.state.project_selection.clone()),+ }+ }++ /// Fold the undo steps pushed since the history had `n0` entries into one step named `label`.+ fn collapse_history(s: &mut Session, n0: usize, label: &str) {+ if s.history.undo.len() > n0 {+ let first = s.history.undo[n0].1.clone();+ s.history.undo.truncate(n0);+ s.history.undo.push((label.to_string(), first));+ }+ }++ /// Every item referenced by a clip in any sequence (subclips pull in their parents, nested+ /// sequences count as used).+ fn used_items(p: &Project) -> BTreeSet<ItemId> {+ let mut used = BTreeSet::new();+ for it in p.items.values() {+ if let ItemKind::Sequence(q) = &it.kind {+ for t in q.all_tracks() {+ for i in &t.items {+ used.insert(i.item);+ }+ }+ if let Some(m) = &q.merged {+ let v = serde_json::to_value(m).unwrap_or_default();+ collect_ids(&v, &mut used, p);+ }+ }+ }+ // subclip parents of anything kept+ let mut changed = true;+ while changed {+ changed = false;+ for it in p.items.values() {+ if let ItemKind::Subclip { parent, .. } = it.kind+ && (used.contains(&it.id) || !is_removable(p, it.id))+ && used.insert(parent)+ {+ changed = true;+ }+ }+ }+ used+ }++ /// Item ids mentioned in a JSON value (keys named `item`/`items`/`video`/`audio` holding ids).+ fn collect_ids(v: &Value, out: &mut BTreeSet<ItemId>, p: &Project) {+ match v {+ Value::Object(m) => {+ for (k, x) in m {+ if matches!(k.as_str(), "item" | "items" | "video" | "audio") {+ for n in x.as_array().cloned().unwrap_or_else(|| vec![x.clone()]) {+ if let Some(id) = n.as_u64().map(ItemId).filter(|i| p.items.contains_key(i)) {+ out.insert(id);+ }+ }+ }+ collect_ids(x, out, p);+ }+ }+ Value::Array(a) => a.iter().for_each(|x| collect_ids(x, out, p)),+ _ => {}+ }+ }++ /// Remove Unused removes clips only: never sequences or graphic sources.+ fn is_removable(p: &Project, id: ItemId) -> bool {+ p.item(id).is_some_and(|i| matches!(i.kind, ItemKind::Media(_) | ItemKind::Subclip { .. } | ItemKind::AdjustmentLayer { .. }))+ }++ fn remove_items(p: &mut Project, ids: &[ItemId]) {+ for i in ids {+ p.items.remove(i);+ p.root.remove_item(*i);+ }+ }++ /// Keyframe times of an effect instance shifted / scaled from clip `from` to clip `to` (media time).+ fn retime_effect(e: &mut filmcraft_project::EffectInstance, from: &TrackItem, to: &TrackItem, scale: bool) {+ let (f0, f1) = (from.source_in, from.source_out());+ let (t0, t1) = (to.source_in, to.source_out());+ let map = |k: Tick| -> Tick {+ if scale && f1 > f0 {+ let r = (k - f0).0 as f64 / (f1 - f0).0 as f64;+ t0 + Tick((r * (t1 - t0).0 as f64).round() as i64)+ } else {+ t0 + (k - f0)+ }+ };+ for p in e.params.values_mut() {+ for k in &mut p.keyframes {+ k.time = map(k.time);+ }+ }+ for m in &mut e.masks {+ for p in [&mut m.path, &mut m.feather, &mut m.opacity, &mut m.expansion] {+ for k in &mut p.keyframes {+ k.time = map(k.time);+ }+ }+ }+ }++ // ---------------------------------------------------------------------------------------------+ // File+ // ---------------------------------------------------------------------------------------------++ fn sequence_from_clip(s: &mut Session, p: &Value) -> Result<Value> {+ let items: Vec<ItemId> = items_p(s, p).into_iter().filter(|i| is_clip_item(&s.project, *i)).collect();+ let first = *items.first().ok_or_else(|| bad("file.newSequenceFromClip", "select a clip in the Project panel"))?;+ let pi = s.project.item(first).ok_or_else(|| bad("file.newSequenceFromClip", "no such item"))?.clone();+ let mut settings = match &pi.kind {+ ItemKind::Sequence(q) => q.settings.clone(),+ _ => media_root(&s.project, first).map(|(_, m, _)| crate::commands::default_seq_settings_for(&m.info)).unwrap_or_default(),+ };+ if let ItemKind::AdjustmentLayer { width, height, rate, .. } = &pi.kind {+ settings.width = *width;+ settings.height = *height;+ settings.frame_rate = *rate;+ }+ let channels = media_root(&s.project, first).and_then(|(_, m, _)| m.info.audio.as_ref().map(|a| a.channels)).unwrap_or(2);+ let n_audio = media_root(&s.project, first).and_then(|(_, m, _)| m.interpret.audio_channels.as_ref().map(|a| a.clips.len())).unwrap_or(1).max(1);+ let n0 = s.history.undo.len();+ let name = pi.name.clone();+ let bin = s.project.root.parent_of(first).filter(|b| *b != s.project.root.id);+ let seq = s.edit("New Sequence From Clip", |pr, st| {+ let id = pr.new_sequence(&name, settings, 1, n_audio.max(1), bin);+ if channels == 1+ && let Some(q) = pr.sequence_mut(id)+ {+ q.settings.audio_master = AudioChannels::Stereo;+ }+ st.active_sequence = Some(id);+ if !st.open_sequences.contains(&id) {+ st.open_sequences.push(id);+ }+ Ok(id)+ })?;+ let mut at = Tick::ZERO;+ let mut placed = Vec::new();+ for item in items {+ let Some(range) = item_range(&s.project, item) else { continue };+ let tg = s.targeting();- let ids = place_item(s, item, range, at, tg.video_dest, tg.audio_dest, false, "New Sequence From Clip")?;++ let ids = place_item(s, item, range, at, tg.video_dest, tg.audio_dest, false, "New Sequence From Clip", None)?;+ at = s.active_sequence().map(|q| q.duration()).unwrap_or(at);+ placed.extend(ids.iter().map(|c| c.0));+ }+ collapse_history(s, n0, "New Sequence From Clip");+ s.state.selection.clear();+ s.events.push(crate::Event::OpenSequence(seq));+ Ok(json!({"sequence": seq.0, "clips": placed}))+ }++ /// The media range an item edits in with: its In/Out marks, a subclip's range, or the whole item.+ fn item_range(p: &Project, id: ItemId) -> Option<TimeRange> {+ let it = p.item(id)?;+ let rate = item_rate(p, id);+ Some(match &it.kind {+ ItemKind::Media(m) => {+ let full = if m.info.duration.0 > 0 { m.info.duration } else { p.settings.default_still_duration };+ let a = m.mark_in.unwrap_or(Tick::ZERO);+ let b = m.mark_out.map(|o| o + rate.frame_duration()).unwrap_or(full);+ TimeRange::from_bounds(a, b.max(a + rate.frame_duration()))+ }+ ItemKind::Subclip { range, .. } => *range,+ ItemKind::Sequence(q) => {+ let a = q.mark_in.unwrap_or(Tick::ZERO);+ let b = q.mark_out.map(|o| o + q.settings.frame_rate.frame_duration()).unwrap_or(q.duration());+ TimeRange::from_bounds(a, b.max(a + q.settings.frame_rate.frame_duration()))+ }+ _ => TimeRange::new(Tick::ZERO, it.duration()),+ })+ }++ fn bin_from_selection(s: &mut Session, p: &Value) -> Result<Value> {+ let items = items_p(s, p);+ if items.is_empty() {+ return Err(bad("file.newBinFromSelection", "select items in the Project panel"));+ }+ let parent = s.project.root.parent_of(items[0]).filter(|b| *b != s.project.root.id);+ let name = match str_p(p, "name") {+ Some(n) => n.to_string(),+ None => {+ let mut n = 1;+ let mut names = Vec::new();+ bin_names(&s.project.root, &mut names);+ while names.contains(&format!("Bin {n:02}")) {+ n += 1;+ }+ format!("Bin {n:02}")+ }+ };+ let bin = s.edit("New Bin From Selection", |pr, _| {+ let b = pr.add_bin(&name, parent);+ pr.move_to_bin(&items, Some(b));+ Ok(b)+ })?;+ Ok(json!({"bin": bin.0, "moved": items.len()}))+ }++ fn bin_names(b: &filmcraft_project::Bin, out: &mut Vec<String>) {+ for c in &b.children {+ if let BinEntry::Bin(x) = c {+ out.push(x.name.clone());+ bin_names(x, out);+ }+ }+ }++ fn offline_file(s: &mut Session, p: &Value) -> Result<Value> {+ let st = s.active_sequence().map(|q| q.settings.clone()).unwrap_or_default();+ let has_v = bool_p(p, "video").unwrap_or(true);+ let has_a = bool_p(p, "audio").unwrap_or(true);+ if !has_v && !has_a {+ return Err(bad("file.newOfflineFile", "an offline file needs video or audio"));+ }+ let rate = f64_p(p, "fps").map(FrameRate::from_f64).unwrap_or(st.frame_rate);+ let width = u64_p(p, "width").map(|v| v as u32).unwrap_or(st.width);+ let height = u64_p(p, "height").map(|v| v as u32).unwrap_or(st.height);+ let secs = f64_p(p, "seconds").unwrap_or(10.0).max(rate.frame_duration().seconds());+ let duration = rate.snap_nearest(Tick::from_seconds_f64(secs)).max(rate.frame_duration());+ let start_tc = match str_p(p, "timecode") {+ Some(tc) => Some(parse_timecode(tc, rate, false, 0).map_err(|e| bad("file.newOfflineFile", format!("timecode: {e:?}")))?),+ None => None,+ };+ let file_name = str_p(p, "fileName").map(str::to_string).filter(|n| !n.is_empty()).unwrap_or_else(|| "Offline.mov".into());+ let name = str_p(p, "name").map(str::to_string).filter(|n| !n.is_empty()).unwrap_or_else(|| file_name.clone());+ let info = filmcraft_media::MediaInfo {+ name: file_name.clone(),+ kind: if has_v { filmcraft_media::MediaKind::Movie } else { filmcraft_media::MediaKind::AudioOnly },+ duration,+ video: has_v.then(|| filmcraft_media::VideoStreamInfo {+ width,+ height,+ frame_rate: rate,+ par: (1, 1),+ codec: String::new(),+ pixel_format: String::new(),+ color: Default::default(),+ has_alpha: false,+ bitrate: None,+ }),+ audio: has_a.then(|| filmcraft_media::AudioStreamInfo {+ sample_rate: u64_p(p, "sampleRate").unwrap_or(48_000) as u32,+ channels: u64_p(p, "channels").unwrap_or(2).max(1) as u32,+ codec: String::new(),+ bits_per_sample: None,+ }),+ container: String::new(),+ start_timecode: start_tc,+ file_size: None,+ };+ let mut meta = BTreeMap::new();+ if let Some(t) = str_p(p, "tapeName").filter(|t| !t.is_empty()) {+ meta.insert("Tape Name".to_string(), t.to_string());+ }+ if let Some(d) = str_p(p, "description").filter(|t| !t.is_empty()) {+ meta.insert("Description".to_string(), d.to_string());+ }+ let id = s.edit("New Offline File", |pr, stt| {+ let id = pr.add_item(+ &name,+ if has_v { Label::Iris } else { Label::Caribbean },+ ItemKind::Media(MediaClip {+ media: MediaRef::File { path: file_name },+ info,+ interpret: Default::default(),+ mark_in: None,+ mark_out: None,+ markers: vec![],+ offline: true,+ proxy: None,+ identity: None,+ }),+ None,+ );+ if let Some(it) = pr.item_mut(id) {+ it.metadata = meta;+ }+ stt.project_selection = vec![id];+ Ok(id)+ })?;+ Ok(json!({"item": id.0}))+ }++ fn close_project(s: &mut Session, p: &Value) -> Result<Value> {+ if s.is_dirty() && !bool_p(p, "force").unwrap_or(false) {+ return Err(EngineError::Other("the project has unsaved changes: save it first, or pass {\"force\": true} to discard them".into()));+ }+ s.project = std::sync::Arc::new(Project::new("Untitled"));+ s.history = Default::default();+ s.history.limit = 200;+ s.state = Session::default().state;+ if s.path.take().is_some() {+ s.previews.reset_temp();+ }+ s.revision += 1;+ s.saved_revision = s.revision;+ s.events.push(crate::Event::ProjectChanged { revision: s.revision });+ Ok(json!({"closed": true}))+ }++ // ---------------------------------------------------------------------------------------------+ // Edit+ // ---------------------------------------------------------------------------------------------++ fn apply_label(s: &mut Session, p: &Value, l: Label) -> Result<Value> {+ let items = match p.get("items").and_then(Value::as_array) {+ Some(a) => a.iter().filter_map(|v| v.as_u64().map(ItemId)).collect(),+ None if p.get("clips").is_some() => Vec::new(),+ None => s.state.project_selection.clone(),+ };+ let clips = match p.get("clips").and_then(Value::as_array) {+ Some(a) => a.iter().filter_map(|v| v.as_u64().map(ClipId)).collect(),+ None if p.get("items").is_some() => Vec::new(),+ None => s.state.selection.clone(),+ };+ if items.is_empty() && clips.is_empty() {+ return Err(EngineError::Other("select clips or project items".into()));+ }+ let seq = s.state.active_sequence;+ let n = s.edit(&format!("Label {}", l.name()), |pr, _| {+ let mut n = 0;+ for i in &items {+ if let Some(it) = pr.item_mut(*i) {+ it.label = l;+ n += 1;+ }+ }+ if let Some(q) = seq.and_then(|q| pr.sequence_mut(q)) {+ for c in &clips {+ if let Some((_, it)) = q.find_item_mut(*c) {+ it.label = l;+ n += 1;+ }+ }+ }+ Ok(n)+ })?;+ Ok(json!({"label": l.name(), "labelled": n}))+ }++ fn select_label_group(s: &mut Session, _: &Value) -> Result<Value> {+ if !s.state.selection.is_empty() {+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let labels: BTreeSet<&str> = s.state.selection.iter().filter_map(|c| q.find_item(*c).map(|(_, i)| i.label.name())).collect();+ let sel: Vec<ClipId> = q.all_tracks().flat_map(|t| t.items.iter()).filter(|i| labels.contains(i.label.name())).map(|i| i.id).collect();+ s.state.selection = sel;+ return Ok(json!({"clips": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>()}));+ }+ let labels: BTreeSet<&str> = s.state.project_selection.iter().filter_map(|i| s.project.item(*i).map(|it| it.label.name())).collect();+ let mut all = Vec::new();+ s.project.root.all_items(&mut all);+ let sel: Vec<ItemId> = all.into_iter().filter(|i| s.project.item(*i).is_some_and(|it| labels.contains(it.label.name()))).collect();+ s.state.project_selection = sel;+ Ok(json!({"items": s.state.project_selection.iter().map(|i| i.0).collect::<Vec<_>>()}))+ }++ fn select_all_matching(s: &mut Session, p: &Value) -> Result<Value> {+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let sources: BTreeSet<ItemId> = clips_p(s, p).iter().filter_map(|c| q.find_item(*c).map(|(_, i)| i.item)).collect();+ let sel: Vec<ClipId> = q.all_tracks().flat_map(|t| t.items.iter()).filter(|i| sources.contains(&i.item)).map(|i| i.id).collect();+ s.state.selection = sel;+ Ok(json!({"clips": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>()}))+ }++ fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {+ let used = used_items(&s.project);+ let unused: Vec<ItemId> = s.project.items.keys().copied().filter(|i| is_removable(&s.project, *i) && !used.contains(i)).collect();+ if unused.is_empty() {+ return Ok(json!({"removed": []}));+ }+ let gone = unused.clone();+ s.edit("Remove Unused", |pr, st| {+ remove_items(pr, &gone);+ st.project_selection.retain(|i| !gone.contains(i));+ if st.source_item.is_some_and(|i| gone.contains(&i)) {+ st.source_item = None;+ }+ Ok(())+ })?;+ for i in &unused {+ s.media.remove(*i);+ }+ Ok(json!({"removed": unused.iter().map(|i| i.0).collect::<Vec<_>>()}))+ }++ /// Media items that refer to the same file (or generator) with the same interpretation are+ /// duplicates; the oldest one is kept and every reference to the others moves to it.+ fn consolidate_duplicates(s: &mut Session, _: &Value) -> Result<Value> {+ let mut groups: BTreeMap<String, Vec<ItemId>> = BTreeMap::new();+ for it in s.project.items.values() {+ if let ItemKind::Media(m) = &it.kind {+ // same file (or generator), interpretation and streams+ let shape = (m.info.video.is_some(), m.info.audio.is_some(), m.info.duration);+ let key = serde_json::to_string(&(&m.media, &m.interpret, m.offline, shape)).unwrap_or_default();+ groups.entry(key).or_default().push(it.id);+ }+ }+ let mut remap: BTreeMap<ItemId, ItemId> = BTreeMap::new();+ for ids in groups.values().filter(|g| g.len() > 1) {+ for d in &ids[1..] {+ remap.insert(*d, ids[0]);+ }+ }+ if remap.is_empty() {+ return Ok(json!({"removed": []}));+ }+ let map = remap.clone();+ s.edit("Consolidate Duplicates", |pr, st| {+ for it in pr.items.values_mut() {+ match &mut it.kind {+ ItemKind::Sequence(q) => {+ for t in q.all_tracks_mut() {+ for i in &mut t.items {+ if let Some(k) = map.get(&i.item) {+ i.item = *k;+ }+ }+ }+ }+ ItemKind::Subclip { parent, .. } => {+ if let Some(k) = map.get(parent) {+ *parent = *k;+ }+ }+ _ => {}+ }+ }+ // keep the marks / markers of the kept item; carry markers of duplicates over+ let dups: Vec<ItemId> = map.keys().copied().collect();+ for d in &dups {+ let markers = pr.item(*d).and_then(|i| i.as_media()).map(|m| m.markers.clone()).unwrap_or_default();+ if let Some(m) = pr.item_mut(map[d]).and_then(|i| i.as_media_mut()) {+ for mk in markers {+ if !m.markers.iter().any(|x| x.start == mk.start && x.name == mk.name) {+ m.markers.push(mk);+ }+ }+ m.markers.sort_by_key(|x| x.start);+ }+ }+ remove_items(pr, &dups);+ for i in st.project_selection.iter_mut() {+ if let Some(k) = map.get(i) {+ *i = *k;+ }+ }+ st.project_selection.dedup();+ if let Some(k) = st.source_item.and_then(|i| map.get(&i)) {+ st.source_item = Some(*k);+ }+ Ok(())+ })?;+ for d in remap.keys() {+ s.media.remove(*d);+ }+ Ok(json!({"removed": remap.keys().map(|i| i.0).collect::<Vec<_>>(), "kept": remap.values().map(|i| i.0).collect::<BTreeSet<_>>()}))+ }++ /// Which attributes a Paste / Remove Attributes call touches.+ struct AttrSel {+ intrinsic: Vec<&'static str>,+ /// None = every standard effect; Some(ids) = those effects (Some(empty) = none).+ effects: Option<Vec<String>>,+ }++ fn attr_sel(p: &Value) -> AttrSel {+ let on = |k: &str| bool_p(p, k).unwrap_or(true);+ let mut intrinsic = Vec::new();+ for (k, id) in [+ ("motion", "motion"),+ ("opacity", "opacity"),+ ("timeRemapping", "time_remap"),+ ("volume", "volume"),+ ("channelVolume", "channel_volume"),+ ("panner", "panner"),+ ] {+ if on(k) {+ intrinsic.push(id);+ }+ }+ let effects = match p.get("effects") {+ Some(Value::Bool(false)) => Some(Vec::new()),+ Some(Value::Array(a)) => Some(a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()),+ _ => None,+ };+ AttrSel { intrinsic, effects }+ }++ fn is_standard(e: &filmcraft_project::EffectInstance) -> bool {+ e.def().is_some_and(|d| !d.intrinsic) && !filmcraft_project::graphic::is_layer(e) && !e.essential+ }++ fn wants_effect(sel: &AttrSel, e: &filmcraft_project::EffectInstance) -> bool {+ sel.effects.as_ref().is_none_or(|ids| ids.contains(&e.effect))+ }++ fn paste_attributes(s: &mut Session, p: &Value) -> Result<Value> {+ let sel = attr_sel(p);+ let scale = bool_p(p, "scaleTimes").unwrap_or(true);+ let src_v = s.state.clipboard.iter().find(|c| c.0 == TrackKind::Video).map(|c| c.2.clone());+ let src_a = s.state.clipboard.iter().find(|c| c.0 == TrackKind::Audio).map(|c| c.2.clone());+ let targets = with_links(s, &clips_p(s, p));+ let n = s.edit_sequence("Paste Attributes", |q, _, _| {+ let mut n = 0;+ for c in &targets {+ let Some((tid, _)) = q.find_item(*c) else { continue };+ let kind = q.track(tid).map(|t| t.kind).unwrap_or_default();+ let Some(src) = (if kind == TrackKind::Video { src_v.as_ref() } else { src_a.as_ref() }) else { continue };+ let Some((_, dst)) = q.find_item_mut(*c) else { continue };+ let before = dst.clone();+ for id in &sel.intrinsic {+ let Some(e) = src.effect(id) else { continue };+ let mut e = e.clone();+ retime_effect(&mut e, src, &before, scale);+ match dst.effects.iter_mut().find(|x| x.effect == *id) {+ Some(slot) => *slot = e,+ None => dst.effects.push(e),+ }+ }+ for e in src.effects.iter().filter(|e| is_standard(e) && wants_effect(&sel, e)) {+ let mut e = e.clone();+ retime_effect(&mut e, src, &before, scale);+ dst.effects.push(e);+ }+ if *dst != before {+ n += 1;+ }+ }+ Ok(n)+ })?;+ Ok(json!({"clips": n}))+ }++ fn remove_attributes(s: &mut Session, p: &Value) -> Result<Value> {+ let sel = attr_sel(p);+ let targets = with_links(s, &clips_p(s, p));+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let frame = (seq.settings.width, seq.settings.height);+ let sizes: BTreeMap<ClipId, (u32, u32)> =+ targets.iter().filter_map(|c| seq.find_item(*c).map(|(_, i)| (*c, filmcraft_render::source_size(&s.project, i.item).unwrap_or(frame)))).collect();+ let n = s.edit_sequence("Remove Attributes", |q, _, _| {+ let mut n = 0;+ for c in &targets {+ let Some((_, it)) = q.find_item_mut(*c) else { continue };+ let before = it.clone();+ for id in &sel.intrinsic {+ if let Some(slot) = it.effects.iter_mut().find(|x| x.effect == *id)+ && let Some(def) = slot.def()+ {+ let mut fresh = def.instance();+ filmcraft_project::resolve_auto_points(&mut fresh, frame, sizes.get(c).copied().unwrap_or(frame));+ *slot = fresh;+ }+ }+ it.effects.retain(|e| !(is_standard(e) && wants_effect(&sel, e)));+ if *it != before {+ n += 1;+ }+ }+ Ok(n)+ })?;+ Ok(json!({"clips": n}))+ }++ // ---------------------------------------------------------------------------------------------+ // Clip: subclips, Modify+ // ---------------------------------------------------------------------------------------------++ /// What Make Subclip would subclip: (parent media item, media range, name, label).+ fn subclip_plan(s: &Session, p: &Value) -> Result<(ItemId, TimeRange, String, Label)> {+ Ok(if let Some(c) = clip_p_or_selection(s, p) {+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let (_, it) = q.find_item(c).ok_or_else(|| bad("clip.makeSubclip", "no such clip"))?;+ let (root, _, _) = media_root(&s.project, it.item).ok_or_else(|| bad("clip.makeSubclip", "only media clips can be subclipped"))?;+ (root, TimeRange::from_bounds(it.source_in, it.source_out()), it.name.clone(), it.label)+ } else {+ let item = item_p(p, "item").or_else(|| subclip_source(s)).ok_or_else(|| bad("clip.makeSubclip", "open a clip in the Source monitor"))?;+ let (root, m, sub) = media_root(&s.project, item).ok_or_else(|| bad("clip.makeSubclip", "only media clips can be subclipped"))?;+ let pi = s.project.item(item).expect("resolved");+ let rate = m.frame_rate();+ let full = sub.unwrap_or(TimeRange::new(Tick::ZERO, if m.info.duration.0 > 0 { m.info.duration } else { s.project.settings.default_still_duration }));+ let range = if sub.is_some() {+ full+ } else {+ let a = m.mark_in.unwrap_or(full.start);+ let b = m.mark_out.map(|o| o + rate.frame_duration()).unwrap_or(full.end());+ TimeRange::from_bounds(a, b)+ };+ (root, range, pi.name.clone(), pi.label)+ })+ }++ /// The Make Subclip dialog's defaults: `{name, startFrame, endFrame, fps}` (media frames).+ pub fn subclip_defaults(s: &Session, p: &Value) -> Option<Value> {+ let (parent, range, base, _) = subclip_plan(s, p).ok()?;+ let rate = item_rate(&s.project, parent);+ Some(json!({"name": format!("{base}.Subclip"), "startFrame": rate.frame_at(range.start), "endFrame": rate.frame_at(range.end()), "fps": rate.as_f64()}))+ }++ fn make_subclip(s: &mut Session, p: &Value) -> Result<Value> {+ let (parent, range, base, label) = subclip_plan(s, p)?;+ let rate = item_rate(&s.project, parent);+ let a = p+ .get("start")+ .and_then(Value::as_i64)+ .map(Tick)+ .or_else(|| p.get("startFrame").and_then(Value::as_i64).map(|f| rate.tick_of(f)))+ .unwrap_or(range.start);+ let b =+ p.get("end").and_then(Value::as_i64).map(Tick).or_else(|| p.get("endFrame").and_then(Value::as_i64).map(|f| rate.tick_of(f))).unwrap_or(range.end());+ if b <= a || a < Tick::ZERO {+ return Err(bad("clip.makeSubclip", "the subclip's end must be after its start"));+ }+ let restrict = bool_p(p, "restrictTrims").unwrap_or(true);+ let name = str_p(p, "name").map(str::to_string).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("{base}.Subclip"));+ let bin = s.project.root.parent_of(parent).filter(|b| *b != s.project.root.id);+ let id = s.edit("Make Subclip", |pr, st| {+ let id = pr.add_item(&name, label, ItemKind::Subclip { parent, range: TimeRange::from_bounds(a, b), restrict_trims: restrict }, bin);+ st.project_selection = vec![id];+ Ok(id)+ })?;+ Ok(json!({"item": id.0}))+ }++ /// `clip` param, else the timeline selection when nothing is loaded in the Source monitor and no+ /// `item` is given.+ fn clip_p_or_selection(s: &Session, p: &Value) -> Option<ClipId> {+ if let Some(c) = crate::commands::clip_p(p, "clip") {+ return Some(c);+ }+ if item_p(p, "item").is_some() || subclip_source(s).is_some() {+ return None;+ }+ s.state.selection.first().copied()+ }++ fn edit_subclip(s: &mut Session, p: &Value) -> Result<Value> {+ let item = item_p(p, "item")+ .or_else(|| s.state.project_selection.iter().copied().find(|i| s.project.item(*i).is_some_and(|it| matches!(it.kind, ItemKind::Subclip { .. }))))+ .ok_or_else(|| bad("clip.editSubclip", "select a subclip"))?;+ let Some(ItemKind::Subclip { parent, range, restrict_trims }) = s.project.item(item).map(|i| i.kind.clone()) else {+ return Err(bad("clip.editSubclip", "not a subclip"));+ };+ let rate = item_rate(&s.project, parent);+ let a = p+ .get("start")+ .and_then(Value::as_i64)+ .map(Tick)+ .or_else(|| p.get("startFrame").and_then(Value::as_i64).map(|f| rate.tick_of(f)))+ .unwrap_or(range.start);+ let b =+ p.get("end").and_then(Value::as_i64).map(Tick).or_else(|| p.get("endFrame").and_then(Value::as_i64).map(|f| rate.tick_of(f))).unwrap_or(range.end());+ if b <= a || a < Tick::ZERO {+ return Err(bad("clip.editSubclip", "the subclip's end must be after its start"));+ }+ let restrict = bool_p(p, "restrictTrims").unwrap_or(restrict_trims);+ let convert = bool_p(p, "convertToMaster").unwrap_or(false);+ let parent_media = s.project.item(parent).and_then(|i| i.as_media()).cloned();+ s.edit("Edit Subclip", |pr, _| {+ let it = pr.item_mut(item).ok_or_else(|| bad("clip.editSubclip", "no such item"))?;+ if convert {+ let mut m = parent_media.ok_or_else(|| bad("clip.editSubclip", "the subclip's media is gone"))?;+ m.mark_in = None;+ m.mark_out = None;+ m.markers.clear();+ it.kind = ItemKind::Media(m);+ } else {+ it.kind = ItemKind::Subclip { parent, range: TimeRange::from_bounds(a, b), restrict_trims: restrict };+ }+ Ok(())+ })?;+ if convert {+ s.media.remove(item);+ }+ Ok(json!({"item": item.0, "converted": convert}))+ }++ fn parse_format(f: &str) -> Option<AudioChannels> {+ match f.to_ascii_lowercase().as_str() {+ "mono" => Some(AudioChannels::Mono),+ "stereo" => Some(AudioChannels::Stereo),+ "5.1" | "surround51" | "surround" => Some(AudioChannels::Surround51),+ "adaptive" => Some(AudioChannels::Adaptive),+ _ => None,+ }+ }++ fn audio_channels(s: &mut Session, p: &Value) -> Result<Value> {+ let items: Vec<ItemId> =+ items_p(s, p).into_iter().filter(|i| s.project.item(*i).and_then(|it| it.as_media()).is_some_and(|m| m.info.has_audio())).collect();+ if items.is_empty() || p.get("channels").is_some() {+ // timeline audio clips: which source channels each plays+ let clips = match p.get("clips").and_then(Value::as_array) {+ Some(a) if a.iter().all(Value::is_u64) => a.iter().filter_map(|v| v.as_u64().map(ClipId)).collect(),+ _ => selected_audio_clips(s),+ };+ let chans: Vec<u16> =+ p.get("channels").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_u64().map(|c| c as u16)).collect()).unwrap_or_default();+ if clips.is_empty() {+ return Err(bad("clip.audioChannels", "select a clip with audio"));+ }+ s.edit_sequence("Modify Audio Channels", |q, _, _| {+ for c in &clips {+ if let Some((_, it)) = q.find_item_mut(*c) {+ it.source_channels = chans.clone();+ }+ }+ Ok(())+ })?;+ return Ok(json!({"clips": clips.iter().map(|c| c.0).collect::<Vec<_>>(), "channels": chans}));+ }+ let format = match str_p(p, "format") {+ Some(f) => Some(parse_format(f).ok_or_else(|| bad("clip.audioChannels", "format is mono, stereo, 5.1 or adaptive"))?),+ None => None,+ };+ let custom: Option<Vec<Vec<u16>>> = p+ .get("clips")+ .and_then(Value::as_array)+ .map(|a| a.iter().map(|c| c.as_array().map(|x| x.iter().filter_map(|v| v.as_u64().map(|n| n as u16)).collect()).unwrap_or_default()).collect());+ let mut out = Vec::new();+ let mut maps = Vec::new();+ for i in &items {+ let m = s.project.item(*i).and_then(|it| it.as_media()).expect("filtered");+ let n = m.info.audio.as_ref().map_or(2, |a| a.channels) as u16;+ let fmt = format.unwrap_or_else(|| m.interpret.audio_channels.as_ref().map_or(AudioChannels::Stereo, |a| a.format));+ let map = match &custom {+ Some(c) => {+ if c.is_empty() || c.iter().any(|x| x.is_empty() || x.iter().any(|ch| *ch >= n)) {+ return Err(bad("clip.audioChannels", format!("each clip needs source channels between 0 and {}", n - 1)));+ }+ AudioChannelMap { format: fmt, clips: c.clone() }+ }+ None => AudioChannelMap::for_format(fmt, n),+ };+ out.push(json!({"item": i.0, "format": format!("{:?}", map.format), "clips": map.clips}));+ maps.push((*i, map));+ }+ s.edit("Modify Audio Channels", |pr, _| {+ for (i, map) in maps {+ if let Some(m) = pr.item_mut(i).and_then(|it| it.as_media_mut()) {+ // the default stereo pair is no override+ m.interpret.audio_channels = if map == AudioChannelMap::for_format(AudioChannels::Stereo, 2) { None } else { Some(map) };+ }+ }+ Ok(())+ })?;+ Ok(json!({"items": out}))+ }++ fn modify_timecode(s: &mut Session, p: &Value) -> Result<Value> {+ let item = item_p(p, "item")+ .or_else(|| s.state.project_selection.iter().copied().find(|i| s.project.item(*i).and_then(|it| it.as_media()).is_some()))+ .ok_or_else(|| bad("clip.modifyTimecode", "select a clip"))?;+ let m = s.project.item(item).and_then(|i| i.as_media()).ok_or_else(|| bad("clip.modifyTimecode", "not a media clip"))?;+ let rate = m.frame_rate();+ let reset = bool_p(p, "reset").unwrap_or(false);+ let frame = if let Some(tc) = str_p(p, "timecode") {+ Some(parse_timecode(tc, rate, false, 0).map_err(|e| bad("clip.modifyTimecode", format!("timecode: {e:?}")))?)+ } else {+ p.get("frame").and_then(Value::as_i64)+ };+ let tape = str_p(p, "tapeName").map(str::to_string);+ if frame.is_none() && tape.is_none() && !reset {+ return Err(bad("clip.modifyTimecode", "need `timecode`, `frame`, `tapeName` or `reset`"));+ }+ if frame.is_some_and(|f| f < 0) {+ return Err(bad("clip.modifyTimecode", "timecode must not be negative"));+ }+ const FILE_TC: &str = "File Timecode";+ let r = s.edit("Modify Timecode", |pr, _| {+ let it = pr.item_mut(item).ok_or_else(|| bad("clip.modifyTimecode", "no such item"))?;+ let cur = it.as_media().and_then(|m| m.info.start_timecode);+ if reset {+ // back to the file's own timecode ("none" = the file had none)+ if let Some(orig) = it.metadata.remove(FILE_TC)+ && let Some(m) = it.as_media_mut()+ {+ m.info.start_timecode = orig.parse::<i64>().ok();+ }+ } else if let Some(f) = frame {+ it.metadata.entry(FILE_TC.to_string()).or_insert_with(|| cur.map(|c| c.to_string()).unwrap_or_else(|| "none".into()));+ if let Some(m) = it.as_media_mut() {+ m.info.start_timecode = Some(f);+ }+ }+ if let Some(t) = &tape {+ if t.is_empty() {+ it.metadata.remove("Tape Name");+ } else {+ it.metadata.insert("Tape Name".into(), t.clone());+ }+ }+ Ok(it.as_media().and_then(|m| m.info.start_timecode))+ })?;+ Ok(json!({"item": item.0, "startTimecode": r}))+ }++ // ---------------------------------------------------------------------------------------------+ // Clip: Video Options+ // ---------------------------------------------------------------------------------------------++ fn video_clips(s: &Session, p: &Value) -> Vec<ClipId> {+ let Some(q) = s.active_sequence() else { return Vec::new() };+ clips_p(s, p).into_iter().filter(|c| q.video_tracks.iter().any(|t| t.item(*c).is_some())).collect()+ }++ fn frame_hold_options(s: &mut Session, p: &Value) -> Result<Value> {+ let clips = video_clips(s, p);+ if clips.is_empty() {+ return Err(bad("clip.frameHoldOptions", "select a video clip"));+ }+ let enabled = bool_p(p, "enabled").unwrap_or(true);+ let hold_filters = bool_p(p, "holdFilters").unwrap_or(false);+ let mode = str_p(p, "holdOn").unwrap_or("in").to_string();+ let ph = s.playhead();+ let seq_t = time_p(s, p, "");+ let tc = str_p(p, "timecode").map(str::to_string);+ let rates: BTreeMap<ClipId, (FrameRate, i64)> = {+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ clips+ .iter()+ .filter_map(|c| {+ let (_, it) = q.find_item(*c)?;+ let start_tc = media_root(&s.project, it.item).and_then(|(_, m, _)| m.info.start_timecode).unwrap_or(0);+ Some((*c, (item_rate(&s.project, it.item), start_tc)))+ })+ .collect()+ };+ let raw_time = p.get("time").and_then(Value::as_i64).map(Tick);+ let held = s.edit_sequence("Frame Hold Options", |q, _, _| {+ let mut out = Vec::new();+ for c in &clips {+ let Some((_, it)) = q.find_item_mut(*c) else { continue };+ if !enabled {+ it.frame_hold = None;+ it.hold_filters = false;+ continue;+ }+ let last = it.end() - Tick(1);+ let unheld = |it: &TrackItem, t: Tick| it.moving_source_time_at(t.clamp(it.start, last));+ let h = match mode.as_str() {+ "in" => unheld(it, it.start),+ "out" => unheld(it, last),+ "playhead" => unheld(it, ph),+ "sequenceTime" => unheld(it, seq_t.ok_or_else(|| bad("clip.frameHoldOptions", "sequenceTime needs `time`/`timecode`"))?),+ "sourceTimecode" => {+ let (rate, start_tc) = rates[c];+ match (&tc, raw_time) {+ (Some(tc), _) => {+ let f = parse_timecode(tc, rate, false, 0).map_err(|e| bad("clip.frameHoldOptions", format!("timecode: {e:?}")))?;+ rate.tick_of(f - start_tc)+ }+ (None, Some(t)) => t,+ (None, None) => return Err(bad("clip.frameHoldOptions", "sourceTimecode needs `timecode` or `time` (media ticks)")),+ }+ }+ m => return Err(bad("clip.frameHoldOptions", format!("unknown holdOn `{m}`"))),+ };+ let rate = rates.get(c).map(|r| r.0).unwrap_or_default();+ let h = rate.snap(h.max(Tick::ZERO));+ it.frame_hold = Some(h);+ it.hold_filters = hold_filters;+ out.push(json!({"clip": c.0, "hold": h.0}));+ }+ Ok(out)+ })?;+ Ok(json!({"clips": held}))+ }++ /// Add Frame Hold: the selected clips (or the targeted video clip under the playhead) hold the+ /// frame at the playhead from there to their end; the clip is split at the playhead first.+ pub(crate) fn add_frame_hold(s: &mut Session, p: &Value) -> Result<Value> {+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let mut clips: Vec<ClipId> = video_clips(s, p).into_iter().filter(|c| q.find_item(*c).is_some_and(|(_, i)| i.start <= t && t < i.end())).collect();+ if clips.is_empty() && p.get("clips").is_none() && p.get("clip").is_none() {+ let tg = s.targeting().targeted;+ clips = q.video_tracks.iter().filter(|tr| tg.contains(&tr.id) && !tr.locked).filter_map(|tr| tr.item_at(t).map(|i| i.id)).take(1).collect();+ }+ if clips.is_empty() {+ return Err(EngineError::Other("place the playhead over a selected video clip".into()));+ }+ let held = s.edit_sequence("Add Frame Hold", |q, ctx, st| {+ let mut out = Vec::new();+ for c in &clips {+ let Some((_, it)) = q.find_item(*c) else { continue };+ let hold = it.moving_source_time_at(t);+ let target = if it.start < t { edit::razor_items(q, &[*c], t, ctx).first().copied() } else { Some(*c) };+ if let Some(id) = target+ && let Some((_, r)) = q.find_item_mut(id)+ {+ r.frame_hold = Some(hold);+ out.push(id);+ }+ }+ st.selection = out.clone();+ Ok(out)+ })?;+ Ok(json!({"clips": held.iter().map(|c| c.0).collect::<Vec<_>>()}))+ }++ fn insert_frame_hold_segment(s: &mut Session, p: &Value) -> Result<Value> {+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let rate = q.settings.frame_rate;+ let pick = |c: &ClipId| q.video_tracks.iter().find_map(|tr| tr.item(*c).filter(|i| i.start <= t && t < i.end()).map(|i| (tr.id, i.clone())));+ let mut hit = crate::commands::clip_p(p, "clip").and_then(|c| pick(&c)).or_else(|| s.state.selection.iter().find_map(pick));+ if hit.is_none() && crate::commands::clip_p(p, "clip").is_none() {+ let tg = s.targeting().targeted;+ hit = q.video_tracks.iter().filter(|tr| tg.contains(&tr.id) && !tr.locked).find_map(|tr| tr.item_at(t).map(|i| (tr.id, i.clone())));+ }+ let (track, it) = hit.ok_or_else(|| EngineError::Other("place the playhead over a video clip".into()))?;+ let secs = f64_p(p, "seconds").unwrap_or(2.0);+ let dur = rate.snap_nearest(Tick((secs * TICKS_PER_SECOND as f64).round() as i64)).max(rate.frame_duration());+ let hold = it.moving_source_time_at(t);+ let id = s.edit_sequence("Insert Frame Hold Segment", |q, ctx, st| {+ let mut seg = it.clone();+ seg.id = ClipId(ctx.alloc());+ seg.start = t;+ seg.duration = dur;+ seg.source_in = hold;+ seg.frame_hold = Some(hold);+ seg.link = None;+ seg.markers.clear();+ let ids = edit::insert(q, vec![(track, seg)], ctx)?;+ st.selection = ids.clone();+ Ok(ids[0])+ })?;+ Ok(json!({"clip": id.0, "duration": dur.0}))+ }++ fn field_options(s: &mut Session, p: &Value) -> Result<Value> {+ let clips = video_clips(s, p);+ if clips.is_empty() {+ return Err(bad("clip.fieldOptions", "select a video clip"));+ }+ let processing = match str_p(p, "processing").unwrap_or("none") {+ "none" => FieldProcessing::None,+ "alwaysDeinterlace" => FieldProcessing::AlwaysDeinterlace,+ "flickerRemoval" => FieldProcessing::FlickerRemoval,+ x => return Err(bad("clip.fieldOptions", format!("unknown processing `{x}`"))),+ };+ let fo = FieldOptions { reverse_field_dominance: bool_p(p, "reverseFieldDominance").unwrap_or(false), processing };+ s.edit_sequence("Field Options", |q, _, _| {+ for c in &clips {+ if let Some((_, it)) = q.find_item_mut(*c) {+ it.field_options = (fo != FieldOptions::default()).then_some(fo);+ }+ }+ Ok(())+ })?;+ Ok(json!({"clips": clips.len()}))+ }++ fn set_interpolation(s: &mut Session, p: &Value, m: TimeInterpolation) -> Result<Value> {+ let clips = video_clips(s, p);+ if clips.is_empty() {+ return Err(bad("clip.setTimeInterpolation", "select a video clip"));+ }+ s.edit_sequence(&format!("Time Interpolation: {}", m.label()), |q, _, _| {+ for c in &clips {+ if let Some((_, it)) = q.find_item_mut(*c) {+ it.time_interpolation = m;+ }+ }+ Ok(())+ })?;+ Ok(json!({"mode": m.name(), "clips": clips.len()}))+ }++ /// Fit to frame (the whole clip visible) / Fill frame (the frame covered): sets Motion ▸ Scale+ /// and centres the clip.+ fn fit_fill(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {+ let clips = video_clips(s, p);+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let (fw, fh) = (q.settings.width as f64, q.settings.height as f64);+ let sizes: Vec<(ClipId, (u32, u32))> =+ clips.iter().filter_map(|c| q.find_item(*c).and_then(|(_, i)| filmcraft_render::source_size(&s.project, i.item)).map(|sz| (*c, sz))).collect();+ if sizes.is_empty() {+ return Err(bad(if fill { "clip.fillFrame" } else { "clip.fitToFrame" }, "select a video clip"));+ }+ let label = if fill { "Fill Frame" } else { "Fit to Frame" };+ let out = s.edit_sequence(label, |q, _, _| {+ let mut out = Vec::new();+ for (c, (w, h)) in &sizes {+ let Some((_, it)) = q.find_item_mut(*c) else { continue };+ let (sx, sy) = (fw / (*w).max(1) as f64, fh / (*h).max(1) as f64);+ let pct = (if fill { sx.max(sy) } else { sx.min(sy) }) * 100.0;+ it.scale_to_frame = false;+ let Some(m) = it.effect_mut("motion") else { continue };+ for (k, v) in [+ ("scale", ParamValue::Float(pct)),+ ("uniform_scale", ParamValue::Bool(true)),+ ("position", ParamValue::Vec2(filmcraft_geom::Vec2::new(fw / 2.0, fh / 2.0))),+ ("anchor", ParamValue::Vec2(filmcraft_geom::Vec2::new(*w as f64 / 2.0, *h as f64 / 2.0))),+ ] {+ match m.param_mut(k) {+ Some(prm) => {+ prm.keyframes.clear();+ prm.value = v;+ }+ None => {+ m.params.insert(k.to_string(), filmcraft_project::Param::new(v));+ }+ }+ }+ out.push(json!({"clip": c.0, "scale": pct}));+ }+ Ok(out)+ })?;+ Ok(json!({"clips": out}))+ }++ // ---------------------------------------------------------------------------------------------+ // Clip: Audio Options+ // ---------------------------------------------------------------------------------------------++ fn breakout_to_mono(s: &mut Session, p: &Value) -> Result<Value> {+ let items: Vec<ItemId> =+ items_p(s, p).into_iter().filter(|i| s.project.item(*i).and_then(|it| it.as_media()).is_some_and(|m| m.info.has_audio())).collect();+ if items.is_empty() {+ return Err(bad("clip.breakoutToMono", "select a clip with audio in the Project panel"));+ }+ let made = s.edit("Breakout to Mono", |pr, st| {+ let mut made = Vec::new();+ for i in &items {+ let Some(it) = pr.item(*i).cloned() else { continue };+ let Some(m) = it.as_media() else { continue };+ let n = m.info.audio.as_ref().map_or(1, |a| a.channels).max(1) as u16;+ let bin = pr.root.parent_of(*i).filter(|b| *b != pr.root.id);+ for c in 0..n {+ let suffix = match (n, c) {+ (2, 0) => "Left".to_string(),+ (2, 1) => "Right".to_string(),+ _ => format!("Ch {}", c + 1),+ };+ let mut mm = m.clone();+ mm.interpret.audio_channels = Some(AudioChannelMap { format: AudioChannels::Mono, clips: vec![vec![c]] });+ mm.mark_in = None;+ mm.mark_out = None;+ mm.markers.clear();+ mm.proxy = None;+ let id = pr.add_item(&format!("{} {suffix}", it.name), it.label, ItemKind::Media(mm), bin);+ made.push(id);+ }+ }+ st.project_selection = made.clone();+ Ok(made)+ })?;+ Ok(json!({"items": made.iter().map(|i| i.0).collect::<Vec<_>>()}))+ }++ fn extract_audio(s: &mut Session, p: &Value) -> Result<Value> {+ let items: Vec<ItemId> = match p.get("items") {+ Some(_) => items_p(s, p),+ None => extract_items(s),+ };+ if items.is_empty() {+ return Err(bad("clip.extractAudio", "select a clip with audio"));+ }+ let n0 = s.history.undo.len();+ let mut out = Vec::new();+ for item in items {+ let (root, m, sub) = media_root(&s.project, item).ok_or_else(|| bad("clip.extractAudio", "not a media clip"))?;+ let a = m.info.audio.clone().ok_or_else(|| bad("clip.extractAudio", "the clip has no audio"))?;+ let range = sub.unwrap_or(TimeRange::new(Tick::ZERO, m.info.duration));+ let dir = match str_p(p, "dir") {+ Some(d) => d.to_string(),+ None => s+ .path+ .as_deref()+ .and_then(|x| std::path::Path::new(x).parent())+ .map(|d| d.to_string_lossy().into_owned())+ .or_else(|| match &m.media {+ MediaRef::File { path } => std::path::Path::new(path).parent().map(|d| d.to_string_lossy().into_owned()),+ _ => None,+ })+ .ok_or_else(|| EngineError::Other("save the project first: extracted audio is written next to it".into()))?,+ };+ let pi = s.project.item(item).expect("resolved");+ let name = pi.name.clone();+ let stem = std::path::Path::new(&name).file_stem().map(|x| x.to_string_lossy().into_owned()).unwrap_or_else(|| name.clone());+ let src = s.media.full_res_source(&s.project, root, &*s.services).ok_or_else(|| EngineError::Other(format!("{name}: media is offline")))?;+ let sr = a.sample_rate.max(8000);+ let start = range.start.to_units_floor(sr as i64);+ let frames = (range.end().to_units_floor(sr as i64) - start).max(0) as usize;+ let buf = src.audio(start, frames, sr).map_err(|e| EngineError::Other(format!("{name}: {e}")))?;+ let ch = buf.channel_count().max(1);+ let mut inter = Vec::with_capacity(frames * ch);+ for i in 0..frames {+ for c in 0..ch {+ inter.push(buf.channels.get(c).and_then(|x| x.get(i)).copied().unwrap_or(0.0));+ }+ }+ let bytes = filmcraft_media::wav::write_wav16(&inter, ch as u16, sr);+ let mut path = std::path::Path::new(&dir).join(format!("{stem} Audio Extracted.wav"));+ let mut k = 2;+ while s.services.file_size(&path.to_string_lossy()).is_ok() {+ path = std::path::Path::new(&dir).join(format!("{stem} Audio Extracted {k}.wav"));+ k += 1;+ }+ let path_s = path.to_string_lossy().into_owned();+ s.services.write_file(&path_s, &bytes).map_err(|e| EngineError::Other(format!("{path_s}: {e}")))?;+ let bin = s.project.root.parent_of(item).filter(|b| *b != s.project.root.id);+ let id = crate::commands::import_bytes(s, &path_s, bytes.into(), bin)?;+ out.push(json!({"item": id.0, "path": path_s, "from": item.0}));+ }+ collapse_history(s, n0, "Extract Audio");+ Ok(json!({"extracted": out}))+ }++ // ---------------------------------------------------------------------------------------------+ // Clip: Replace With Clip+ // ---------------------------------------------------------------------------------------------++ #[derive(Clone, Copy, PartialEq, Eq)]+ enum Replace {+ Source,+ MatchFrame,+ Bin,+ }++ fn replace_with(s: &mut Session, p: &Value, how: Replace) -> Result<Value> {+ let cmd = match how {+ Replace::Source => "clip.replaceFromSource",+ Replace::MatchFrame => "clip.replaceFromSourceMatchFrame",+ Replace::Bin => "clip.replaceFromBin",+ };+ let new_item = match how {+ Replace::Bin => item_p(p, "item").or_else(|| s.state.project_selection.iter().copied().find(|i| is_clip_item(&s.project, *i))),+ _ => s.state.source_item,+ }+ .ok_or_else(|| bad(cmd, "no replacement clip"))?;+ let pi = s.project.item(new_item).ok_or_else(|| bad(cmd, "no such item"))?.clone();+ let (has_v, has_a) = (pi.has_video(), pi.has_audio());+ // where the replacement starts in its media: Source In (or the subclip / item start)+ let in_point = match how {+ Replace::Bin => item_range(&s.project, new_item).map(|r| r.start).unwrap_or_default(),+ _ => source_range(s).map(|(_, r)| r.start).unwrap_or_default(),+ };+ let src_ph = s.state.source_playhead;+ let ph = s.playhead();+ let targets = with_links(s, &clips_p(s, p));+ let src_channels = pi.as_media().and_then(|m| m.interpret.audio_channels.as_ref()).and_then(|a| a.clips.first().cloned()).unwrap_or_default();+ let replaced = s.edit_sequence("Replace With Clip", |q, _, _| {+ let mut out = Vec::new();+ for c in &targets {+ let Some((tid, _)) = q.find_item(*c) else { continue };+ let kind = q.track(tid).map(|t| t.kind).unwrap_or_default();+ if (kind == TrackKind::Video && !has_v) || (kind == TrackKind::Audio && !has_a) {+ continue;+ }+ let Some((_, it)) = q.find_item_mut(*c) else { continue };+ let src_in = match how {+ // the Source monitor frame lines up with the sequence playhead+ Replace::MatchFrame => src_ph - Tick(((ph - it.start).0 as f64 * it.speed.abs()).round() as i64),+ _ => in_point,+ };+ if src_in < Tick::ZERO {+ return Err(EngineError::Other("not enough media before the Source monitor playhead to match the frame".into()));+ }+ it.item = new_item;+ it.name = pi.name.clone();+ it.label = pi.label;+ it.source_in = src_in;+ it.frame_hold = None;+ it.multicam = None;+ if kind == TrackKind::Audio {+ it.source_channels = src_channels.clone();+ }+ out.push(c.0);+ }+ if out.is_empty() {+ return Err(EngineError::Other("the replacement has no video or audio for the selected clips".into()));+ }+ Ok(out)+ })?;+ Ok(json!({"clips": replaced, "item": new_item.0}))+ }diff --cc crates/engine/src/commands.rsindex 00580c8ff,403b01539..9db124484--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@@ -318,10 -297,26 +318,27 @@@ pub(crate) fn place_itemplacements.push((vdest.expect("checked"), v));}if has_a {+ let adest = adest.expect("checked");- let mut a = p.make_track_item(item, TrackKind::Audio, at, range, rate).ok_or_else(|| bad(label, "bad item"))?;+ let (arange, aat) = audio_split.unwrap_or((range, at));+ let mut a = p.make_track_item(item, TrackKind::Audio, aat, arange, rate).ok_or_else(|| bad(label, "bad item"))?;- a.link = link;- placements.push((adest.expect("checked"), a));+ // Modify ▸ Audio Channels with several audio clips: one per clip, on the tracks below+ let extra: Vec<Vec<u16>> = p+ .item(item)+ .and_then(|i| i.as_media())+ .and_then(|m| m.interpret.audio_channels.as_ref())+ .map(|m| m.clips.iter().skip(1).cloned().collect())+ .unwrap_or_default();+ let tracks: Vec<TrackId> = p.sequence(seq_id).map(|q| q.audio_tracks.iter().map(|t| t.id).collect()).unwrap_or_default();+ let first = tracks.iter().position(|t| *t == adest).unwrap_or(0);+ a.link = if link.is_none() && !extra.is_empty() { Some(p.alloc_id()) } else { link };+ placements.push((adest, a.clone()));+ for (k, chans) in extra.into_iter().enumerate() {+ let Some(tid) = tracks.get(first + k + 1) else { break };+ let mut b = a.clone();+ b.id = ClipId(p.alloc_id());+ b.source_channels = chans;+ placements.push((*tid, b));+ }}let snapshot = p.clone();let durations = move |id: ItemId| crate::media_duration(&snapshot, &media, id);@@@ -1996,11 -1918,9 +2015,10 @@@ fn build() -> Vec<CommandSpec>v.extend(crate::project_manager::commands());v.extend(crate::masks::commands());v.extend(crate::presets::commands());+ v.extend(crate::transcript::commands());- // Labels as individual commands (Edit ▸ Label ▸ <name>)- for l in Label::ALL {- let _ = l;- }+ // Edit ▸ Label ▸ <colour>, Paste Attributes, subclips, Video / Audio Options, Replace With Clip…+ // and their menu order+ crate::clip_ops::apply_layout(&mut v);v.shrink_to_fit();v}diff --cc crates/format/src/lib.rsindex 469a48274,8490a76a9..42e86f5ff--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@@ -48,7 -48,7 +48,7 @@@ pub type Migration = fn(Value) -> Resul/// `MIGRATIONS[i]` upgrades schema `i + 1` to `i + 2`. Append one function per schema bump; never/// edit a shipped one.--pub const MIGRATIONS: &[Migration] = &[v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9];++pub const MIGRATIONS: &[Migration] = &[v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9, v9_to_v10];/// The schema version this build writes (and the newest it reads).pub const SCHEMA_VERSION: u32 = MIGRATIONS.len() as u32 + 1;@@@ -258,13 -259,13 +258,19 @@@ fn v8_to_v9(doc: Value) -> Result<ValueOk(doc)}++/// v9 → v10: clip time interpolation, Hold Filters, Field Options and audio source channels; the++/// Modify ▸ Audio Channels map; subclips' Restrict Trims flag. Existing data needs no change.++fn v9_to_v10(doc: Value) -> Result<Value, String> {++ Ok(doc)++}++#[cfg(test)]mod tests {use super::*;#[test]fn schema_version_matches_table() {-- assert_eq!(SCHEMA_VERSION, 9);++ assert_eq!(SCHEMA_VERSION, 10);}#[test]diff --cc crates/ui-egui/src/control.rsindex 53ed79381,f639b0798..9e39f018b--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@@ -158,21 -158,13 +158,28 @@@ pub fn handle(app: &mut FilmcraftApp, cif let Some(v) = p.get("safeMargins").and_then(Value::as_bool) {app.ui.program.safe_margins = v;}+ // Monitor view state (serde fields of `MonitorView`), merged into the current state.+ for k in ["program", "source"] {+ let Some(patch) = p.get(k).and_then(Value::as_object) else { continue };+ let mv = if k == "program" { &mut app.ui.program } else { &mut app.ui.source };+ let mut cur = serde_json::to_value(&*mv).unwrap_or_default();+ if let Some(o) = cur.as_object_mut() {+ for (f, v) in patch {+ o.insert(f.clone(), v.clone());+ }+ }+ match serde_json::from_value(cur) {+ Ok(m) => *mv = m,+ Err(e) => return err(format!("`{k}`: {e}")),+ }+ }+ // fields of the open Edit / Clip / File dialog (`panels::clip_dialogs`)+ if let Some(m) = p.get("clipDialog").and_then(Value::as_object) {+ let Some(d) = app.ui.clip_dialog.as_mut() else { return err("no clip dialog is open") };+ for (k, v) in m {+ d.params[k.as_str()] = v.clone();+ }+ }ok(Value::Null)}"ui.panel.show" | "ui.panel.close" => {diff --cc crates/ui-egui/src/menus.rsindex 807a4452d,7cd902ded..cb5096bd8--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -493,10 -397,30 +476,32 @@@ pub fn menu_bar(app: &mut FilmcraftApp}}+ /// One menu level: items whose path ends here, and a submenu (at its first item's position) for+ /// each deeper path segment, recursively (e.g. Clip ▸ Video Options ▸ Time Interpolation).+ fn menu_level(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: &mut Option<String>) {+ let mut subs: Vec<&str> = Vec::new();+ for it in items {+ if let Some(sub) = it.path.get(depth).map(String::as_str) {+ if subs.contains(&sub) {+ continue;+ }+ subs.push(sub);+ let inner: Vec<&MenuItem> = items.iter().copied().filter(|x| x.path.get(depth).map(String::as_str) == Some(sub)).collect();+ ui.menu_button(sub, |ui| {+ ui.set_min_width(220.0);+ menu_level(ui, &inner, depth + 1, clicked);+ });+ } else if menu_entry(ui, it) {+ *clicked = Some(it.id.clone());+ ui.close();+ }+ }+ }+fn menu_entry(ui: &mut egui::Ui, it: &MenuItem) -> bool {- let mut b = egui::Button::new(&it.label);+ // checkable items leave room for a checkmark drawn at the left+ let label = if it.checked.is_some() { format!(" {}", it.label) } else { it.label.clone() };+ let mut b = egui::Button::new(label);if let Some(s) = &it.shortcut {b = b.shortcut_text(shortcut_text(s));}diff --cc crates/ui-egui/src/panels/dialogs.rsindex 2763cbdd7,08e551e16..217c3353d--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@@ -6,9 -6,9 +6,10 @@@ use crate::{Dialog, FilmcraftApp}pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {crate::panels::media_dialogs::show(app, ctx);crate::panels::color_dialogs::show(app, ctx);+ crate::panels::clip_dialogs::show(app, ctx);crate::panels::presets::save_dialog(app, ctx);crate::panels::multicam::show_dialog(app, ctx);+ crate::panels::monitor_view::dialogs(app, ctx);let Some(d) = app.dialog else { return };if let Some(still_open) = crate::panels::file_dialogs::show(app, ctx, d) {if !still_open && app.dialog == Some(d) {diff --cc crates/ui-egui/src/state.rsindex 4eda7e155,fa704978f..ba71b96ea--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@@ -429,9 -325,23 +429,26 @@@ pub struct UiState/// Multi-Camera Record On/Off (key 0): playing in the Multi-Camera view records cuts.#[serde(default = "yes")]pub multicam_record: bool,+ /// Open guide dialog (Add Guide / Save Guides as Template / Manage Guides).+ #[serde(default)]+ pub guide_dialog: Option<GuideDialog>,+ /// Edit / Clip / File menu dialog (Paste Attributes, Make Subclip, Frame Hold Options, …;+ /// open when Some). See `panels::clip_dialogs`.+ #[serde(default)]+ pub clip_dialog: Option<ClipDialogDraft>,+ }++ /// An open Edit / Clip / File menu dialog: the engine command it runs on OK and the parameters+ /// being edited (the same JSON the command takes, so agents can fill it with `ui.set`).+ #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+ pub struct ClipDialogDraft {+ pub command: String,+ pub params: serde_json::Value,+ /// Extra data shown by the dialog (effect names, channel count, …); not sent.+ #[serde(default)]+ pub info: serde_json::Value,+ #[serde(default)]+ pub error: String,}/// A pen mask in progress: vertices placed so far, in clip pixels (`[x, y, tangent x, tangent y]`).@@@ -694,7 -584,7 +711,8 @@@ impl Default for UiStatesave_preset: None,sync_dialog: None,multicam_record: true,+ guide_dialog: None,+ clip_dialog: None,}}}diff --cc docs/control-protocol.mdindex 0061b76bc,bf91a96a4..b4ad1381d--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@@ -19,7 -19,7 +19,7 @@@ Methods (handlers in `crates/ui-egui/sr| `engine.commands` / `ui.menu.list` | – | command registry / menu tree || `ui.inspect` | – | UI state (tool, workspace, dock, timeline view, playback, fps…) || `ui.elements` | `{prefix?}` | every on-screen interactive element: id, label, rect |- | `ui.set` | `{tool, workspace, mode, theme, focused, playbackRes, timeline:{pps,scroll,fit}, program:{…}, source:{…}}` | `program` / `source` merge fields into the monitor view state (`res`, `paused_res`, `high_quality`, `display`, `zoom`, `pan`, `show_rulers`, `show_guides`, `lock_guides`, `snap`, `guides`, `compare_ref`, …; see [monitors.md](monitors.md)) |-| `ui.set` | `{tool, workspace, mode, theme, focused, playbackRes, timeline:{pps,scroll,fit}, clipDialog:{param: value}}` | `clipDialog` sets fields of the open Edit / Clip / File dialog (Paste Attributes, Make Subclip, Frame Hold Options, …) |++| `ui.set` | `{tool, workspace, mode, theme, focused, playbackRes, timeline:{pps,scroll,fit}, program:{…}, source:{…}, clipDialog:{param: value}}` | `program` / `source` merge fields into the monitor view state (`res`, `paused_res`, `high_quality`, `display`, `zoom`, `pan`, `show_rulers`, `show_guides`, `lock_guides`, `snap`, `guides`, `compare_ref`, …; see [monitors.md](monitors.md)); `clipDialog` sets fields of the open Edit / Clip / File dialog (Paste Attributes, Make Subclip, Frame Hold Options, …) || `ui.panel.show` / `ui.panel.close` | `{panel}` | || `ui.click` / `ui.move` | `{id}` or `{x,y}`, `button`, `count`, `modifiers` | synthetic pointer input || `ui.drag` | `{from, to, steps, modifiers}` | press–move–release |diff --cc docs/project-files.mdindex 56df29e58,f1077a9ec..4d1424d43--- a/docs/project-files.md+++ b/docs/project-files.md@@@ -8,7 -8,7 +8,7 @@@ writing them is `crates/format` (`filmc```json{"format": "filmcraft.project",-- "schema_version": 9,++ "schema_version": 10,"generator": "FilmCraft 0.1.0","project": { "name": "…", "settings": { … }, "root": { … }, "items": { … }, "next_id": 48 }}@@@ -32,7 -32,7 +32,8 @@@| 6 | M11.7/M11.9 | media identity fingerprints, ingest settings; no-op step || 7 | M5.5 | effect masks: `masks` on effect instances with keyframable Bézier `Path` values; no-op step || 8 | M12 | multi-camera source sequences and clips, merged clips; no-op step |-| 9 | M3.10 | clip time interpolation, Hold Filters, Field Options, audio source channels, Modify ▸ Audio Channels map, subclip Restrict Trims; no-op step |+| 9 | M10.5 | transcripts of media items (`project.transcripts`); no-op step |++| 10 | M3.10 | clip time interpolation, Hold Filters, Field Options, audio source channels, Modify ▸ Audio Channels map, subclip Restrict Trims; no-op step |### Migrations@@@ -60,8 -60,8 +61,8 @@@ on disk is unchanged until you save. ThA file with a `schema_version` newer than the build supports is **refused**, not half-read:--> this project was saved by a newer version of FilmCraft (project schema v10); this build reads up to--> v9. Update FilmCraft to open it.++> this project was saved by a newer version of FilmCraft (project schema v11); this build reads up to++> v10. Update FilmCraft to open it.Reading it partially and saving it back would silently drop whatever the newer version added.