From 6d0747c73d4ee59a4c6e885e2930fcc8d7ff51dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 20 Aug 2026 01:55:28 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20per-clip=20audio=20?= =?UTF-8?q?fades,=20adjacency=20crossfade,=20and=20edith=2018?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clip carries fade_in/fade_out, an equal-power gain envelope mixed into playback and export, a crossfade() op that sets both edges of two adjacent audio clips, and split's rule that only the kept edge keeps its fade. The project file format bumps to edith 18 to carry the two new fields; a v17 (or older) file loads with every clip's fades at zero. Fixes a stray fade_in/fade_out struct-literal fragment left outside any Clip literal in Player::trimmed (crates/app/src/player/timeline_edit.rs), which was a syntax error breaking the whole app crate's build. Adds unit coverage for Fade::gain_at's boundary/midpoint curve, the split edge rule, crossfade's adjacency refusal, the Clip size-lock test (40 -> 48 bytes), and a v17-loads-zero-fades / v18-round-trips edith.rs test. --- crates/app/src/tests/editing.rs | 10 + crates/app/src/tests/layout.rs | 2 + crates/app/src/tests/view.rs | 2 + crates/app/src/timeline_math.rs | 6 + crates/engine/examples/bench.rs | 2 + crates/engine/src/audio.rs | 113 ++++++++++- crates/engine/src/edith.rs | 203 +++++++++++++----- crates/engine/src/export.rs | 10 +- crates/engine/src/playback.rs | 13 +- crates/engine/src/project.rs | 305 +++++++++++++++++++++++++++- crates/engine/src/proxy.rs | 2 + crates/engine/src/silence.rs | 2 + crates/engine/src/sweep.rs | 2 + crates/engine/tests/audio_export.rs | 18 ++ crates/engine/tests/audio_files.rs | 2 + crates/engine/tests/eq_audio.rs | 2 + crates/engine/tests/export.rs | 4 + crates/engine/tests/lanes.rs | 6 + crates/engine/tests/opus_export.rs | 4 + crates/engine/tests/silence.rs | 4 + crates/engine/tests/speed.rs | 2 + 21 files changed, 645 insertions(+), 69 deletions(-) diff --git a/crates/app/src/tests/editing.rs b/crates/app/src/tests/editing.rs index b93dc67..0421f74 100644 --- a/crates/app/src/tests/editing.rs +++ b/crates/app/src/tests/editing.rs @@ -615,6 +615,8 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { use keymap::{ActionId, Keymap}; // Frames 30..90 of the timeline, taken from the head of its source. let clip = Clip { + fade_in: 0, + fade_out: 0, start: 30, in_frame: 0, out_frame: 60, @@ -655,6 +657,8 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { // clip by any reading of the playhead, so "only from inside a clip" // there is a refusal claiming something the screen contradicts. let slow = Clip { + fade_in: 0, + fade_out: 0, speed: Speed::MIN, ..clip }; @@ -679,6 +683,8 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { // engine's question. Group is offered on every clip, for that reason. assert!(!offered(&clip, v1, ActionId::Detach, 0)); let grouped = Clip { + fade_in: 0, + fade_out: 0, link: Some(3), ..clip }; @@ -981,6 +987,8 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { fn a_menu_offers_only_what_applies_and_is_drawn_inside_the_window() { use keymap::ActionId; let clip = Clip { + fade_in: 0, + fade_out: 0, start: 30, in_frame: 0, out_frame: 60, @@ -1611,6 +1619,8 @@ fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() { #[test] fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() { let clip = |source: usize| Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: 30, diff --git a/crates/app/src/tests/layout.rs b/crates/app/src/tests/layout.rs index 6459e5a..1212593 100644 --- a/crates/app/src/tests/layout.rs +++ b/crates/app/src/tests/layout.rs @@ -801,6 +801,8 @@ fn a_stills_trim_preview_grows_forward_like_the_commit() { #[test] fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() { let at = |start: u32| Clip { + fade_in: 0, + fade_out: 0, start, in_frame: 0, out_frame: 30, diff --git a/crates/app/src/tests/view.rs b/crates/app/src/tests/view.rs index 67118c2..d1167f0 100644 --- a/crates/app/src/tests/view.rs +++ b/crates/app/src/tests/view.rs @@ -147,6 +147,8 @@ fn a_lane_refuses_the_files_it_cannot_hold_before_the_release_says_so() { #[test] fn the_marks_are_every_lane_the_playhead_and_the_start() { let clip = |start: u32, frames: u32, link| Clip { + fade_in: 0, + fade_out: 0, start, in_frame: 0, out_frame: frames, diff --git a/crates/app/src/timeline_math.rs b/crates/app/src/timeline_math.rs index 85efc18..d9e6eca 100644 --- a/crates/app/src/timeline_math.rs +++ b/crates/app/src/timeline_math.rs @@ -303,12 +303,16 @@ pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip }; match still { true => Clip { + fade_in: 0, + fade_out: 0, in_frame: 0, out_frame: keep, start: to, ..clip }, false => Clip { + fade_in: 0, + fade_out: 0, in_frame: clip.out_frame - keep.min(clip.out_frame), start: to, ..clip @@ -317,6 +321,8 @@ pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip } Edge::End => match clip.speed.fit(to.saturating_sub(clip.start)) { Some(keep) => Clip { + fade_in: 0, + fade_out: 0, out_frame: clip.in_frame + keep, ..clip }, diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index 979c908..0959178 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -860,6 +860,8 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { .min(meta.frame_count.max(1)); let in_frame = (meta.frame_count / 10).min(meta.frame_count.saturating_sub(span)); let clip = Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame, out_frame: in_frame + span, diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 3687daa..4fabd21 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -392,6 +392,22 @@ impl AudioSession { eqs: &[Option], speeds: &[Option], sample_rate: Option, + ) -> crate::Result)>> { + Self::open_multi_streams_speed_at_fade(sources, segs, eqs, speeds, &[], sample_rate) + } + + /// [`open_multi_streams_speed_at`](Self::open_multi_streams_speed_at) with a + /// fade envelope per segment: `fades[i]` is what segment `i` plays through + /// ([`emit`]'s last effect, after the rate and the equalizer), built the + /// same way `eqs` and `speeds` are -- one entry per `segs`, a short list + /// meaning flat from there on. + pub fn open_multi_streams_speed_at_fade( + sources: &[(PathBuf, usize)], + segs: &[(Option, f64, f64)], + eqs: &[Option], + speeds: &[Option], + fades: &[Option], + sample_rate: Option, ) -> crate::Result)>> { // The first source that could have a track, which is not always index 0: // a still image has none, and one at the front of the list (a save @@ -571,6 +587,17 @@ impl AudioSession { }) .collect(); + // One [`crate::project::Fade`] per segment, exactly the eq and speed + // lists' rule: a short `fades` (the empty one every plain caller + // passes) means the rest play flat, and it is cloned rather than + // built here because [`Project::audio_fades_from`] already resolved + // each clip's own frame count against where this segment lands. + let fades: Vec> = segments + .iter() + .enumerate() + .map(|(i, _)| fades.get(i).copied().flatten()) + .collect(); + let (tx, rx) = sync_channel(32); thread::Builder::new() .name("audio-decode".into()) @@ -581,6 +608,7 @@ impl AudioSession { segments, eqs, speeds, + fades, timeline, tx, }) @@ -690,7 +718,27 @@ impl AudioSession { limiter: Limiter, sample_rate: Option, ) -> crate::Result)>> { - Self::open_mixed_streams_live(sources, lanes, eqs, speeds, gains, limiter, None, sample_rate) + Self::open_mixed_streams_master_at_fade( + sources, lanes, eqs, speeds, &[], gains, limiter, sample_rate, + ) + } + + /// [`open_mixed_streams_master_at`](Self::open_mixed_streams_master_at) + /// with a fade envelope per segment; see + /// [`open_mixed_streams_live_fade`](Self::open_mixed_streams_live_fade). + pub fn open_mixed_streams_master_at_fade( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + eqs: &[Vec>], + speeds: &[Vec>], + fades: &[Vec>], + gains: &[f32], + limiter: Limiter, + sample_rate: Option, + ) -> crate::Result)>> { + Self::open_mixed_streams_live_fade( + sources, lanes, eqs, speeds, fades, gains, limiter, None, sample_rate, + ) } /// [`open_mixed_streams_master`](Self::open_mixed_streams_master) with the @@ -710,6 +758,27 @@ impl AudioSession { limiter: Limiter, live: Option<&Arc>, sample_rate: Option, + ) -> crate::Result)>> { + Self::open_mixed_streams_live_fade( + sources, lanes, eqs, speeds, &[], gains, limiter, live, sample_rate, + ) + } + + /// [`open_mixed_streams_live`](Self::open_mixed_streams_live) with a fade + /// envelope per segment as well: `fades[i]` is what segment `i` plays + /// through -- [`crate::Project::audio_fades_from`] is what builds it, off + /// the same walk the segments come from. A short or missing list means + /// the rest play flat, the eq list's rule. + pub fn open_mixed_streams_live_fade( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + eqs: &[Vec>], + speeds: &[Vec>], + fades: &[Vec>], + gains: &[f32], + limiter: Limiter, + live: Option<&Arc>, + sample_rate: Option, ) -> crate::Result)>> { let [first, ..] = lanes else { return Ok(None); @@ -717,11 +786,13 @@ impl AudioSession { if !Self::is_mixed(lanes.len(), gains, limiter) { let flat = Vec::new(); let plain = Vec::new(); - return Self::open_multi_streams_speed_at( + let flat_fade = Vec::new(); + return Self::open_multi_streams_speed_at_fade( sources, first, eqs.first().unwrap_or(&flat), speeds.first().unwrap_or(&plain), + fades.first().unwrap_or(&flat_fade), sample_rate, ); } @@ -732,12 +803,14 @@ impl AudioSession { // agree by construction; `None` from any of them is a silent // timeline. let flat = Vec::new(); + let flat_fade = Vec::new(); let plain = Vec::new(); - let Some((lane_meta, rx)) = Self::open_multi_streams_speed_at( + let Some((lane_meta, rx)) = Self::open_multi_streams_speed_at_fade( sources, segs, eqs.get(i).unwrap_or(&flat), speeds.get(i).unwrap_or(&plain), + fades.get(i).unwrap_or(&flat_fade), sample_rate, )? else { @@ -2820,6 +2893,10 @@ struct Worker { /// every segment of a project nobody has speeded or rate-mismatched, and /// the path that emits the decoder's own samples untouched. speeds: Vec>, + /// One per entry of `segments` again: that segment's gain envelope, or + /// `None` for one that plays flat -- [`emit`]'s last effect, run after + /// the rate and the equalizer. + fades: Vec>, /// `start_sample` of the first chunk. timeline: u64, tx: SyncSender, @@ -2953,8 +3030,16 @@ fn run(mut w: Worker) { let mut speeds = std::mem::take(&mut w.speeds); // ...and a short rate list is "real time from here on", for the same reason. speeds.resize_with(segments.len(), || None); + let mut fades = std::mem::take(&mut w.fades); + // ...and a short fade list is "flat from here on", the same rule again. + fades.resize_with(segments.len(), || None); - for ((seg, eq), speed) in segments.iter().zip(eqs.iter_mut()).zip(speeds.iter_mut()) { + for (((seg, eq), speed), fade) in segments + .iter() + .zip(eqs.iter_mut()) + .zip(speeds.iter_mut()) + .zip(fades.iter_mut()) + { let Some(source) = seg.source else { // A gap: hand the device real silence rather than nothing at all, // in the same packet-sized chunks decoding produces, so `fed` and @@ -2984,6 +3069,7 @@ fn run(mut w: Worker) { seg, eq.as_mut(), speed, + fade, channels, &mut timeline, &w.tx, @@ -2999,6 +3085,7 @@ fn run(mut w: Worker) { seg, eq.as_mut(), speed, + fade, channels, &mut timeline, &w.tx, @@ -3014,6 +3101,7 @@ fn run(mut w: Worker) { seg, eq.as_mut(), speed, + fade, channels, &mut timeline, &w.tx, @@ -3063,6 +3151,7 @@ fn run(mut w: Worker) { seg, eq.as_mut(), speed.as_mut(), + fade.as_mut(), pos, next, &mut timeline, @@ -3115,6 +3204,7 @@ fn emit( seg: &Segment, eq: Option<&mut EqState>, speed: Option<&mut Rate>, + fade: Option<&mut crate::project::Fade>, pos: u64, next: u64, timeline: &mut u64, @@ -3147,6 +3237,15 @@ fn emit( if let Some(eq) = eq { eq.process(interleaved); } + // The fade last, on the same output-rate samples the mix will hear: its + // frame counts are timeline frames ([`crate::project::Clip::fade_in`]), + // which is what a resample has already turned these into. The state + // walks forward with the segment across as many buffers as decoding + // takes, exactly as the equalizer's does. + if let Some(fade) = fade { + fade.apply(interleaved, channels); + fade.elapsed = fade.elapsed.saturating_add((interleaved.len() / channels) as u32); + } let chunk = AudioChunk { start_sample: *timeline, samples: std::mem::take(interleaved), @@ -3164,6 +3263,7 @@ fn run_ac3( seg: &Segment, mut eq: Option<&mut EqState>, speed: &mut Option, + fade: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -3206,6 +3306,7 @@ fn run_ac3( seg, eq.as_deref_mut(), speed.as_mut(), + fade.as_mut(), pos, next, timeline, @@ -3227,6 +3328,7 @@ fn run_mkv_ac3( seg: &Segment, mut eq: Option<&mut EqState>, speed: &mut Option, + fade: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -3268,6 +3370,7 @@ fn run_mkv_ac3( seg, eq.as_deref_mut(), speed.as_mut(), + fade.as_mut(), pos, next, timeline, @@ -3294,6 +3397,7 @@ fn run_sym( seg: &Segment, mut eq: Option<&mut EqState>, speed: &mut Option, + fade: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -3342,6 +3446,7 @@ fn run_sym( seg, eq.as_deref_mut(), speed.as_mut(), + fade.as_mut(), pos, next, timeline, diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 6c177c9..e0ecc9c 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -16,9 +16,9 @@ //! subtitle 3 test_av.mp4 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk //! color 0.1:1.2:0.9:-0.3 -//! video 1 0 0 120 0 0 0 0 fit 1000 -//! audio 1 0 0 120 0 0 0 - fit 1000 -//! video 2 120 0 120 1 - - - fill 2000 +//! video 1 0 0 120 0 0 0 0 fit 1000 0 0 +//! audio 1 0 0 120 0 0 0 - fit 1000 30 30 +//! video 2 120 0 120 1 - - - fill 2000 0 0 //! audio 2 //! sub 1 0 60 0 500000 1500000 //! sub 2 @@ -110,15 +110,18 @@ //! -- the first colour line is color 0 -- printed and refused by the same rules. //! //! A lane line is ` -//! `: which lane the clip is on -- its kind and its 1-based number +//! `: which lane the clip is on -- its kind and its 1-based number //! among the lanes of that kind, the [`crate::project::Lane::label`] a header //! column shows -- then where the clip sits on the timeline, the half-open //! source range it plays, the file it plays from, its group id, the eq line it //! plays through, the colour line it is graded by (`-` for none of those three) //! and how it meets a project canvas of another shape, spelled `fit`, `fill`, -//! `stretch` or `center` ([`crate::scale::FitPolicy`]), and how fast it plays, +//! `stretch` or `center` ([`crate::scale::FitPolicy`]), how fast it plays, //! in thousandths of real time ([`crate::project::Speed`], `1000` for a clip -//! nobody has speeded). Timeline placement is +//! nobody has speeded), and finally its ramp up from silence and ramp down to +//! it, in timeline frames ([`crate::project::Clip::fade_in`], +//! [`crate::project::Clip::fade_out`], `0 0` for a clip nobody has faded). +//! Timeline placement is //! explicit, so a *gap* is simply a stretch no line covers -- there is nothing //! to write for one, and nothing that can disagree about its length. The `` //! and `` are *source* frames whatever the speed says: how long the clip is @@ -143,6 +146,8 @@ //! track 3 of a two-track palette is refused here, as a clip naming a source //! that is not there is. //! +//! **Version 17** was this without the clip's two fade fields: such a project +//! holds no clip anyone has faded, which is what a `0 0` pair still means. //! **Version 15** was this without the caption's group field: such a project //! holds captions no hand ever grouped, which is every caption there could be. //! **Version 14** was that without the `sub` lines: such a project holds no @@ -180,7 +185,7 @@ //! nothing, and an older one plays everything at real time, and an older one //! mixes flat, and an older one shows no subtitles, and an older one is shown //! in the reference rendition, and an older one places none of the words it -//! names -- and saving any of them writes v16. An older +//! names -- and saving any of them writes v18. An older //! reader refuses a newer file by name. //! //! Text because an edit list is a few integers and a path, and a path is @@ -216,7 +221,8 @@ use crate::subtitle::SubtitleTrack; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. -const MAGIC: &[u8] = b"edith 17"; +const MAGIC: &[u8] = b"edith 18"; +const MAGIC_V17: &[u8] = b"edith 17"; const MAGIC_V16: &[u8] = b"edith 16"; const MAGIC_V15: &[u8] = b"edith 15"; const MAGIC_V14: &[u8] = b"edith 14"; @@ -549,13 +555,15 @@ fn emit( let color = c.color.map_or("-".to_string(), |e| e.to_string()); out.extend_from_slice( format!( - "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {}\n", + "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {} {} {}\n", c.start, c.in_frame, c.out_frame, c.source, fit_name(c.fit), - c.speed.permille() + c.speed.permille(), + c.fade_in, + c.fade_out, ) .as_bytes(), ); @@ -598,8 +606,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The dialects that wrote a source line without its stream field. Reading // one is the whole of what "an old project still opens" means here. let streamless = v1 || first == MAGIC_V2; - // The one that carries an explicit sound rate... - let v17 = first == MAGIC; + // The one that carries a per-clip fade envelope... + let v18 = first == MAGIC; + // ...the one that carries an explicit sound rate... + let v17 = v18 || first == MAGIC_V17; // ...the one whose captions may carry a group id... let v16 = v17 || first == MAGIC_V16; // ...the one that places the words it names... @@ -963,6 +973,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { let f = fields(rest, 3, "clip", n)?; let clip = check( Clip { + fade_in: 0, + fade_out: 0, start: queued, in_frame: number(f[0], n)?, out_frame: number(f[1], n)?, @@ -1081,16 +1093,31 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { if numbered && rest.is_empty() { continue; } - // v8 grew the speed field, v7 the fit one, v6 the colour one and - // v5 the eq one; every older dialect ends at the link. - let want = - 5 + usize::from(v5) + usize::from(v6) + usize::from(v7) + usize::from(v8); + // v18 grew the two fade fields, v8 the speed one, v7 the fit + // one, v6 the colour one and v5 the eq one; every older + // dialect ends at the link. + let want = 5 + + usize::from(v5) + + usize::from(v6) + + usize::from(v7) + + usize::from(v8) + + 2 * usize::from(v18); let f = fields(rest, want, "clip", n)?; + let in_frame = number(f[1], n)?; + let out_frame = number(f[2], n)?; + let speed = speed_of(f.get(8).copied(), n)?; + // Clamped to the clip's own timeline length, + // [`Project::set_fade_in`]'s rule: a crafted or hand-edited + // file asking for more ramp than the clip has frames gets the + // clip's whole length rather than a refusal. + let frames = speed.frames(out_frame.saturating_sub(in_frame)); let clip = check( Clip { + fade_in: number(f.get(9).copied().unwrap_or(b"0"), n)?.min(frames), + fade_out: number(f.get(10).copied().unwrap_or(b"0"), n)?.min(frames), start: number(f[0], n)?, - in_frame: number(f[1], n)?, - out_frame: number(f[2], n)?, + in_frame, + out_frame, source: number(f[3], n)? as usize, link: match f[4] { b"-" => None, @@ -1099,7 +1126,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?, color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?, fit: fit_policy(f.get(7).copied(), n)?, - speed: speed_of(f.get(8).copied(), n)?, + speed, }, &doc, n, @@ -1509,7 +1536,7 @@ mod tests { video 1 0 0 30 0 - - - fit 1000\n"; let old = parse(v9, &dir).expect("v9 still loads"); assert_eq!(old.subtitles, Vec::new()); - assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 17\n")); + assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 18\n")); // ...and the line itself is not a v9 line: a dialect may not be mixed. let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir) .unwrap_err() @@ -1851,7 +1878,7 @@ mod tests { assert_eq!(mixed, "line 3: unknown keyword \"samplerate\""); // A number out of a sound rate's range is a corrupt line, by name. for line in ["samplerate 0\n", "samplerate 500000\n", "samplerate nope\n"] { - let file = format!("edith 17\nsource 0 a.mp4\n{line}"); + let file = format!("edith 18\nsource 0 a.mp4\n{line}"); assert!( parse(file.as_bytes(), &dir).is_err(), "{line:?} is not a sound rate line" @@ -1919,6 +1946,8 @@ mod tests { fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option) -> Clip { Clip { + fade_in: 0, + fade_out: 0, start, in_frame, out_frame, @@ -1977,10 +2006,10 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 18\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ - audio 1 0 0 30 0 0 - - fit 1000\n", + video 1 0 0 30 0 0 - - fit 1000 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0\n\ + audio 1 0 0 30 0 0 - - fit 1000 0 0\n", "the file under the project directory is written relative to it, \ each with the audio stream it plays" ); @@ -2014,9 +2043,9 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ - video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", + "edith 18\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 4 - - fit 1000 0 0\naudio 1\n\ + video 2 40 0 10 0 - - - fit 1000 0 0\naudio 2 0 0 30 0 4 - - fit 1000 0 0\n", "an empty lane is a line of its own; everything else is its clips" ); let back = parse(&bytes, &dir).expect("parse"); @@ -2100,20 +2129,28 @@ mod tests { let lanes = two( vec![ Clip { + fade_in: 0, + fade_out: 0, eq: Some(0), ..clip(0, 0, 30, 0, Some(0)) }, Clip { + fade_in: 0, + fade_out: 0, eq: Some(1), ..clip(30, 10, 20, 0, None) }, ], vec![ Clip { + fade_in: 0, + fade_out: 0, eq: Some(0), ..clip(0, 0, 30, 0, Some(0)) }, Clip { + fade_in: 0, + fade_out: 0, eq: Some(2), ..clip(30, 0, 10, 0, None) }, @@ -2122,12 +2159,12 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 18\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 16777215.0:-0.1:3.918315e-39:hs\n\ eq\n\ - video 1 0 0 30 0 0 0 - fit 1000\nvideo 1 30 10 20 0 - 1 - fit 1000\n\ - audio 1 0 0 30 0 0 0 - fit 1000\naudio 1 30 0 10 0 - 2 - fit 1000\n", + video 1 0 0 30 0 0 0 - fit 1000 0 0\nvideo 1 30 10 20 0 - 1 - fit 1000 0 0\n\ + audio 1 0 0 30 0 0 0 - fit 1000 0 0\naudio 1 30 0 10 0 - 2 - fit 1000 0 0\n", "the table comes before the clips, and a clip names a line of it" ); @@ -2196,12 +2233,16 @@ mod tests { let lanes = two( vec![ Clip { + fade_in: 0, + fade_out: 0, color: Some(0), fit: FitPolicy::default(), speed: Speed::NORMAL, ..clip(0, 0, 30, 0, Some(0)) }, Clip { + fade_in: 0, + fade_out: 0, color: Some(1), fit: FitPolicy::default(), speed: Speed::NORMAL, @@ -2210,12 +2251,16 @@ mod tests { ], vec![ Clip { + fade_in: 0, + fade_out: 0, color: Some(0), fit: FitPolicy::default(), speed: Speed::NORMAL, ..clip(0, 0, 30, 0, Some(0)) }, Clip { + fade_in: 0, + fade_out: 0, color: Some(2), fit: FitPolicy::default(), speed: Speed::NORMAL, @@ -2226,12 +2271,12 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 18\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ color 0.1:1.2:0.9:-0.3\n\ color -1e-7:16777215.0:3.918315e-39:-0.0\n\ color 0.0:1.0:1.0:0.0\n\ - video 1 0 0 30 0 0 - 0 fit 1000\nvideo 1 30 10 20 0 - - 1 fit 1000\n\ - audio 1 0 0 30 0 0 - 0 fit 1000\naudio 1 30 0 10 0 - - 2 fit 1000\n", + video 1 0 0 30 0 0 - 0 fit 1000 0 0\nvideo 1 30 10 20 0 - - 1 fit 1000 0 0\n\ + audio 1 0 0 30 0 0 - 0 fit 1000 0 0\naudio 1 30 0 10 0 - - 2 fit 1000 0 0\n", "the table comes before the clips, and a clip names a line of it" ); @@ -2291,9 +2336,9 @@ mod tests { (1280, 720), old.playhead )), - "edith 17\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 18\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ - video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" + video 1 0 0 30 0 0 0 - fit 1000 0 0\naudio 1 0 0 30 0 0 - - fit 1000 0 0\n" ); } @@ -2306,6 +2351,8 @@ mod tests { let dir = PathBuf::from("/proj"); let sources = vec![Source::new("/proj/a.mp4", 0)]; let speeded = |start, in_frame, out_frame, permille| Clip { + fade_in: 0, + fade_out: 0, start, in_frame, out_frame, @@ -2329,9 +2376,9 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ - audio 1 0 0 30 0 - - - fit 2000\n", + "edith 18\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 2000 0 0\nvideo 1 15 30 40 0 - - - fit 250 0 0\n\ + audio 1 0 0 30 0 - - - fit 2000 0 0\n", "the rate is the clip line's last field, in thousandths" ); let back = parse(&bytes, &dir).expect("parse"); @@ -2358,8 +2405,8 @@ mod tests { (1280, 720), old.playhead )), - "edith 17\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" + "edith 18\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 0 - - fit 1000 0 0\naudio 1 0 0 30 0 0 - - fit 1000 0 0\n" ); // A rate outside what the editor can set is a corrupt line, by name. let bad = b"edith 8\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 9000\n"; @@ -2369,6 +2416,50 @@ mod tests { ); } + #[test] + fn a_v17_file_loads_with_zero_fades_and_fades_round_trip_bit_exactly() { + let dir = PathBuf::from("/proj"); + // The v17 dialect: nine clip fields, the last the speed -- no fade + // pair after it at all, not even zeroes. + let v17 = b"edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"; + let old = parse(v17, &dir).expect("v17 parses"); + assert!( + old.lanes + .iter() + .flat_map(|(_, clips)| clips) + .all(|c| c.fade_in == 0 && c.fade_out == 0), + "nothing before v18 had a fade to name" + ); + + // ...and the dialect that does: nonzero fades on both edges, written + // and read back as the very numbers. + let sources = vec![Source::new("/proj/a.mp4", 0)]; + let faded = Clip { + fade_in: 5, + fade_out: 7, + start: 0, + in_frame: 0, + out_frame: 30, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + let lanes = vec![(LaneKind::Video, vec![faded])]; + let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); + assert_eq!( + String::from_utf8_lossy(&bytes), + "edith 18\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 5 7\n", + "the fades are the clip line's last two fields" + ); + let back = parse(&bytes, &dir).expect("parse"); + assert_eq!(back.lanes, lanes, "the fades round trip as the very numbers"); + } + /// The whole of the v9 bump, the speed test's twin: the mix a project was /// left at -- every track's own volume and the master limiter -- plus the /// rate it was cut at, all written, all read back as the very numbers, and @@ -2409,10 +2500,10 @@ mod tests { ); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ + "edith 18\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ limiter -1.5 on\nsource 0 a.mp4\n\ - video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ - audio 2 0 0 30 0 - - - fit 1000\n\ + video 1 0 0 30 0 - - - fit 1000 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0\n\ + audio 2 0 0 30 0 - - - fit 1000 0 0\n\ gain audio 1 3.0\ngain audio 2 -6.5\n", "the mix is lines of its own, the gains after the lanes they name" ); @@ -2441,8 +2532,8 @@ mod tests { (1280, 720), old.playhead )), - "edith 17\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ - video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" + "edith 18\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0\n" ); // Each of the three refuses by name, on its own line. @@ -2605,10 +2696,10 @@ mod tests { assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); assert_eq!( String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), - "edith 17\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 18\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ - audio 1 0 0 30 0 0 - - fit 1000\n" + video 1 0 0 30 0 0 - - fit 1000 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0\n\ + audio 1 0 0 30 0 0 - - fit 1000 0 0\n" ); // An empty lane's line is still the whole of that lane, eq or no eq. let empty = parse( @@ -2658,10 +2749,10 @@ mod tests { let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( String::from_utf8_lossy(&v5), - "edith 17\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 18\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 0 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ - audio 1 0 0 30 0 0 - - fit 1000\n", + video 1 0 0 30 0 0 - - fit 1000 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0\n\ + audio 1 0 0 30 0 0 - - fit 1000 0 0\n", "a re-saved v2 project differs only by its version, the lane \ numbers, the streams it always meant and an equalizer it has none of" ); @@ -2690,7 +2781,7 @@ mod tests { // Saved again it is the current version, which round-trips to the // same document. let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); - assert!(v5.starts_with(b"edith 17\n")); + assert!(v5.starts_with(b"edith 18\n")); let again = parse(&v5, &dir).expect("v5 parses"); assert_eq!(again.lanes, back.lanes); // A dialect may not be mixed: lane lines under v1, `clip` under v2. @@ -2800,8 +2891,8 @@ mod tests { let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 17\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ - video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" + "edith 18\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0\n" ); // Loading rejoins the *given* directory, so the file is reached by the // way the project was opened -- the same file, through the link, still @@ -2845,10 +2936,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 18\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 19\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 18"); + assert_eq!(err, "line 1: unsupported version 19"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 4410c50..129e17c 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1671,16 +1671,18 @@ fn encode_audio( let segs = project.audio_segments_from(0, meta.frame_rate); let eqs = project.audio_eqs_from(0, meta.frame_rate); let speeds = project.audio_speeds_from(0, meta.frame_rate); + let fades = project.audio_fades_from(0, meta.frame_rate); // Coarse stage timers, in the same voice as `export video: copy` below: an // export of a feature film spends minutes in here before a byte of picture // is written, and which minutes went where is the first question asked of a // slow export. Three lines an export, so they stay on. let mixed = std::time::Instant::now(); - let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at( + let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade( &sources, &segs, &eqs, &speeds, + &fades, &project.audio_gains(), project.limiter(), sample_rate, @@ -2765,15 +2767,19 @@ fn run_audio( // 2x is half as long and holds the samples that were heard -- not a // second pass here that could disagree with what the ear got. let speeds = project.audio_speeds_from(0, meta.frame_rate); + // ...and the fades with them, the same choke-point reason again: a clip's + // envelope runs inside the worker playback feeds from too. + let fades = project.audio_fades_from(0, meta.frame_rate); // ...and the mix over both: each lane's volume into the sum, the master // limiter out of it. The same opener playback's feeder reads from, so a // file is written at the levels it was heard at -- there is no second // place here that could mix it differently. - let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at( + let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade( &sources, &segs, &eqs, &speeds, + &fades, &project.audio_gains(), project.limiter(), sample_rate, diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index fe593ba..365af44 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -618,6 +618,8 @@ impl PlaybackSession { // *video* open's pair of grouped clips: here there is no picture to // group the sound with, so the video lane starts empty. let clip = Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: meta.frame_count, @@ -701,6 +703,8 @@ impl PlaybackSession { color: ColorDescription::default(), }; let clip = Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: place_frames(meta.frame_count, IMAGE_ONLY_RATE), @@ -2625,6 +2629,8 @@ impl PlaybackSession { let source = self.project.import(path, stream); self.note_frames(source, frames, rate); let clip = Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: match image { @@ -3248,6 +3254,10 @@ impl PlaybackSession { // speeded, which is the path that decodes the same samples it always // did. let speeds = self.project.audio_speeds_from(target, fps); + // ...and the fades, the same way again: a clip's own envelope runs + // inside its worker, after the rate and the equalizer, so a fade + // edit is audible at once exactly as an EQ edit is. + let fades = self.project.audio_fades_from(target, fps); // Each source on the stream it was placed with: what plays is what // the library row said, and what an export copies (`export::run`). let sources = self.project.audio_sources(); @@ -3277,11 +3287,12 @@ impl PlaybackSession { // one `pread` on a cold 25 GB film is seconds, and this is called // from a ruler drag ([`Audio::spawn_feeder_deferred`]). audio_running = audio.spawn_feeder_deferred(move || { - match AudioSession::open_mixed_streams_live( + match AudioSession::open_mixed_streams_live_fade( &sources, &segs, &eqs, &speeds, + &fades, &gains, limiter, Some(&worker_controls), diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index b11442d..0df7e2b 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -430,6 +430,15 @@ pub struct Clip { /// changes is how many *timeline* frames that range is spread over /// ([`Clip::frames`]). pub speed: Speed, + /// Timeline frames of ramp-up from silence at the clip's own start, inline + /// like [`Clip::fit`] and [`Clip::speed`] for the same reason: one small + /// number with nothing to share, and every consumer (mixer, exporter) wants + /// it sitting right next to the frame range it shapes. Clamped to the + /// clip's own length by the setter -- never wider than the clip is long. + pub fade_in: u32, + /// Timeline frames of ramp-down to silence at the clip's own end. Same + /// promises as [`Clip::fade_in`]. + pub fade_out: u32, } impl Clip { @@ -748,6 +757,62 @@ pub struct Stretch { pub timeline_secs: f64, } +/// What one audio segment's gain envelope is: [`Project::audio_fades_from`] +/// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved +/// against where in the *clip* -- not the segment, which may start mid-clip +/// on a seek -- this segment's first frame lands. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Fade { + /// How many of the clip's own frames already played before this + /// segment's first frame: `0` unless playback started mid-clip. + pub elapsed: u32, + /// The clip's [`Clip::fade_in`]. + pub fade_in: u32, + /// The clip's [`Clip::fade_out`]. + pub fade_out: u32, + /// The clip's own [`Clip::frames`] -- the envelope's whole width, of + /// which this segment may only cover the tail. + pub total: u32, +} + +impl Fade { + /// The gain at clip-relative frame `pos`, an equal-power curve on each + /// edge that plays through unchanged (gain `1.0`) wherever neither ramp + /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the + /// ramp, so a fade lands on silence at its very first (or very last) + /// frame and reaches unity smoothly rather than at a constant slope -- + /// the same curve [`Project::crossfade`] relies on to keep two clips' + /// sum around one level through the join. Both ramps multiply where a + /// clip is short enough for them to overlap. + fn gain_at(self, pos: u32) -> f32 { + let mut g = 1.0f32; + if self.fade_in > 0 && pos < self.fade_in { + let t = pos as f32 / self.fade_in as f32; + g *= (t * std::f32::consts::FRAC_PI_2).sin(); + } + if self.fade_out > 0 { + let out_start = self.total.saturating_sub(self.fade_out); + if pos >= out_start { + let remaining = self.total.saturating_sub(pos); + let t = remaining as f32 / self.fade_out as f32; + g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin(); + } + } + g + } + + /// Multiplies `frames` in place -- `channels`-wide interleaved samples, + /// starting at this segment's own frame `0` -- by [`Self::gain_at`]. + pub fn apply(self, frames: &mut [f32], channels: usize) { + for (i, block) in frames.chunks_mut(channels).enumerate() { + let g = self.gain_at(self.elapsed.saturating_add(i as u32)); + for s in block { + *s *= g; + } + } + } +} + /// What a save writes and a load takes back: the sources, every lane in /// display order with its kind, and the equalizer and colour tables their clips /// index into -- [`Project::without_orphan_sources`] out, @@ -810,6 +875,8 @@ impl Project { /// is clamped to one frame. pub fn single(path: impl AsRef, frame_count: u32) -> Self { let clip = Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: frame_count.max(1), @@ -1188,6 +1255,8 @@ impl Project { self.snapshot(); let start = self.timeline_frames(); let clip = Clip { + fade_in: 0, + fade_out: 0, start, in_frame: 0, out_frame: frame_count.max(1), @@ -2396,6 +2465,76 @@ impl Project { true } + /// Timeline frames of ramp-up from silence at the start of the clip at + /// `idx` of `lane`. `0` for an index that is not there, same as a clip + /// that has none. + pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 { + self.lane(lane).get(idx).map_or(0, |c| c.fade_in) + } + + /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade + /// can shrink a clip's audible middle to nothing but never ask for more + /// ramp than the clip has frames. One undo step like [`Project::set_fit`], + /// and `false` (no history) for an index that is not there. + pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + if idx >= self.lane(lane).len() { + return false; + } + self.snapshot(); + let clip = &mut self.lane_mut(lane).expect("checked above")[idx]; + clip.fade_in = frames.min(clip.frames()); + true + } + + /// Timeline frames of ramp-down to silence at the end of the clip at + /// `idx` of `lane`. Same promise as [`Project::fade_in_of`]. + pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 { + self.lane(lane).get(idx).map_or(0, |c| c.fade_out) + } + + /// Sets it. Same promises as [`Project::set_fade_in`]. + pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + if idx >= self.lane(lane).len() { + return false; + } + self.snapshot(); + let clip = &mut self.lane_mut(lane).expect("checked above")[idx]; + clip.fade_out = frames.min(clip.frames()); + true + } + + /// Crossfades the audio clip at `idx` of `lane` into the one immediately + /// after it, over `frames` timeline frames: sets `idx`'s + /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`, + /// each clamped to its own clip's length. `false` -- no history -- unless + /// `lane` is audio, `idx + 1` is in bounds, and the two clips are + /// adjacent: the second's [`Clip::start`] is exactly the first's + /// [`Clip::end`], no gap between them. + /// + /// This is the whole mechanism, not a stand-in for one: a *real* + /// cross-fade -- both takes heard at once, blending -- is what two clips + /// **overlapping** on separate lanes already get for free from the + /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]). + /// This call only shapes the edges of two clips already sitting + /// end-to-end on *one* lane, so the join between them fades like one did. + pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { + if lane.kind != LaneKind::Audio { + return false; + } + let clips = self.lane(lane); + let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else { + return false; + }; + if a.end() != b.start { + return false; + } + self.snapshot(); + let clips = self.lane_mut(lane).expect("checked above"); + clips[idx].fade_out = frames.min(clips[idx].frames()); + clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames()); + true + } + /// Every frame number on every lane rewritten onto a timeline counted at /// another rate: `k` is old timeline frames per new one, `counts` is how /// long each source is on the *new* timeline (indexed as @@ -2804,8 +2943,18 @@ impl Project { tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so"); tail.start = timeline_frame; tail.link = right_of(orig[data_i]); + // A split makes a new edge for each half, and a fade is a promise + // about an edge: only the half that *kept* the original edge + // keeps that fade, re-clamped to its own now-shorter length (a + // cut inside the ramp shortens it, never leaves it pointing past + // the clip it is on); the edge the cut itself made starts, or + // ends, flat -- there was no silence there to ramp out of. + tail.fade_in = 0; + tail.fade_out = tail.fade_out.min(tail.frames()); data.clips[idx].out_frame = tail.in_frame; data.clips[idx].link = orig[data_i]; + data.clips[idx].fade_out = 0; + data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames()); data.clips.insert(idx + 1, tail); } true @@ -3137,6 +3286,8 @@ impl Project { } self.snapshot(); let clip = Clip { + fade_in: 0, + fade_out: 0, start: timeline_frame, link: None, ..clip @@ -3176,6 +3327,8 @@ impl Project { self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new())); } let clip = Clip { + fade_in: 0, + fade_out: 0, start: timeline_frame, link: Some(self.new_link()), ..clip @@ -3751,6 +3904,8 @@ impl Project { } self.snapshot(); let clip = Clip { + fade_in: 0, + fade_out: 0, start: at, link: Some(self.new_link()), ..clip @@ -4416,6 +4571,42 @@ impl Project { .collect() } + /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s + /// segments plays through: the same lanes in the same order, one entry per + /// segment, `None` where the segment is a gap or its clip has neither a + /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for + /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason. + pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec>> { + self.audio_lanes() + .into_iter() + .map(|lane| self.lane_fades_from(lane, timeline_frame, fps)) + .collect() + } + + /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching + /// [`lane_segments_from`](Project::lane_segments_from) entry for entry. + pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec> { + if !(fps.is_finite() && fps > 0.0) { + return Vec::new(); + } + self.spans_from(lane, timeline_frame) + .iter() + .map(|span| { + let (idx, _) = self.map(lane, span.start)?; + let clip = self.lane(lane).get(idx)?; + (clip.fade_in > 0 || clip.fade_out > 0).then(|| Fade { + // `span.len` is the clip's own remaining frames from + // `span.start` on -- shorter than `clip.frames()` only + // when this is the first span of a seek mid-clip. + elapsed: clip.frames().saturating_sub(span.len), + fade_in: clip.fade_in, + fade_out: clip.fade_out, + total: clip.frames(), + }) + }) + .collect() + } + /// Pushes the undo snapshot. Every mutating method calls this once, *after* /// it has decided it will succeed -- a refusal must not cost an undo step. fn snapshot(&mut self) { @@ -4761,6 +4952,8 @@ fn clear(clips: &mut Vec, start: u32, end: u32) { && c.start < start { out.push(Clip { + fade_in: 0, + fade_out: 0, out_frame: c.in_frame + keep.min(c.len()), link: None, ..c @@ -4774,6 +4967,8 @@ fn clear(clips: &mut Vec, start: u32, end: u32) { && c.end() > end { out.push(Clip { + fade_in: 0, + fade_out: 0, start: end, in_frame: c.out_frame - keep.min(c.len()), link: None, @@ -4880,6 +5075,8 @@ mod tests { /// A contiguous placement, group id ignored: what most assertions compare. fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip { Clip { + fade_in: 0, + fade_out: 0, start, in_frame, out_frame, @@ -5008,6 +5205,89 @@ mod tests { ); } + /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at + /// the very first frame of a fade-in, unity at its last, equal-power + /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches + /// at all. + #[test] + fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() { + let f = Fade { + elapsed: 0, + fade_in: 10, + fade_out: 10, + total: 40, + }; + assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame"); + assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends"); + let midpoint = std::f32::consts::FRAC_PI_2 * 0.5; + assert!( + (f.gain_at(5) - midpoint.sin()).abs() < 1e-6, + "equal-power midpoint is sin(pi/4)" + ); + assert_eq!(f.gain_at(20), 1.0, "unchanged in the body, past either ramp"); + // The fade-out is the same curve, mirrored, counting down from the + // clip's end: unity at the frame the ramp starts, the same + // equal-power midpoint, and -- since `total` itself is one past the + // clip's last valid frame -- the very last frame is one step short of + // the silence a fade-in's own frame `0` lands on exactly. + assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts"); + assert!( + (f.gain_at(35) - midpoint.sin()).abs() < 1e-6, + "the fade-out's own equal-power midpoint" + ); + assert!( + (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6, + "one step short of silence at the clip's last playable frame" + ); + } + + /// [`Project::crossfade`] refuses a non-audio lane and two clips that are + /// not adjacent, and otherwise sets the shared edge's fades and nothing + /// else. + #[test] + fn crossfade_only_joins_adjacent_audio_clips() { + let mut p = Project::single(FILE, 20); + assert!(p.split(10)); + assert!( + !p.crossfade(Lane::V1, 0, 5), + "video is not an audio lane" + ); + assert!( + !p.crossfade(Lane::A1, 1, 5), + "there is no clip after idx 1" + ); + assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent"); + let a = p.lane(Lane::A1); + assert_eq!(a[0].fade_out, 5); + assert_eq!(a[1].fade_in, 5); + assert_eq!(a[0].fade_in, 0); + assert_eq!(a[1].fade_out, 0); + + // A gap between two clips is not adjacency, even on an audio lane. + let mut p2 = Project::single(FILE, 1); + let a2 = p2.add_lane(LaneKind::Audio); + assert!(p2.place(a2, 0, clip(0, 0, 3, 0))); + assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one"); + assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent"); + } + + /// The rule [`Project::write_split`] follows for the edge the razor makes: + /// the left half keeps its old [`Clip::fade_in`] (clamped to its new, + /// shorter length) and loses its [`Clip::fade_out`]; the right half is the + /// mirror image. + #[test] + fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() { + let mut p = Project::single(FILE, 20); + assert!(p.set_fade_in(Lane::V1, 0, 15)); + assert!(p.set_fade_out(Lane::V1, 0, 15)); + assert!(p.split(5)); + let v = p.lane(Lane::V1); + assert_eq!(v[0].fade_in, 5, "the left half's kept fade-in, clamped to 5 frames"); + assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat"); + assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat"); + assert_eq!(v[1].fade_out, 15, "the right half's kept fade-out, unclamped: 15 frames fit in 15"); + } + /// The music video's own path: the take comes apart into halves that carry /// ids of their own, one undo puts it back, and two clips over the same /// frames become one take again by hand. @@ -6188,14 +6468,15 @@ mod tests { /// table like the eq and the grade: there is nothing for a table to share. /// It costs the clip nothing at all -- the fields before it (a `usize` /// source and two `Option`s) already left the struct padded to 40 - /// bytes, and the byte landed in that padding. This is the assert that says - /// so: a clip that grew a word grew every undo snapshot and every clipboard - /// copy with it. + /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are the + /// two `u32`s after it, so those cost the clip a full word each: 48 bytes + /// total. This is the assert that says so: a clip that grows a word grows + /// every undo snapshot and every clipboard copy with it. #[test] fn a_fit_policy_costs_the_clip_no_word() { assert_eq!( std::mem::size_of::(), - 40, + 48, "Clip changed size: {} bytes", std::mem::size_of::() ); @@ -6204,6 +6485,8 @@ mod tests { /// The clip a copy would hand back: source `[100, 102)`, unrelated to /// anything in `three()` so it is recognisable wherever it lands. const PASTED: Clip = Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 100, out_frame: 102, @@ -6276,6 +6559,8 @@ mod tests { let mut p = three(); let wav = p.import("/nonexistent/song.wav", 0); let copied = Clip { + fade_in: 0, + fade_out: 0, source: wav, ..PASTED }; @@ -7514,8 +7799,8 @@ mod tests { fn a_clip_is_still_a_small_copy() { assert_eq!( std::mem::size_of::(), - 40, - "Clip changed size -- 32 before the colour index, 40 after" + 48, + "Clip changed size -- 32 before the colour index, 40 before the fades, 48 after" ); } @@ -7597,6 +7882,8 @@ mod tests { // format could not have written, are refused at this door too. let eqd = |i: u16| { vec![Clip { + fade_in: 0, + fade_out: 0, eq: Some(i), ..video[0] }] @@ -7633,6 +7920,8 @@ mod tests { // The same two refusals for a colour, at the same door. let graded = |i: u16| { vec![Clip { + fade_in: 0, + fade_out: 0, color: Some(i), fit: FitPolicy::default(), speed: Speed::NORMAL, @@ -7691,6 +7980,8 @@ mod tests { fn a_link_id_is_never_two_clips_of_one_lane() { let sources = vec![Source::new(FILE, 0)]; let linked = |start, in_frame, out_frame, link| Clip { + fade_in: 0, + fade_out: 0, start, in_frame, out_frame, @@ -8468,6 +8759,8 @@ mod tests { fn a_group_may_span_any_lane() { let lane = |kind, clips: Vec| LaneData::new(kind, clips); let one = |start: u32, end: u32, link| Clip { + fade_in: 0, + fade_out: 0, start, in_frame: start, out_frame: end, diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs index 645cc4b..ad018bc 100644 --- a/crates/engine/src/proxy.rs +++ b/crates/engine/src/proxy.rs @@ -487,6 +487,8 @@ fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result Clip { Clip { + fade_in: 0, + fade_out: 0, start, in_frame, out_frame, diff --git a/crates/engine/src/sweep.rs b/crates/engine/src/sweep.rs index 7e8fef9..360f1ca 100644 --- a/crates/engine/src/sweep.rs +++ b/crates/engine/src/sweep.rs @@ -66,6 +66,8 @@ fn track() -> SubtitleTrack { fn clip(start: u32, in_frame: u32, out_frame: u32) -> Clip { Clip { + fade_in: 0, + fade_out: 0, start, in_frame, out_frame, diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 4964a25..0b63953 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -61,6 +61,8 @@ fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { /// re-encodes today and once refused outright. fn mixed_project() -> Project { let clip = |start, source| Clip { + fade_in: 0, + fade_out: 0, start, in_frame: 0, out_frame: 30, @@ -83,6 +85,8 @@ fn mixed_project() -> Project { ( LaneKind::Video, vec![Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: 90, @@ -324,6 +328,8 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { let song = asset("test_tone.mp3"); let still = asset("test_still.png"); let clip = |source, frames| Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: frames, @@ -388,6 +394,8 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { #[test] fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() { let clip = Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: 30, @@ -621,6 +629,8 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { ( LaneKind::Video, vec![Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: 60, @@ -635,6 +645,8 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { ( LaneKind::Audio, vec![Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: 60, @@ -689,6 +701,8 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { #[test] fn a_silent_clip_exports_as_silence_over_its_own_span() { let clip = |start, source| Clip { + fade_in: 0, + fade_out: 0, start, in_frame: 0, out_frame: 30, @@ -779,6 +793,8 @@ fn a_51_ac3_source_round_trips_through_a_wav() { vec![( LaneKind::Audio, vec![Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: 30, @@ -904,6 +920,8 @@ fn a_mono_timeline_exports_as_dual_mono_ogg() { vec![( LaneKind::Audio, vec![Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: 30, diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index d06364e..88990af 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -491,6 +491,8 @@ fn a_song_survives_a_save_and_a_reload() { Lane::A1, 1.0, Clip { + fade_in: 0, + fade_out: 0, in_frame: 0, out_frame: 30, ..song diff --git a/crates/engine/tests/eq_audio.rs b/crates/engine/tests/eq_audio.rs index e3576eb..d7668cc 100644 --- a/crates/engine/tests/eq_audio.rs +++ b/crates/engine/tests/eq_audio.rs @@ -54,6 +54,8 @@ fn boost() -> EqParams { fn clip(start: u32, source: usize, frames: u32) -> Clip { Clip { + fade_in: 0, + fade_out: 0, start, in_frame: 0, out_frame: frames, diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 20cf1fb..20047ef 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -234,6 +234,8 @@ fn exports_an_edited_timeline_in_hardware() { fn exports_at_the_project_resolution_with_the_watched_geometry() { let _seat = pin_software(); let clip = |source: usize, start: u32| engine::Clip { + fade_in: 0, + fade_out: 0, start, in_frame: 0, out_frame: 10, @@ -316,6 +318,8 @@ fn exports_the_audio_stream_the_timeline_plays() { let multi = asset("test_multiaudio.mp4"); let (meta, _) = engine::demux::Demuxer::open(&multi).expect("open the fixture"); let whole = engine::Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: meta.frame_count, diff --git a/crates/engine/tests/lanes.rs b/crates/engine/tests/lanes.rs index 1332c19..f5afc9c 100644 --- a/crates/engine/tests/lanes.rs +++ b/crates/engine/tests/lanes.rs @@ -235,6 +235,8 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() { pin_software(); let source = asset("test_av.mp4"); let clip = Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: TOTAL, @@ -296,6 +298,8 @@ fn two_audio_lanes_are_summed() { let one_lane = Project::single(asset("test_av.mp4"), TOTAL); let mut project = one_lane.clone(); let doubled = Clip { + fade_in: 0, + fade_out: 0, start: TOP_IN, in_frame: TOP_IN, out_frame: TOP_OUT, @@ -553,6 +557,8 @@ fn a_paste_never_touches_the_captions() { let clip = *project.lane(Lane::V1).first().expect("V1 holds the film"); let pasted = Clip { + fade_in: 0, + fade_out: 0, out_frame: 30, ..clip }; diff --git a/crates/engine/tests/opus_export.rs b/crates/engine/tests/opus_export.rs index 5be6726..98fa1d3 100644 --- a/crates/engine/tests/opus_export.rs +++ b/crates/engine/tests/opus_export.rs @@ -80,6 +80,8 @@ fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { /// `sound_in` seconds into that file: an edit, so nothing here can be a copy. fn project(video: &Path, sound: &Path, sound_in: u32) -> Project { let clip = |source, in_frame, out_frame| Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame, out_frame, @@ -420,6 +422,8 @@ fn a_copied_picture_names_the_sound_it_was_written_with() { let (meta, _) = engine::demux::Demuxer::open(&video).expect("probe the picture"); let frames = meta.frame_count; let clip = |source, out_frame| Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame, diff --git a/crates/engine/tests/silence.rs b/crates/engine/tests/silence.rs index 3c756ef..bda8930 100644 --- a/crates/engine/tests/silence.rs +++ b/crates/engine/tests/silence.rs @@ -138,6 +138,8 @@ fn speed_mode_refuses_a_clip_that_laps_over_a_silence() { let lane = p.add_lane(LaneKind::Video); assert_eq!(lane.label(), "V2"); let broll = Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: 20, @@ -173,6 +175,8 @@ fn speed_mode_refuses_a_clip_that_laps_over_a_silence() { /// A clip covering the whole fixture, for a second track to carry. fn whole(source: usize, frames: u32) -> Clip { Clip { + fade_in: 0, + fade_out: 0, start: 0, in_frame: 0, out_frame: frames, diff --git a/crates/engine/tests/speed.rs b/crates/engine/tests/speed.rs index a5c4330..d96d895 100644 --- a/crates/engine/tests/speed.rs +++ b/crates/engine/tests/speed.rs @@ -516,6 +516,8 @@ fn an_mp4_export_honours_a_speeded_picture_across_a_rate_change() { Lane::V1, fast, Clip { + fade_in: 0, + fade_out: 0, speed: Speed::NORMAL, ..whole }