diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 4fabd21..86bb0d5 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -393,20 +393,25 @@ impl AudioSession { speeds: &[Option], sample_rate: Option, ) -> crate::Result)>> { - Self::open_multi_streams_speed_at_fade(sources, segs, eqs, speeds, &[], sample_rate) + // No fades on this path, so the fps a `Fade` would be rescaled by is + // never read; any finite value does. + Self::open_multi_streams_speed_at_fade(sources, segs, eqs, speeds, &[], 1.0, 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. + /// meaning flat from there on. `fps` is the timeline rate each `Fade` was + /// built at ([`crate::Project::audio_fades_from`]) -- this is the one + /// place that rate meets the audio one ([`crate::project::Fade::scaled`]). pub fn open_multi_streams_speed_at_fade( sources: &[(PathBuf, usize)], segs: &[(Option, f64, f64)], eqs: &[Option], speeds: &[Option], fades: &[Option], + fps: f64, sample_rate: Option, ) -> crate::Result)>> { // The first source that could have a track, which is not always index 0: @@ -591,11 +596,15 @@ impl AudioSession { // 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. + // each clip's own frame count against where this segment lands -- + // in timeline frames, though, which is `fps`-relative and not yet + // the rate `Fade::apply` will count samples at; `.scaled` re-counts + // it in frames of `meta.sample_rate` now that this is known. + let fade_ratio = f64::from(meta.sample_rate) / fps; let fades: Vec> = segments .iter() .enumerate() - .map(|(i, _)| fades.get(i).copied().flatten()) + .map(|(i, _)| fades.get(i).copied().flatten().map(|f| f.scaled(fade_ratio))) .collect(); let (tx, rx) = sync_channel(32); @@ -718,26 +727,30 @@ impl AudioSession { limiter: Limiter, sample_rate: Option, ) -> crate::Result)>> { + // No fades on this path -- see `open_multi_streams_speed_at`'s same + // placeholder. Self::open_mixed_streams_master_at_fade( - sources, lanes, eqs, speeds, &[], gains, limiter, sample_rate, + sources, lanes, eqs, speeds, &[], 1.0, 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). + /// `fps` is [`open_multi_streams_speed_at_fade`](Self::open_multi_streams_speed_at_fade)'s. pub fn open_mixed_streams_master_at_fade( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], speeds: &[Vec>], fades: &[Vec>], + fps: f64, 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, + sources, lanes, eqs, speeds, fades, fps, gains, limiter, None, sample_rate, ) } @@ -759,8 +772,10 @@ impl AudioSession { live: Option<&Arc>, sample_rate: Option, ) -> crate::Result)>> { + // No fades on this path -- see `open_multi_streams_speed_at`'s same + // placeholder. Self::open_mixed_streams_live_fade( - sources, lanes, eqs, speeds, &[], gains, limiter, live, sample_rate, + sources, lanes, eqs, speeds, &[], 1.0, gains, limiter, live, sample_rate, ) } @@ -768,13 +783,15 @@ impl AudioSession { /// 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. + /// the rest play flat, the eq list's rule. `fps` is the timeline rate + /// those fades were built at ([`crate::project::Fade::scaled`]). pub fn open_mixed_streams_live_fade( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], speeds: &[Vec>], fades: &[Vec>], + fps: f64, gains: &[f32], limiter: Limiter, live: Option<&Arc>, @@ -793,6 +810,7 @@ impl AudioSession { eqs.first().unwrap_or(&flat), speeds.first().unwrap_or(&plain), fades.first().unwrap_or(&flat_fade), + fps, sample_rate, ); } @@ -811,6 +829,7 @@ impl AudioSession { eqs.get(i).unwrap_or(&flat), speeds.get(i).unwrap_or(&plain), fades.get(i).unwrap_or(&flat_fade), + fps, sample_rate, )? else { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 32a9a6c..800b50a 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -592,6 +592,17 @@ fn mastered(project: &Project) -> bool { project.limiter().is_active() || project.audio_gains().iter().any(|&g| g != 1.0) } +/// Whether any audio clip has a fade -- [`equalized`]'s pair again: a fade is +/// gain math on decoded samples ([`crate::project::Fade::apply`]), and a +/// packet copy carries neither an equalizer nor a fade. An mp4 whose timeline +/// has one is decoded and re-encoded so the fade actually reaches the file. +fn faded(project: &Project) -> bool { + project + .audio_lanes() + .into_iter() + .any(|lane| project.lane(lane).iter().any(|c| c.fade_in > 0 || c.fade_out > 0)) +} + /// The bitrate an export codes at: the caller's number clamped into what an /// asked-for rate may be ([`MAX_EXPLICIT_BITRATE`]), the derived one where there /// was none. Clamped rather than refused, for the reason [`Enc::open`] states. @@ -736,6 +747,7 @@ fn forces_encode(project: &Project, ranged: bool) -> bool { .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal())) || equalized(project) || mastered(project) + || faded(project) } /// What the sound is written by. Every audio encoder here is software -- there @@ -1825,6 +1837,7 @@ fn encode_audio( &eqs, &speeds, &fades, + meta.frame_rate, &project.audio_gains(), project.limiter(), sample_rate, @@ -2996,6 +3009,7 @@ fn run_audio( &eqs, &speeds, &fades, + meta.frame_rate, &project.audio_gains(), project.limiter(), sample_rate, @@ -4897,6 +4911,24 @@ mod tests { assert_eq!(asked(1), MIN_BITRATE, "and floored"); } + /// A clip's fade takes the copy path away, exactly as an equalizer does: + /// a copied AAC packet cannot carry gain math nobody put in the file. The + /// bug this guards is [`forces_encode`] gating on `equalized`/`mastered` + /// but never checking a clip's own `fade_in`/`fade_out` at all -- the + /// default Web MP4 export then labelled and took the "AAC copy" path for + /// a project whose picture showed a fade, and the fade never reached the + /// file. + #[test] + fn a_fade_forces_the_audio_to_be_re_encoded() { + let mut project = Project::single("/nonexistent/film.mp4", 90); + assert!(!forces_encode(&project, false), "flat, so a copy is fine"); + assert!(project.set_fade_in(crate::project::Lane::new(crate::project::LaneKind::Audio, 0), 0, 15)); + assert!( + forces_encode(&project, false), + "a fade-in on the only clip must force a re-encode" + ); + } + fn meta(width: u32, height: u32) -> VideoMeta { VideoMeta { width, diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 491c2fb..9ee5740 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -3347,6 +3347,7 @@ impl PlaybackSession { &eqs, &speeds, &fades, + fps, &gains, limiter, Some(&worker_controls), diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index ce3a325..2464391 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -822,6 +822,29 @@ impl Fade { } } } + + /// Every field re-counted at `ratio` frames-out per frame-in, rounded to + /// the nearest whole frame. [`Project::lane_fades_from`] builds a `Fade` + /// in *timeline* frames ([`Clip::fade_in`]'s own unit, the fps every clip + /// position is in) but [`Self::apply`] multiplies *audio* frames -- + /// `channels`-wide sample blocks at whatever rate the mix is running at, + /// which is almost never the video's fps. Left unconverted, `elapsed` (an + /// audio-frame count) raced past `total`/`fade_out` (fps-frame counts) a + /// few milliseconds into any clip, so a fade-out silenced the rest of the + /// clip outright and a fade-in finished before a listener's ear caught up + /// -- audible on nothing shorter than a clip a few fps-frames long, which + /// is why 338 green tests never once ran the two curves out of step. + /// `ratio` is `sample_rate / fps`, applied once where the audio session + /// first learns its own rate ([`crate::AudioSession::open_multi_streams_speed_at_fade`]). + pub fn scaled(self, ratio: f64) -> Fade { + let conv = |f: u32| (f64::from(f) * ratio).round() as u32; + Fade { + elapsed: conv(self.elapsed), + fade_in: conv(self.fade_in), + fade_out: conv(self.fade_out), + total: conv(self.total), + } + } } /// What a save writes and a load takes back: the sources, every lane in diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 495d32b..8ccfa79 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -901,6 +901,195 @@ fn exports_the_timeline_as_an_ogg_vorbis() { std::fs::remove_file(&out).unwrap(); } +/// A synthetic 44.1 kHz stereo WAV of a constant-amplitude 440 Hz tone, +/// `secs` long, as plain a RIFF header as `a_mono_timeline_exports_as_dual_mono_ogg` +/// writes -- no fixture needed, since a fade's shape is a claim about level +/// over time and a flat tone is the cleanest body to shape. +fn tone_wav(path: &Path, secs: f64) { + let frames = (secs * f64::from(RATE)) as usize; + let data = (frames * 4) as u32; // stereo, 16-bit + let mut wav = Vec::with_capacity(44 + frames * 4); + wav.extend_from_slice(b"RIFF"); + wav.extend_from_slice(&(36 + data).to_le_bytes()); + wav.extend_from_slice(b"WAVEfmt "); + wav.extend_from_slice(&16u32.to_le_bytes()); + wav.extend_from_slice(&1u16.to_le_bytes()); // PCM + wav.extend_from_slice(&2u16.to_le_bytes()); // stereo + wav.extend_from_slice(&RATE.to_le_bytes()); + wav.extend_from_slice(&(RATE * 4).to_le_bytes()); // byte rate + wav.extend_from_slice(&4u16.to_le_bytes()); // block align + wav.extend_from_slice(&16u16.to_le_bytes()); + wav.extend_from_slice(b"data"); + wav.extend_from_slice(&data.to_le_bytes()); + for i in 0..frames { + let t = i as f64 / f64::from(RATE); + let s = (0.8 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() * 32767.0) as i16; + wav.extend_from_slice(&s.to_le_bytes()); + wav.extend_from_slice(&s.to_le_bytes()); + } + std::fs::write(path, &wav).expect("write the tone fixture"); +} + +/// Regression for the export that drew a fade in the UI and stored it on the +/// clip but never carried it into the written file: a single clip with a +/// 1.5 s fade-in, exported as a WAV, must actually be quiet at the start and +/// rise across the ramp -- not the source's own flat level from sample zero. +#[test] +fn a_fade_in_reaches_the_exported_audio() { + let src = out_path("fadein_src", "wav"); + tone_wav(&src, 3.0); + let fps = 30.0; + let clip = Clip { + fade_in: 45, // 1.5 s at 30 fps + fade_out: 0, + transition_out: 0, + start: 0, + in_frame: 0, + out_frame: 90, // 3.0 s at 30 fps + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + let project = Project::from_parts( + vec![Source::new(src.to_path_buf(), 0)], + vec![(LaneKind::Audio, vec![clip])], + Vec::new(), + Vec::new(), + ) + .expect("a one-clip fade-in project"); + let meta = engine::VideoMeta { + width: 1, + height: 1, + frame_rate: fps, + frame_count: 90, + codec: engine::Codec::H264, + color: Default::default(), + }; + let out = out_path("fadein", "wav"); + let handle = engine::export::start( + project, + meta, + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + None, + ); + wait(&handle, Duration::from_secs(60)).expect("wav export of a faded clip"); + + let (audio, samples) = decode(&out); + let channels = usize::from(audio.channels); + let body = rms(&samples, channels, 2.0, 2.9); + let start = rms(&samples, channels, 0.0, 0.1); + let quarter = rms(&samples, channels, 0.3, 0.4); + let half = rms(&samples, channels, 0.7, 0.8); + let near_end = rms(&samples, channels, 1.35, 1.45); + println!( + "fade-in rms: start {start:.4} quarter {quarter:.4} half {half:.4} \ + near-end {near_end:.4} body {body:.4}" + ); + assert!(body > 0.3, "the tone's own body is audible: {body:.4}"); + assert!( + start < body * 0.1, + "the very start is quiet: {start:.4} vs body {body:.4}" + ); + assert!(quarter < half, "the envelope rises: {quarter:.4} -> {half:.4}"); + assert!( + half < near_end, + "the envelope keeps rising into the ramp's end: {half:.4} -> {near_end:.4}" + ); + assert!( + (near_end - body).abs() < body * 0.15, + "past the ramp the level settles at the body's own: {near_end:.4} vs {body:.4}" + ); + std::fs::remove_file(&out).unwrap(); + std::fs::remove_file(&src).unwrap(); +} + +/// Regression for the worse of the two bugs: a clip split in two and +/// cross-faded at the join used to go silent for its *entire* remaining +/// length once the fade's frame count (a handful of fps-frames) was read as +/// a sample count (a mixed-rate quantity thousands of times larger) -- the +/// gain curve's tail condition was true from a few milliseconds in to the +/// end of the segment. The first half's own interior, well clear of either +/// edge, must still be at the tone's own level. +#[test] +fn a_split_and_crossfaded_clip_has_no_muted_interior() { + let src = out_path("crossfade_src", "wav"); + tone_wav(&src, 3.0); + let fps = 30.0; + let clip = |start, in_frame, out_frame| Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, + start, + in_frame, + out_frame, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + // The clip split at 1.5 s (45 frames @ 30 fps) into two adjacent halves, + // exactly what `Project::split` leaves behind. + let mut project = Project::from_parts( + vec![Source::new(src.to_path_buf(), 0)], + vec![( + LaneKind::Audio, + vec![clip(0, 0, 45), clip(45, 45, 90)], + )], + Vec::new(), + Vec::new(), + ) + .expect("a split clip on one audio lane"); + assert!( + project.crossfade(Lane::new(LaneKind::Audio, 0), 0, 15), + "adjacent halves cross-fade at their join" + ); + let meta = engine::VideoMeta { + width: 1, + height: 1, + frame_rate: fps, + frame_count: 90, + codec: engine::Codec::H264, + color: Default::default(), + }; + let out = out_path("crossfade", "wav"); + let handle = engine::export::start( + project, + meta, + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + None, + ); + wait(&handle, Duration::from_secs(60)).expect("wav export of a cross-faded split"); + + let (audio, samples) = decode(&out); + let channels = usize::from(audio.channels); + // The source's own flat level, read off a stretch with no fade anywhere + // near it (the second half's own interior, past its fade-in). + let reference = rms(&samples, channels, 2.0, 2.9); + // The first half's interior: from just past 0 to well before its own + // fade-out starts at 1.0 s (45 - 15 frames = 30 frames @ 30 fps). + let interior = rms(&samples, channels, 0.1, 0.9); + println!("crossfade rms: interior {interior:.4} reference {reference:.4}"); + assert!( + interior > reference * 0.7, + "the first half's interior is not muted: {interior:.4} vs reference {reference:.4}" + ); + std::fs::remove_file(&out).unwrap(); + std::fs::remove_file(&src).unwrap(); +} + /// A **mono** timeline through the same door. `rusty_vorbis` ships one embedded /// setup header and it is a stereo profile -- a mono push is refused outright /// ("bad coupling channels") -- so `export::write_ogg` writes the mix as dual