Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

Merge origin/main into multi-stream audio

Brandon Thomas701d7c7111c5
diff --cc crates/codecs/src/mkv.rs
index b39801618,e1fa14824..9f96df446
--- a/crates/codecs/src/mkv.rs
+++ b/crates/codecs/src/mkv.rs
@@@ -54,18 -46,53 +57,49 @@@ pub struct MkvSource
/// Video codec as an ISO-BMFF sample entry (for the decoder factories).
ventry: Option<SampleEntry>,
video: GopCache,
- audio: Mutex<AudioState>,
- /// Audio packet start positions in source sample frames.
- audio_starts: Vec<i64>,
- /// Decoder pre-roll after a seek, in source sample frames (0: prime with one packet).
- audio_preroll: i64,
+ /// The playable audio tracks in file order: `info.audio_streams[k]` describes `audios[k]`.
+ audios: Vec<MkvAudio>,
}
+ /// Audio packet start positions in source sample frames.
+ ///
+ /// Block timestamps are quantised to `TimestampScale` (usually 1 ms), so they are only accurate to a
+ /// tick: a 1024-sample AAC frame at 48 kHz lasts 21.33 ms. Packets that all decode to the same
+ /// length (AAC, MPEG audio, AC-3) therefore run on from one another, resynchronising to the
+ /// timestamp only across gaps of more than half a packet (and more than two ticks); see
+ /// [`crate::audio::contiguous_starts`]. Opus packets: [`opus_starts`]. Other codecs start at their
+ /// timestamps.
+ fn audio_starts(file: &MkvFile, bytes: &crate::Src, ti: usize, rate: i64) -> Vec<i64> {
+ use crate::audio::{FixedFrames, PacketTime, contiguous_starts, fixed_packet_samples};
+ let Some(t) = file.tracks.get(ti) else { return Vec::new() };
+ if let Some(h) = opus_head(&t.codec) {
+ return opus_starts(file, bytes, ti, &h, rate);
+ }
+ let (n, d) = tb(t);
+ let at = |pts: i64| (pts as i128 * n as i128 * rate as i128 / d as i128) as i64;
+ let first = || file.read_sample(bytes, ti, 0).unwrap_or_default();
+ let out_rate = u32::try_from(rate).unwrap_or(0);
+ let frame = match &t.codec {
+ Codec::Aac { asc } => fixed_packet_samples(FixedFrames::Aac(asc), &[], out_rate),
+ Codec::Mp3 | Codec::Mp2 => fixed_packet_samples(FixedFrames::MpegAudio, &first(), out_rate),
+ Codec::Ac3 => fixed_packet_samples(FixedFrames::Ac3, &first(), out_rate),
+ _ => None,
+ };
+ let Some(frame) = frame else {
+ return t.samples.iter().map(|s| at(s.pts)).collect();
+ };
+ let packets = t.samples.iter().map(|s| PacketTime { stamp: at(s.pts), stamped: own_stamp(s), samples: Some(frame) });
+ contiguous_starts(packets, (frame / 2).max(stamp_tolerance(t, rate)))
+ }
+
/// Sample-exact Opus packet start positions (48 kHz frames, pre-skip removed).
///
- /// Block timestamps are quantised to `TimestampScale` (usually 1 ms) and the demuxer subtracts a
- /// rounded `CodecDelay`, so they are only accurate to a tick. Starts are therefore accumulated from
- /// each packet's TOC duration, resynchronising to the timestamp only across real gaps (more than
- /// two ticks off). Pre-skip is the exact `CodecDelay` (or the header's pre-skip when it is absent).
+ /// The demuxer also subtracts a rounded `CodecDelay` from the timestamps. Starts are accumulated
+ /// from each packet's TOC duration, resynchronising to the timestamp only across real gaps (more
+ /// than two ticks off). Pre-skip is the exact `CodecDelay` (or the header's pre-skip when it is
+ /// absent).
fn opus_starts(file: &MkvFile, bytes: &crate::Src, ti: usize, head: &filmcraft_opus::OpusHead, rate: i64) -> Vec<i64> {
- let t = &file.tracks[ti];
+ let Some(t) = file.tracks.get(ti) else { return Vec::new() };
let (n, d) = tb(t);
let scale_ns = (n as i128 * 1_000_000_000 / d as i128).max(1);
let delay_ns = t.codec_delay_ns as i128;
@@@ -329,20 -350,12 +368,15 @@@ impl MkvSource
start_timecode: None,
file_size: Some(bytes.0.len()),
};
- let audio_starts = atrack.map(|i| audio_starts(&file, &bytes, i, info.audio.as_ref().map_or(48_000, |a| a.sample_rate) as i64)).unwrap_or_default();
- let audio_preroll = atrack
- .map(|i| {
- let t = &file.tracks[i];
- let rate = info.audio.as_ref().map_or(48_000, |a| a.sample_rate) as i64;
- match t.codec {
+ // `info.audio_streams[k]` was made from `atracks[k]`, so the two stay index-aligned
+ let audios: Vec<MkvAudio> = atracks
+ .iter()
+ .zip(&info.audio_streams)
+ .filter_map(|(&i, ainfo)| {
+ let t = file.tracks.get(i)?;
+ let rate = ainfo.sample_rate as i64;
- let (n, d) = tb(t);
- let at = |pts: i64| (pts as i128 * n as i128 * rate as i128 / d as i128) as i64;
- let starts = match opus_head(&t.codec) {
- Some(h) => opus_starts(&file, &bytes, i, &h, rate),
- None => t.samples.iter().map(|s| at(s.pts)).collect(),
- };
++ let starts = audio_starts(&file, &bytes, i, rate);
+ let preroll = match t.codec {
Codec::Opus { .. } => {
let container = (t.seek_pre_roll_ns as u128 * rate as u128).div_ceil(1_000_000_000) as i64;
container.max(crate::audio::OPUS_PRE_ROLL as i64 * rate / 48_000)
diff --cc crates/codecs/src/mp4.rs
index 65eff7726,2cdcad31f..e48670dfa
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@@ -29,19 -29,6 +29,19 @@@ struct AudioState
last_decoded: Option<usize>,
}
+/// One playable audio track with its own decoder state and timing tables.
+struct Mp4Audio {
+ /// Index into `Mp4File::tracks`.
+ track: usize,
+ state: Mutex<AudioState>,
- /// Cumulative sample start frames for the track (for packet lookup).
++ /// Packet start positions in source sample frames (see [`audio_starts`]).
+ starts: Vec<i64>,
+ /// Presentation offset of the track in its timescale (edit list, or Opus pre-skip).
+ offset: i64,
- /// Decoder pre-roll after a seek, in track timescale units (0: prime with one packet).
++ /// Decoder pre-roll after a seek, in source sample frames (0: prime with one packet).
+ preroll: i64,
+}
+
pub struct Mp4Source {
info: MediaInfo,
bytes: crate::Src,
@@@ -204,11 -229,37 +238,11 @@@ impl Mp4Source
}
info
});
- let audio = atrack.map(|i| {
- let t = &file.tracks[i];
- let entry = &t.entries[0];
- let ap = entry.audio.clone().unwrap_or_default();
- let (rate, ch, bits) = match &entry.codec {
- CodecConfig::Aac(a) => (
- {
- // HE-AAC plays at twice the core rate the AudioSpecificConfig starts with
- // an AAC access unit is at most 6144 bits per channel: a hostile `stsz` can't make us read more
- let units = t
- .samples
- .iter()
- .take(8)
- .filter_map(|x| filmcraft_media::reader::read_range(&*bytes.0, x.offset, (x.size as usize).min(MAX_AAC_PROBE_UNIT)).ok());
- let units: Vec<Vec<u8>> = units.collect();
- match crate::audio::aac_output_rate(&a.asc, units.iter().map(Vec::as_slice)) {
- Some(r) => r,
- None if a.sample_rate > 0 => a.sample_rate,
- None => ap.sample_rate as u32,
- }
- },
- if a.channel_config > 0 { a.channel_config as u32 } else { ap.channels },
- None,
- ),
- CodecConfig::Pcm(p) => (p.sample_rate as u32, p.channels, Some(p.bits as u32)),
- CodecConfig::Opus(o) => (crate::audio::OPUS_RATE, (o.output_channels as u32).max(1), None),
- _ => (if ap.sample_rate > 0.0 { ap.sample_rate as u32 } else { t.timescale }, ap.channels.max(1), None),
- };
- AudioStreamInfo { sample_rate: rate.max(1), channels: ch.max(1), codec: codec_label(&entry.codec), bits_per_sample: bits }
- });
- let duration = vtrack.or(atrack).and_then(|i| file.tracks.get(i)).map(|t| presentation_duration(&file, t)).unwrap_or_default();
+ // one entry per playable audio track (`playable` guarantees a sample description); a track
+ // that somehow has none is dropped so `audio_streams` and `audios` stay index-aligned
- let atracks: Vec<usize> = atracks.into_iter().filter(|&i| file.tracks.get(i).is_some_and(|t| !t.entries.is_empty())).collect();
- let audio_streams: Vec<AudioStreamInfo> = atracks.iter().filter_map(|&i| file.tracks.get(i)).filter_map(|t| audio_stream_info(t, &bytes)).collect();
++ let (atracks, audio_streams): (Vec<usize>, Vec<AudioStreamInfo>) =
++ atracks.into_iter().filter_map(|i| Some((i, audio_stream_info(file.tracks.get(i)?, &bytes)?))).unzip();
+ let duration = vtrack.or(atracks.first().copied()).and_then(|i| file.tracks.get(i)).map(|t| presentation_duration(&file, t)).unwrap_or_default();
let start_timecode = file.tracks.iter().find_map(|t| match t.codec() {
Some(CodecConfig::Timecode(tc)) => tc.start_frame.map(|f| f as i64),
_ => None,
@@@ -223,33 -274,34 +257,26 @@@
start_timecode,
file_size: Some(bytes.0.len()),
};
- let audio_rate = info.audio.as_ref().map_or(48_000, |a| a.sample_rate);
- let audio_starts = atrack.map(|i| audio_starts(&file, &bytes, i, audio_rate)).unwrap_or_default();
- let (audio_offset, audio_preroll) = atrack
- .map(|i| {
- let t = &file.tracks[i];
+ let audios: Vec<Mp4Audio> = atracks
+ .iter()
- .filter_map(|&i| {
++ .zip(&info.audio_streams)
++ .filter_map(|(&i, ainfo)| {
+ let t = file.tracks.get(i)?;
- let mut acc = 0i64;
- let starts = t
- .samples
- .iter()
- .map(|s| {
- let st = acc;
- acc = acc.saturating_add(s.duration as i64);
- st
- })
- .collect();
++ let starts = audio_starts(&file, &bytes, i, ainfo.sample_rate);
let ts = t.timescale.max(1) as i64;
- match &t.entries[0].codec {
- CodecConfig::Opus(o) => {
+ let (offset, preroll) = match t.entries.first().map(|e| &e.codec) {
+ Some(CodecConfig::Opus(o)) => {
let off = if t.edit_offset != 0 { t.edit_offset } else { -(o.pre_skip as i64) * ts / 48_000 };
- (off, (crate::audio::OPUS_PRE_ROLL as u64 * ts as u64).div_ceil(48_000) as i64)
+ // (Opus plays at 48 kHz: the pre-roll is in its sample frames)
+ (off, crate::audio::OPUS_PRE_ROLL as i64)
}
_ => (t.edit_offset, 0),
- }
+ };
+ let state = Mutex::new(AudioState { decoder: None, packets: HashMap::new(), order: Vec::new(), last_decoded: None });
+ Some(Mp4Audio { track: i, state, starts, offset, preroll })
})
- .unwrap_or((0, 0));
- Ok(Self {
- info,
- bytes,
- file,
- vtrack,
- atrack,
- video: GopCache::new(explicit_color).with_rotation(rotation),
- audio: Mutex::new(AudioState { decoder: None, packets: HashMap::new(), order: Vec::new(), last_decoded: None }),
- audio_starts,
- audio_offset,
- audio_preroll,
- })
+ .collect();
+ Ok(Self { info, bytes, file, vtrack, video: GopCache::new(explicit_color).with_rotation(rotation), audios })
}
fn read(&self, track: usize, i: usize) -> crate::Result<Vec<u8>> {
@@@ -369,18 -413,15 +396,15 @@@ impl MediaSource for Mp4Source
let ratio = src_rate as f64 / sample_rate as f64;
let p0 = (start as f64 * ratio).floor() as i64;
// (in i128: a hostile edit list can make the offset large enough to overflow i64)
- let offset = i128::from(self.audio_offset) * i128::from(src_rate) / i128::from(track.timescale.max(1));
+ let offset = i128::from(a.offset) * i128::from(src_rate) / i128::from(track.timescale.max(1));
let s0 = i64::try_from(i128::from(p0) - offset).unwrap_or(if offset > 0 { i64::MIN } else { i64::MAX });
let need = (frames as f64 * ratio).ceil() as i64 + 2;
- // Samples-per-unit: the track timescale is usually the sample rate for audio.
- let unit = src_rate as f64 / track.timescale.max(1) as f64;
let mut src: Vec<Vec<f32>> = vec![vec![0.0; need.max(0) as usize]; ch];
- let mut st = self.audio.lock().unwrap_or_else(|e| e.into_inner());
- let first = self.audio_starts.partition_point(|&x| x <= s0.max(0)).saturating_sub(1);
+ let mut st = a.state.lock().unwrap_or_else(|e| e.into_inner());
- let first = a.starts.partition_point(|&x| (x as f64 * unit) as i64 <= s0.max(0)).saturating_sub(1);
++ let first = a.starts.partition_point(|&x| x <= s0.max(0)).saturating_sub(1);
let mut i = first;
while i < track.samples.len() {
- let Some(&start_units) = a.starts.get(i) else { break };
- let pk_start = (start_units as f64 * unit) as i64;
- let pk_start = self.audio_starts[i];
++ let Some(&pk_start) = a.starts.get(i) else { break };
if pk_start >= s0.saturating_add(need) {
break;
}
diff --cc crates/codecs/tests/matroska_audio_oracle.rs
index 000000000,c1726fd8c..1298ccd48
mode 000000,100644..100644
--- a/crates/codecs/tests/matroska_audio_oracle.rs
+++ b/crates/codecs/tests/matroska_audio_oracle.rs
@@@ -1,0 -1,50 +1,50 @@@
+ //! Matroska audio made by ffmpeg, against ffmpeg's decode (#236). ffmpeg stamps blocks to the
+ //! millisecond, so at 44.1 kHz AAC (1024-sample), MP3 (1152) and AC-3 (1536) packets are each
+ //! stamped up to half a millisecond off their exact start. Read back block by block, as playback
+ //! reads it, a tone must stay as smooth as ffmpeg's decode of it: no holes or overlaps between
+ //! packets.
+
+ mod common;
+
+ use common::*;
+
+ /// Largest |second difference| of `x` from `from` on: a click shows up as a spike.
+ fn roughness(x: &[f32], from: usize) -> f32 {
+ x.windows(3).skip(from).map(|w| (w[0] - 2.0 * w[1] + w[2]).abs()).fold(0.0, f32::max)
+ }
+
+ #[test]
+ fn matroska_audio_plays_without_holes() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let cases: [(&str, u32, &[&str]); 5] = [
+ ("tone_aac_48k.mkv", 48_000, &["-c:a", "aac", "-b:a", "160k"]),
+ ("tone_aac_44k.mkv", 44_100, &["-c:a", "aac", "-b:a", "160k"]),
+ ("tone_mp3_44k.mkv", 44_100, &["-c:a", "libmp3lame", "-b:a", "192k"]),
+ ("tone_mp2_44k.mkv", 44_100, &["-c:a", "mp2", "-b:a", "192k"]),
+ ("tone_ac3_44k.mkv", 44_100, &["-c:a", "ac3", "-b:a", "192k"]),
+ ];
+ for (name, rate, codec) in cases {
+ let input = format!("sine=frequency=440:sample_rate={rate}:duration=3");
+ let args: Vec<&str> = ["-f", "lavfi", "-i", input.as_str(), "-af", "volume=4"].iter().copied().chain(codec.iter().copied()).collect();
+ let Some(path) = fixture(&ff, name, &args) else {
+ eprintln!("SKIPPED ({name}): this ffmpeg can't encode it");
+ continue;
+ };
+ let src = filmcraft_codecs::open_bytes(name, bytes(&path)).unwrap();
- assert_eq!(src.info().audio.as_ref().map(|a| a.sample_rate), Some(rate), "{name}");
++ assert_eq!(src.info().audio().map(|a| a.sample_rate), Some(rate), "{name}");
+ let frames = rate as usize * 29 / 10;
+ let mut ours = Vec::with_capacity(frames);
+ while ours.len() < frames {
+ let n = 512.min(frames - ours.len());
+ ours.extend_from_slice(&src.audio(ours.len() as i64, n, rate).unwrap().channels[0]);
+ }
+ let theirs = ffmpeg_audio_f32(&ff, &path, &[]);
+ // past the codecs' start-up (priming, MP3's first frame)
+ let skip = rate as usize / 10;
+ let (r_ours, r_theirs) = (roughness(&ours, skip), roughness(&theirs[..theirs.len().min(frames)], skip));
+ let peak = ours.iter().skip(skip).fold(0f32, |m, x| m.max(x.abs()));
+ println!("{name}: peak {peak:.3}, max |second difference| ours {r_ours:.5}, ffmpeg {r_theirs:.5}");
+ assert!(peak > 0.4, "{name}: the tone is missing (peak {peak})");
+ assert!(r_ours < 2.0 * r_theirs + 0.005, "{name}: clicks between packets (|Δ²| {r_ours} vs ffmpeg's {r_theirs})");
+ }
+ }
diff --cc crates/edit/src/frame_size.rs
index 000000000,607cfe40d..90585c9cd
mode 000000,100644..100644
--- a/crates/edit/src/frame_size.rs
+++ b/crates/edit/src/frame_size.rs
@@@ -1,0 -1,212 +1,213 @@@
+ //! Sequence Settings ▸ "Scale motion effects proportionally when changing frame size".
+ //!
+ //! Motion's Position is in sequence pixels and its Scale is relative to the source, so a new frame
+ //! size leaves every clip where it was in pixels: smaller and off-centre in a larger frame, cropped
+ //! in a smaller one. With the option on, the whole picture scales instead, by one factor about the
+ //! frame centre. On an aspect change (16:9 → 9:16) that factor is the one that fits the old frame
+ //! inside the new one (`min(W1/W0, H1/H0)`), so nothing is cropped and the old composition sits
+ //! centred, letterboxed or pillarboxed, rather than filling the new frame.
+
+ use filmcraft_project::{ParamValue, Sequence, TrackKind};
+
+ /// Motion Scale's upper bound (the parameter's range, in %).
+ const MAX_SCALE: f64 = 10_000.0;
+
+ /// The uniform factor `k` and the old and new frame centres for `from` → `to`, or `None` for an
+ /// empty frame on either side.
+ fn fit(from: (u32, u32), to: (u32, u32)) -> Option<(f64, (f64, f64), (f64, f64))> {
+ if from.0 == 0 || from.1 == 0 || to.0 == 0 || to.1 == 0 {
+ return None;
+ }
+ let (w0, h0, w1, h1) = (f64::from(from.0), f64::from(from.1), f64::from(to.0), f64::from(to.1));
+ let k = (w1 / w0).min(h1 / h0);
+ (k.is_finite() && k > 0.0).then_some((k, (w0 / 2.0, h0 / 2.0), (w1 / 2.0, h1 / 2.0)))
+ }
+
+ /// Rescale the Motion of every video clip in `seq` for a frame-size change from `from` to `to`:
+ /// static values and every keyframe. Returns how many clips were rescaled (0 when the size does not
+ /// change).
+ ///
+ /// - Position maps through `p' = c1 + k·(p − c0)`. An automatic (NaN) position stays automatic: it
+ /// follows the frame centre on its own.
+ /// - Scale and Scale Width are multiplied by `k`, up to the parameter's 10 000 %. A clip with Scale to
+ /// Frame Size keeps its Scale, because the renderer refits it to the new frame anyway.
+ /// - Anchor Point (source pixels) and Rotation do not depend on the frame size and stay as they are.
+ /// - Only the intrinsic Motion effect changes, as the option's name says: the points of standard
+ /// effects (a Mirror centre, the Transform effect's Position) keep their pixel values.
+ pub fn scale_motion(seq: &mut Sequence, from: (u32, u32), to: (u32, u32)) -> usize {
+ if from == to {
+ return 0;
+ }
+ let Some((k, c0, c1)) = fit(from, to) else { return 0 };
+ let mut n = 0;
+ for track in seq.all_tracks_mut().filter(|t| t.kind == TrackKind::Video) {
+ for item in &mut track.items {
+ let refits = item.scale_to_frame;
+ let Some(motion) = item.effect_mut("motion") else { continue };
+ if let Some(p) = motion.param_mut("position") {
+ p.map_values(|v| match v {
+ ParamValue::Vec2(mut v) => {
+ v.x = c1.0 + k * (v.x - c0.0);
+ v.y = c1.1 + k * (v.y - c0.1);
+ ParamValue::Vec2(v)
+ }
+ other => other,
+ });
+ }
+ if !refits {
+ for id in ["scale", "scale_width"] {
+ if let Some(p) = motion.param_mut(id) {
+ p.map_values(|v| match v {
+ ParamValue::Float(s) => ParamValue::Float((s * k).clamp(0.0, MAX_SCALE)),
+ other => other,
+ });
+ }
+ }
+ }
+ n += 1;
+ }
+ }
+ n
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+ use filmcraft_project::{ClipId, ItemId, Keyframe, Label, Project, SequenceSettings, TrackItem, find_effect};
+ use filmcraft_time::Tick;
+
+ fn seq_with(items: Vec<TrackItem>) -> Sequence {
+ let mut p = Project::new("t");
+ let s = p.new_sequence("s", SequenceSettings::default(), 2, 1, None);
+ let mut seq = p.sequence(s).unwrap().clone();
+ seq.video_tracks[0].items = items;
+ seq
+ }
+
+ fn clip(id: u64, pos: (f64, f64), scale: f64) -> TrackItem {
+ let mut motion = find_effect("motion").unwrap().instance();
+ motion.param_mut("position").unwrap().value = ParamValue::Vec2(filmcraft_geom::Vec2::new(pos.0, pos.1));
+ motion.param_mut("scale").unwrap().value = ParamValue::Float(scale);
+ TrackItem {
+ id: ClipId(id),
+ item: ItemId(1),
+ name: format!("c{id}"),
+ label: Label::Iris,
+ start: Tick(id as i64 * 1_000_000_000_000),
+ duration: Tick(1_000_000_000_000),
+ source_in: Tick::ZERO,
+ speed: 1.0,
+ reverse: false,
+ enabled: true,
+ link: None,
+ group: None,
+ effects: vec![motion],
+ 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(),
++ audio_stream: 0,
+ graphic: None,
+ }
+ }
+
+ fn pos(seq: &Sequence, i: usize) -> (f64, f64) {
+ match seq.video_tracks[0].items[i].effect("motion").unwrap().param("position").unwrap().value {
+ ParamValue::Vec2(v) => (v.x, v.y),
+ _ => panic!("position is a point"),
+ }
+ }
+
+ fn scale(seq: &Sequence, i: usize) -> f64 {
+ match seq.video_tracks[0].items[i].effect("motion").unwrap().param("scale").unwrap().value {
+ ParamValue::Float(s) => s,
+ _ => panic!("scale is a number"),
+ }
+ }
+
+ fn close(a: (f64, f64), b: (f64, f64)) -> bool {
+ (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9
+ }
+
+ #[test]
+ fn same_aspect_scales_position_and_scale_together() {
+ let mut seq = seq_with(vec![clip(1, (960.0, 540.0), 100.0), clip(2, (300.0, 90.0), 50.0)]);
+ assert_eq!(scale_motion(&mut seq, (1920, 1080), (1280, 720)), 2);
+ assert!(close(pos(&seq, 0), (640.0, 360.0)), "{:?}", pos(&seq, 0));
+ assert!(close(pos(&seq, 1), (200.0, 60.0)), "{:?}", pos(&seq, 1));
+ assert!((scale(&seq, 0) - 100.0 * 2.0 / 3.0).abs() < 1e-9);
+ assert!((scale(&seq, 1) - 50.0 * 2.0 / 3.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn aspect_change_fits_the_old_frame_inside_the_new_one() {
+ // 1920x1080 -> 1080x1920: k = min(1080/1920, 1920/1080) = 0.5625, centred
+ let mut seq = seq_with(vec![clip(1, (960.0, 540.0), 100.0), clip(2, (0.0, 0.0), 100.0)]);
+ scale_motion(&mut seq, (1920, 1080), (1080, 1920));
+ assert!(close(pos(&seq, 0), (540.0, 960.0)), "{:?}", pos(&seq, 0));
+ // the old top-left corner lands on the new frame's left edge, letterboxed vertically
+ assert!(close(pos(&seq, 1), (0.0, 960.0 - 0.5625 * 540.0)), "{:?}", pos(&seq, 1));
+ assert!((scale(&seq, 0) - 56.25).abs() < 1e-9);
+ }
+
+ #[test]
+ fn keyframes_scale_too() {
+ let mut c = clip(1, (960.0, 540.0), 100.0);
+ let m = c.effect_mut("motion").unwrap();
+ m.param_mut("position").unwrap().keyframes = vec![
+ Keyframe::new(Tick::ZERO, ParamValue::Vec2(filmcraft_geom::Vec2::new(0.0, 0.0))),
+ Keyframe::new(Tick(10), ParamValue::Vec2(filmcraft_geom::Vec2::new(1920.0, 1080.0))),
+ ];
+ m.param_mut("scale").unwrap().keyframes = vec![Keyframe::new(Tick::ZERO, ParamValue::Float(100.0)), Keyframe::new(Tick(10), ParamValue::Float(200.0))];
+ let mut seq = seq_with(vec![c]);
+ scale_motion(&mut seq, (1920, 1080), (3840, 2160));
+ let m = seq.video_tracks[0].items[0].effect("motion").unwrap();
+ let kp: Vec<_> = m.param("position").unwrap().keyframes.iter().map(|k| k.value.clone()).collect();
+ assert_eq!(kp, vec![ParamValue::Vec2(filmcraft_geom::Vec2::new(0.0, 0.0)), ParamValue::Vec2(filmcraft_geom::Vec2::new(3840.0, 2160.0))]);
+ let ks: Vec<_> = m.param("scale").unwrap().keyframes.iter().map(|k| k.value.clone()).collect();
+ assert_eq!(ks, vec![ParamValue::Float(200.0), ParamValue::Float(400.0)]);
+ }
+
+ #[test]
+ fn automatic_position_stays_automatic() {
+ let mut seq = seq_with(vec![clip(1, (f64::NAN, f64::NAN), 100.0)]);
+ scale_motion(&mut seq, (1920, 1080), (1280, 720));
+ let (x, y) = pos(&seq, 0);
+ assert!(x.is_nan() && y.is_nan());
+ assert!((scale(&seq, 0) - 100.0 * 2.0 / 3.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn scale_to_frame_clips_keep_their_scale_but_move() {
+ let mut c = clip(1, (480.0, 270.0), 100.0);
+ c.scale_to_frame = true;
+ let mut seq = seq_with(vec![c]);
+ scale_motion(&mut seq, (1920, 1080), (3840, 2160));
+ assert!(close(pos(&seq, 0), (960.0, 540.0)), "{:?}", pos(&seq, 0));
+ assert_eq!(scale(&seq, 0), 100.0);
+ }
+
+ #[test]
+ fn scale_is_capped_at_the_parameter_range() {
+ let mut seq = seq_with(vec![clip(1, (1.0, 1.0), 5000.0)]);
+ scale_motion(&mut seq, (2, 2), (8, 8));
+ assert_eq!(scale(&seq, 0), MAX_SCALE);
+ }
+
+ #[test]
+ fn same_size_or_empty_frame_changes_nothing() {
+ let mut seq = seq_with(vec![clip(1, (100.0, 100.0), 100.0)]);
+ let before = seq.clone();
+ assert_eq!(scale_motion(&mut seq, (1920, 1080), (1920, 1080)), 0);
+ assert_eq!(scale_motion(&mut seq, (0, 1080), (1280, 720)), 0);
+ assert_eq!(scale_motion(&mut seq, (1920, 1080), (1280, 0)), 0);
+ // Debug, not ==: the automatic anchor is NaN, which never equals itself
+ assert_eq!(format!("{:?}", seq.video_tracks[0].items[0].effects), format!("{:?}", before.video_tracks[0].items[0].effects));
+ }
+ }
diff --cc crates/render/src/audio.rs
index f05888183,20cf73558..404ee794f
--- a/crates/render/src/audio.rs
+++ b/crates/render/src/audio.rs
@@@ -338,6 -338,18 +338,18 @@@ pub fn clip_signal(item: &TrackItem, st
Some(out)
}
+ /// Whether a clip plays one source channel on both sides: a mono source, or one picked channel
+ /// (Modify ▸ Audio Channels, Breakout to Mono). Loudness Auto-Match measures such a clip as the one
+ /// channel it is, as BS.1770 (and ffmpeg's `ebur128`) measure a mono programme, not as the
+ /// dual-mono pair [`clip_signal`] plays, which reads 3 LU louder. `None` when the clip has no
+ /// audio source.
+ pub fn clip_is_mono(item: &TrackItem, sources: &dyn SourceProvider) -> Option<bool> {
+ let src = sources.source(item.item)?;
- let available = src.info().audio.as_ref()?.channels as usize;
++ let available = src.info().audio_streams.get(item.audio_stream)?.channels as usize;
+ let (left, right) = source_pair(item, available);
+ Some(left == right)
+ }
+
/// The clip's audio (after speed/reverse) for timeline samples `[x0, x0 + len)` as `w` channels
/// (2: stereo, mono sources on both sides; 6: 5.1), with silence outside the clip.
fn raw_channels(item: &TrackItem, src: SourceAudio, x0: i64, len: usize, sr: u32, w: usize) -> Vec<Vec<f32>> {
diff --cc crates/ui-egui/src/panels/misc.rs
index 040aa590c,e42a9f09c..63e494b84
--- a/crates/ui-egui/src/panels/misc.rs
+++ b/crates/ui-egui/src/panels/misc.rs
@@@ -145,17 -145,17 +145,17 @@@ pub fn info(app: &mut FilmcraftApp, ui
};
if let Some(item) = app.session.state.project_selection.first().and_then(|i| app.session.project.item(*i)).cloned() {
ui.label(egui::RichText::new(&item.name).strong());
- line(ui, "Type:", item.type_label().to_string());
+ line(ui, tl!("Type:"), crate::i18n::t(item.type_label()).to_string());
if let Some(m) = item.as_media() {
if let Some(v) = &m.info.video {
- line(ui, "Video:", format!("{} fps, {} x {} ({:.4})", v.frame_rate.label(), v.width, v.height, v.par.0 as f32 / v.par.1 as f32));
- line(ui, "Codec:", v.codec.clone());
+ line(ui, tl!("Video:"), format!("{} fps, {} x {} ({:.4})", v.frame_rate.label(), v.width, v.height, v.par.0 as f32 / v.par.1 as f32));
+ line(ui, tl!("Codec:"), v.codec.clone());
}
- if let Some(a) = &m.info.audio {
+ if let Some(a) = m.info.audio() {
- line(ui, "Audio:", format!("{} Hz - {} ch - {}", a.sample_rate, a.channels, a.codec));
+ line(ui, tl!("Audio:"), format!("{} Hz - {} ch - {}", a.sample_rate, a.channels, a.codec));
}
}
- line(ui, "Duration:", format_time(item.duration(), item.frame_rate(), false, TimeDisplay::Timecode, 48000));
+ line(ui, tl!("Duration:"), format_time(item.duration(), item.frame_rate(), false, TimeDisplay::Timecode, 48000));
ui.separator();
}
if let Some(seq) = app.session.active_sequence() {
diff --cc crates/ui-egui/src/panels/timeline_hit.rs
index 000000000,f8bb64c21..fa536c774
mode 000000,100644..100644
--- a/crates/ui-egui/src/panels/timeline_hit.rs
+++ b/crates/ui-egui/src/panels/timeline_hit.rs
@@@ -1,0 -1,434 +1,435 @@@
+ //! What a press on the Timeline grabs (#259).
+ //!
+ //! Pure geometry and rules, shared by the cursor, the hover bracket, the press handler and the
+ //! control channel's `ui.timeline.hit`, so what the pointer shows is what a press does.
+
+ use std::cmp::Ordering;
+
+ use egui::{Modifiers, Pos2};
+ use filmcraft_edit::Edge;
+ use filmcraft_project::{ClipId, Sequence, Track, TrackId, TransitionId};
+
+ use super::timeline::Layout;
+ use crate::state::Tool;
+
+ /// How close (px) to a cut the Selection tool rolls instead of rippling when Settings ▸ Trim ▸
+ /// "Allow Selection tool to choose Roll and Ripple trims without modifier key" is on.
+ pub const ROLL_PX: f32 = 2.5;
+
+ /// Widest an edge zone gets (px), on each side of a clip edge.
+ pub const EDGE_PX: f32 = 7.0;
+
+ /// The trim the Selection tool starts at an edit point: Cmd+Shift = roll, Cmd = ripple. With the
+ /// Trim setting on (`no_modifier`), no modifier is needed: right on the cut (when a clip is on the
+ /// other side) rolls, elsewhere on the edge ripples. Otherwise a plain drag is a regular trim.
+ pub fn selection_trim_kind(no_modifier: bool, cmd: bool, shift: bool, dist_px: f32, has_neighbour: bool) -> &'static str {
+ if cmd && shift {
+ "roll"
+ } else if cmd {
+ "ripple"
+ } else if no_modifier {
+ if has_neighbour && dist_px <= ROLL_PX { "roll" } else { "ripple" }
+ } else {
+ "trim"
+ }
+ }
+
+ /// Distance (px) from `x` to the cut at `clip`'s `edge`, and whether a clip touches that cut on
+ /// the other side.
+ pub(crate) fn edge_geometry(seq: &Sequence, layout: &Layout, track: TrackId, clip: ClipId, edge: Edge, x: f32) -> (f32, bool) {
+ let Some(tr) = seq.track(track) else { return (f32::MAX, false) };
+ let Some(it) = tr.item(clip) else { return (f32::MAX, false) };
+ let (cut, neighbour) = match edge {
+ Edge::Out => (it.end(), tr.items.iter().any(|x| x.start == it.end())),
+ Edge::In => (it.start, tr.items.iter().any(|x| x.end() == it.start)),
+ };
+ ((layout.x_of(cut) - x).abs(), neighbour)
+ }
+
+ /// What is at a screen point.
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ pub enum Hit {
+ Ruler,
+ Clip { track: TrackId, clip: ClipId, edge: Option<Edge> },
+ Transition { track: TrackId, id: TransitionId },
+ Empty { track: TrackId },
+ None,
+ }
+
+ pub fn hit(seq: &Sequence, layout: &Layout, pos: Pos2) -> Hit {
+ if layout.ruler.contains(pos) {
+ return Hit::Ruler;
+ }
+ if !layout.content.contains(pos) {
+ return Hit::None;
+ }
+ let Some(row) = layout.row_at(pos.y) else { return Hit::None };
+ let Some(tr) = seq.track(row.track) else { return Hit::None };
+ for trn in &tr.transitions {
+ let x0 = layout.x_of(trn.start);
+ let x1 = layout.x_of(trn.end());
+ if pos.x >= x0 && pos.x <= x1 && pos.y > row.rect.min.y + 17.0 {
+ return Hit::Transition { track: row.track, id: trn.id };
+ }
+ }
+ if let Some((clip, edge)) = edge_at(tr, layout, pos.x) {
+ return Hit::Clip { track: row.track, clip, edge: Some(edge) };
+ }
+ match tr.item_at(layout.tick_at(pos.x)) {
+ Some(it) => Hit::Clip { track: row.track, clip: it.id, edge: None },
+ None => Hit::Empty { track: row.track },
+ }
+ }
+
+ /// A clip edge within reach of the pointer.
+ #[derive(Clone, Copy)]
+ struct Reach {
+ clip: ClipId,
+ edge: Edge,
+ /// The pointer is inside the clip (or exactly on the edge).
+ inside: bool,
+ /// How far the pointer is from the edge (px).
+ dist: f32,
+ }
+
+ impl Reach {
+ /// Inside a clip beats outside one (so at a cut the side of the cut picks the clip), then the
+ /// nearer edge wins; an exact tie (right on a cut, or mid-way across a narrow gap) goes to the
+ /// later clip's In edge.
+ fn beats(&self, other: &Reach) -> bool {
+ if self.inside != other.inside {
+ return self.inside;
+ }
+ match self.dist.partial_cmp(&other.dist) {
+ Some(Ordering::Less) => true,
+ Some(Ordering::Greater) => false,
+ _ => self.edge == Edge::In && other.edge != Edge::In,
+ }
+ }
+ }
+
+ /// The edge zone (px, on each side of an edge) of a clip `w` px wide on screen: a third of the
+ /// clip, at most [`EDGE_PX`], so the middle third of a narrow clip still moves it. `None` when the
+ /// clip has no usable width (zoomed far out, or a broken zoom): it has no edges then.
+ fn zone(w: f32) -> Option<f32> {
+ if w.is_finite() && w > 0.0 { Some(EDGE_PX.min(w / 3.0)) } else { None }
+ }
+
+ /// The clip edge on `tr` a pointer at `x` grabs (#259), whatever the order of `tr.items`.
+ fn edge_at(tr: &Track, layout: &Layout, x: f32) -> Option<(ClipId, Edge)> {
+ let mut best: Option<Reach> = None;
+ for it in &tr.items {
+ let (x0, x1) = (layout.x_of(it.start), layout.x_of(it.end()));
+ let Some(e) = zone(x1 - x0) else { continue };
+ // the pointer's distance into the clip from each of its edges
+ for (edge, d) in [(Edge::In, x - x0), (Edge::Out, x1 - x)] {
+ if !(-e..=e).contains(&d) {
+ continue;
+ }
+ let r = Reach { clip: it.id, edge, inside: d >= 0.0, dist: d.abs() };
+ if best.is_none_or(|b| r.beats(&b)) {
+ best = Some(r);
+ }
+ }
+ }
+ best.map(|r| (r.clip, r.edge))
+ }
+
+ /// The trim a press on a clip edge starts.
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ pub enum EdgeKind {
+ /// Regular trim: the edge moves, opening or covering a gap.
+ Trim,
+ /// Ripple trim: the edge moves and later clips follow.
+ Ripple,
+ /// Roll the cut between `left` and `right`.
+ Roll { left: ClipId, right: ClipId },
+ /// Rate Stretch: the clip's speed changes to fill its new length.
+ Stretch,
+ /// Remix: a music clip is re-planned to its new length (Out edges only).
+ Remix,
+ }
+
+ impl EdgeKind {
+ /// Its name on the control channel (`ui.timeline.hit` → `kind`).
+ pub fn name(self) -> &'static str {
+ match self {
+ EdgeKind::Trim => "trim",
+ EdgeKind::Ripple => "ripple",
+ EdgeKind::Roll { .. } => "roll",
+ EdgeKind::Stretch => "rateStretch",
+ EdgeKind::Remix => "remix",
+ }
+ }
+ }
+
+ /// What a press of a tool at a point grabs: a clip edge and the trim it starts, or whatever else
+ /// is there.
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ pub enum Grab {
+ Edge {
+ track: TrackId,
+ clip: ClipId,
+ edge: Edge,
+ kind: EdgeKind,
+ },
+ /// Not an edge this tool trims: a clip body, a transition, an empty track, the ruler or
+ /// nothing. A clip's `edge` may still be set, for tools that do something else there (Razor,
+ /// Slip…).
+ Other(Hit),
+ }
+
+ impl Grab {
+ /// What is under the pointer, whatever the tool does with it.
+ pub fn hit(self) -> Hit {
+ match self {
+ Grab::Edge { track, clip, edge, .. } => Hit::Clip { track, clip, edge: Some(edge) },
+ Grab::Other(h) => h,
+ }
+ }
+ }
+
+ /// What a press of `tool` with `mods` at `pos` grabs (#259): the one place that decides which
+ /// tools trim at a clip edge and which trim they start. `roll_ripple` is Settings ▸ Trim ▸ "Allow
+ /// Selection tool to choose Roll and Ripple trims without modifier key".
+ pub fn grab_at(seq: &Sequence, layout: &Layout, pos: Pos2, tool: Tool, mods: Modifiers, roll_ripple: bool) -> Grab {
+ let h = hit(seq, layout, pos);
+ let Hit::Clip { track, clip, edge: Some(edge) } = h else { return Grab::Other(h) };
+ let kind = match tool {
+ Tool::Selection => {
+ let (dist, neighbour) = edge_geometry(seq, layout, track, clip, edge, pos.x);
+ match selection_trim_kind(roll_ripple, mods.command, mods.shift, dist, neighbour) {
+ "roll" => roll(seq, track, clip, edge),
+ "ripple" => EdgeKind::Ripple,
+ _ => EdgeKind::Trim,
+ }
+ }
+ Tool::Ripple => EdgeKind::Ripple,
+ Tool::Rolling => roll(seq, track, clip, edge),
+ Tool::RateStretch => EdgeKind::Stretch,
+ Tool::Remix if edge == Edge::Out => EdgeKind::Remix,
+ _ => return Grab::Other(h),
+ };
+ Grab::Edge { track, clip, edge, kind }
+ }
+
+ /// A roll of the cut at `clip`'s `edge`, or a regular trim when no clip touches that cut on the
+ /// other side (there is nothing to roll against).
+ fn roll(seq: &Sequence, track: TrackId, clip: ClipId, edge: Edge) -> EdgeKind {
+ let Some(tr) = seq.track(track) else { return EdgeKind::Trim };
+ let Some(it) = tr.item(clip) else { return EdgeKind::Trim };
+ let pair = match edge {
+ Edge::Out => tr.items.iter().find(|x| x.start == it.end()).map(|r| (clip, r.id)),
+ Edge::In => tr.items.iter().find(|x| x.end() == it.start).map(|l| (l.id, clip)),
+ };
+ match pair {
+ Some((left, right)) => EdgeKind::Roll { left, right },
+ None => EdgeKind::Trim,
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+ use egui::{Rect, pos2};
+ use filmcraft_project::{ItemId, Label, Project, SequenceSettings, TrackItem, TrackKind};
+ use filmcraft_time::{FrameRate, Tick};
+
+ use crate::panels::timeline::Row;
+
+ /// The row's top. Points are hit-tested 10 px below it, above where transitions are hit.
+ const TOP: f32 = 100.0;
+
+ /// A clip on screen from `x0` to `x1` px (the layout is 100 px per second).
+ fn clip(id: u64, x0: f64, x1: f64) -> TrackItem {
+ TrackItem {
+ id: ClipId(id),
+ item: ItemId(1),
+ name: format!("c{id}"),
+ label: Label::Iris,
+ start: Tick::from_seconds_f64(x0 / 100.0),
+ duration: Tick::from_seconds_f64((x1 - x0) / 100.0),
+ source_in: Tick::ZERO,
+ speed: 1.0,
+ reverse: false,
+ enabled: true,
+ link: None,
+ group: None,
+ effects: Vec::new(),
+ markers: Vec::new(),
+ 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(),
++ audio_stream: 0,
+ graphic: None,
+ }
+ }
+
+ /// A: 100–300, B: 300–500 (sharing a cut with A), C: 504–700 (after a 4 px gap), D: 800–809
+ /// (9 px wide, so its zones are 3 px).
+ fn clips() -> Vec<TrackItem> {
+ vec![clip(1, 100.0, 300.0), clip(2, 300.0, 500.0), clip(3, 504.0, 700.0), clip(4, 800.0, 809.0)]
+ }
+
+ /// One video track holding `items`, laid out at 100 px/s from x = 0.
+ fn fixture(items: Vec<TrackItem>) -> (Sequence, Layout, TrackId) {
+ let mut p = Project::new("t");
+ let s = p.new_sequence("s", SequenceSettings { frame_rate: FrameRate::FPS_24, ..Default::default() }, 1, 0, None);
+ let mut seq = p.sequence(s).cloned().expect("sequence");
+ let track = seq.video_tracks[0].id;
+ seq.video_tracks[0].items = items;
+ let row = Rect::from_min_max(pos2(0.0, TOP), pos2(2000.0, TOP + 60.0));
+ let layout = Layout {
+ content: row,
+ ruler: Rect::from_min_max(pos2(0.0, 0.0), pos2(2000.0, 40.0)),
+ rows: vec![Row { track, kind: TrackKind::Video, index: 0, rect: row }],
+ pps: 100.0,
+ scroll: 0.0,
+ split_y: TOP + 60.0,
+ };
+ (seq, layout, track)
+ }
+
+ fn at(x: f32) -> Pos2 {
+ pos2(x, TOP + 10.0)
+ }
+
+ fn edge_hit(track: TrackId, clip: u64, edge: Edge) -> Hit {
+ Hit::Clip { track, clip: ClipId(clip), edge: Some(edge) }
+ }
+
+ #[test]
+ fn the_side_of_a_cut_picks_the_clip() {
+ let (seq, l, tr) = fixture(clips());
+ assert_eq!(hit(&seq, &l, at(297.0)), edge_hit(tr, 1, Edge::Out));
+ assert_eq!(hit(&seq, &l, at(303.0)), edge_hit(tr, 2, Edge::In));
+ // right on the cut: the later clip
+ assert_eq!(hit(&seq, &l, at(300.0)), edge_hit(tr, 2, Edge::In));
+ }
+
+ #[test]
+ fn a_narrow_gap_splits_at_its_middle() {
+ let (seq, l, tr) = fixture(clips());
+ assert_eq!(hit(&seq, &l, at(501.0)), edge_hit(tr, 2, Edge::Out));
+ assert_eq!(hit(&seq, &l, at(503.0)), edge_hit(tr, 3, Edge::In));
+ // exactly mid-way: the later clip
+ assert_eq!(hit(&seq, &l, at(502.0)), edge_hit(tr, 3, Edge::In));
+ }
+
+ #[test]
+ fn free_edges_reach_into_the_gap_beside_them() {
+ let (seq, l, tr) = fixture(clips());
+ assert_eq!(hit(&seq, &l, at(95.0)), edge_hit(tr, 1, Edge::In));
+ assert_eq!(hit(&seq, &l, at(705.0)), edge_hit(tr, 3, Edge::Out));
+ assert_eq!(hit(&seq, &l, at(92.0)), Hit::Empty { track: tr });
+ assert_eq!(hit(&seq, &l, at(200.0)), Hit::Clip { track: tr, clip: ClipId(1), edge: None });
+ }
+
+ #[test]
+ fn edges_do_not_depend_on_the_order_of_the_items() {
+ let mut reversed = clips();
+ reversed.reverse();
+ let (a, la, _) = fixture(clips());
+ let (b, lb, _) = fixture(reversed);
+ // edge points only: finding the clip under a body point relies on the items being sorted
+ for x in [297.0, 300.0, 303.0, 501.0, 502.0, 503.0, 95.0, 705.0, 802.0, 807.0] {
+ assert_eq!(hit(&a, &la, at(x)), hit(&b, &lb, at(x)), "x = {x}");
+ }
+ }
+
+ #[test]
+ fn a_narrow_clip_keeps_its_middle_third() {
+ let (seq, l, tr) = fixture(clips());
+ assert_eq!(hit(&seq, &l, at(802.0)), edge_hit(tr, 4, Edge::In));
+ assert_eq!(hit(&seq, &l, at(807.0)), edge_hit(tr, 4, Edge::Out));
+ assert_eq!(hit(&seq, &l, at(804.5)), Hit::Clip { track: tr, clip: ClipId(4), edge: None });
+ // 4 px outside it is beyond its 3 px zone
+ assert_eq!(hit(&seq, &l, at(796.0)), Hit::Empty { track: tr });
+ }
+
+ #[test]
+ fn hostile_points_and_zooms_never_panic_or_grab_an_edge() {
+ let (seq, l, tr) = fixture(vec![clip(5, 1000.0, 1000.0)]);
+ // a zero-length clip has no edges, even right on it
+ assert_eq!(hit(&seq, &l, at(1000.0)), Hit::Empty { track: tr });
+ for p in [pos2(f32::NAN, TOP + 10.0), pos2(f32::INFINITY, TOP + 10.0), pos2(f32::NEG_INFINITY, TOP + 10.0), pos2(300.0, f32::NAN), pos2(300.0, 5000.0)]
+ {
+ assert_eq!(hit(&seq, &l, p), Hit::None, "{p:?}");
+ }
+ let (seq, l, _) = fixture(clips());
+ assert_eq!(hit(&seq, &l, pos2(300.0, 20.0)), Hit::Ruler);
+ for pps in [0.0, f64::NAN, f64::INFINITY] {
+ let broken = Layout { pps, ..l.clone() };
+ assert!(!matches!(hit(&seq, &broken, at(300.0)), Hit::Clip { edge: Some(_), .. }), "pps {pps}");
+ }
+ }
+
+ use egui::Modifiers;
+
+ use crate::state::Tool;
+
+ const ROLL_AB: EdgeKind = EdgeKind::Roll { left: ClipId(1), right: ClipId(2) };
+
+ fn grab(seq: &Sequence, l: &Layout, tool: Tool, x: f32, mods: Modifiers, roll_ripple: bool) -> Grab {
+ grab_at(seq, l, at(x), tool, mods, roll_ripple)
+ }
+
+ fn edge_grab(track: TrackId, clip: u64, edge: Edge, kind: EdgeKind) -> Grab {
+ Grab::Edge { track, clip: ClipId(clip), edge, kind }
+ }
+
+ #[test]
+ fn selection_tool_trims_by_modifier_and_setting() {
+ let (seq, l, tr) = fixture(clips());
+ let (none, cmd, cmd_shift) = (Modifiers::NONE, Modifiers::COMMAND, Modifiers::COMMAND | Modifiers::SHIFT);
+ let sel = |x, mods, pref| grab(&seq, &l, Tool::Selection, x, mods, pref);
+ assert_eq!(sel(297.0, none, false), edge_grab(tr, 1, Edge::Out, EdgeKind::Trim));
+ assert_eq!(sel(303.0, cmd, false), edge_grab(tr, 2, Edge::In, EdgeKind::Ripple));
+ assert_eq!(sel(303.0, cmd_shift, false), edge_grab(tr, 2, Edge::In, ROLL_AB));
+ // Settings ▸ Trim: right on the cut rolls, elsewhere on the edge ripples
+ assert_eq!(sel(298.0, none, true), edge_grab(tr, 1, Edge::Out, ROLL_AB));
+ assert_eq!(sel(302.0, none, true), edge_grab(tr, 2, Edge::In, ROLL_AB));
+ assert_eq!(sel(305.0, none, true), edge_grab(tr, 2, Edge::In, EdgeKind::Ripple));
+ // a roll with no clip on the other side of the cut is a regular trim
+ assert_eq!(sel(102.0, cmd_shift, false), edge_grab(tr, 1, Edge::In, EdgeKind::Trim));
+ // mid-clip: the clip itself
+ assert_eq!(sel(200.0, none, false), Grab::Other(Hit::Clip { track: tr, clip: ClipId(1), edge: None }));
+ }
+
+ #[test]
+ fn which_tools_trim_at_an_edge() {
+ let (seq, l, tr) = fixture(clips());
+ let g = |tool, x| grab(&seq, &l, tool, x, Modifiers::NONE, false);
+ assert_eq!(g(Tool::Ripple, 297.0), edge_grab(tr, 1, Edge::Out, EdgeKind::Ripple));
+ assert_eq!(g(Tool::Rolling, 303.0), edge_grab(tr, 2, Edge::In, ROLL_AB));
+ assert_eq!(g(Tool::Rolling, 102.0), edge_grab(tr, 1, Edge::In, EdgeKind::Trim));
+ assert_eq!(g(Tool::RateStretch, 297.0), edge_grab(tr, 1, Edge::Out, EdgeKind::Stretch));
+ assert_eq!(g(Tool::Remix, 297.0), edge_grab(tr, 1, Edge::Out, EdgeKind::Remix));
+ // Remix has Out edges only
+ assert_eq!(g(Tool::Remix, 303.0), Grab::Other(edge_hit(tr, 2, Edge::In)));
+ for tool in [Tool::Razor, Tool::Slip, Tool::Slide, Tool::Hand, Tool::Zoom, Tool::TrackSelectForward] {
+ assert_eq!(g(tool, 297.0), Grab::Other(edge_hit(tr, 1, Edge::Out)), "{tool:?}");
+ }
+ }
+
+ #[test]
+ fn edge_kind_names_for_the_control_channel() {
+ assert_eq!(
+ [EdgeKind::Trim, EdgeKind::Ripple, ROLL_AB, EdgeKind::Stretch, EdgeKind::Remix].map(EdgeKind::name),
+ ["trim", "ripple", "roll", "rateStretch", "remix"]
+ );
+ }
+
+ #[test]
+ fn a_grab_reports_what_is_under_it() {
+ let (seq, l, tr) = fixture(clips());
+ assert_eq!(grab(&seq, &l, Tool::Selection, 303.0, Modifiers::NONE, false).hit(), edge_hit(tr, 2, Edge::In));
+ assert_eq!(grab(&seq, &l, Tool::Razor, 303.0, Modifiers::NONE, false).hit(), edge_hit(tr, 2, Edge::In));
+ }
+ }