Skip to content

programmatic video rendering framework that is actually fast

feat(fframes): per-track audio effects (#219)

Dmitriy Kovalenko44f5431ce630
diff --git a/AGENTS.md b/AGENTS.md
index 0c1aa400..364f6990 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -545,8 +545,38 @@ AudioMap::from([
range renders) get 5 ms de-click fades.
- Verify without listening: `audio analyze` (integrated/short-term loudness in LUFS, true
peak, clipping, silent ranges, loudness per scene, `--waveform` PNG with scenes and cues)
- and `audio at 4.2s` (which files play, where in the file, at what level, ducked or not).
- Aim for about -14 LUFS integrated for web video and a true peak below -1 dBTP.
+ and `audio at 4.2s` (which files play, where in the file, at what level, ducked or not,
+ rate and effects). Aim for about -14 LUFS integrated for web video and a true peak below
+ -1 dBTP.
+
+Per-track effects master the takes inside `fn audio`, no ffmpeg pass before the mix:
+
+```rust
+use fframes::{AudioTrack, AudioTimestamp::*, Compressor};
+
+AudioTrack::new("voice.wav", Second(1.)..Eof)
+ .highpass(80.) // 12 dB/oct, Butterworth; twice for 24 dB/oct
+ .peak(3000., 2.5, 1.2) // hz, db, q
+ .high_shelf(9000., -3.) // hz, db (half of db at hz); also low_shelf
+ .compress(Compressor { threshold_db: -24., ratio: 3., ..Default::default() })
+ .normalize_lufs(-16.) // integrated loudness of the played part
+ .gain_db(-1.) // applies after the effects
+ .voice();
+AudioTrack::new("whoosh.wav", Second(4.)..Eof).rate(0.8).width(1.5); // a lower, longer, wider variation
+```
+
+- Order: the file is read at `rate`, then the effects run in the order of the calls, then
+ gain, pan, fades and ducking. Filters run at the mix rate, after the rate change.
+- `rate(f)` changes speed and pitch together like a tape. A range that ends at `Eof` follows
+ the new length. `offset` stays in seconds of the file.
+- `compress`: feed-forward, peak detector, both channels linked; `Compressor::default()` is
+ -18 dB, 3:1, 10 ms attack, 150 ms release, 6 dB soft knee.
+- `width(w)`: mid/side, 0 mono, 1 unchanged, above 1 wider; the mono sum does not change. A
+ mono file becomes stereo (a delayed, high-passed side signal).
+- `normalize_lufs` measures after the effects before it, so put it after `compress`.
+- The mixer renders a track with effects once, when it is built (one per render, preview or
+ `audio` command). It keeps the played part in memory at the mix rate: 23 MB per stereo
+ minute at 48 kHz. Tracks without effects are read from the file as before.
### 8. Render it: `fframes::cli`
diff --git a/fframes/src/audio_analysis.rs b/fframes/src/audio_analysis.rs
index 1be8c1f5..e58324f1 100644
--- a/fframes/src/audio_analysis.rs
+++ b/fframes/src/audio_analysis.rs
@@ -9,14 +9,23 @@ use std::ops::Range;
/// Biquad in transposed direct form II, f64 state.
#[derive(Clone, Copy)]
-struct Biquad {
+pub(crate) struct Biquad {
b: [f64; 3],
a: [f64; 2],
z: [f64; 2],
}
impl Biquad {
- fn process(&mut self, x: f64) -> f64 {
+ /// A filter from the coefficients of `H(z) = (b0 + b1/z + b2/z^2) / (a0 + a1/z + a2/z^2)`.
+ pub(crate) fn new(b: [f64; 3], a: [f64; 3]) -> Self {
+ Self {
+ b: b.map(|b| b / a[0]),
+ a: [a[1] / a[0], a[2] / a[0]],
+ z: [0.; 2],
+ }
+ }
+
+ pub(crate) fn process(&mut self, x: f64) -> f64 {
let y = self.b[0] * x + self.z[0];
self.z[0] = self.b[1] * x - self.a[0] * y + self.z[1];
self.z[1] = self.b[2] * x - self.a[1] * y;
diff --git a/fframes/src/audio_effects.rs b/fframes/src/audio_effects.rs
new file mode 100644
index 00000000..be28856f
--- /dev/null
+++ b/fframes/src/audio_effects.rs
@@ -0,0 +1,456 @@
+//! Per-track effects: loudness normalization, RBJ biquad filters, a compressor and stereo
+//! width. See `AudioTrack::highpass` and the other builder methods.
+//!
+//! The mixer renders a track with effects once, when the mixer is built. It reads the part of
+//! the file that plays at the mix rate (resampled, at the track's `rate`). Then it runs the
+//! effects in the order of the calls. Gain, pan, fades and ducking apply after the effects.
+use crate::audio_analysis::{Biquad, LoudnessAnalysis};
+use serde::Serialize;
+use std::f64::consts::TAU;
+use std::fmt;
+
+/// One processing step of a track, see the `AudioTrack` methods with the same names.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Effect {
+ /// Gain that brings the integrated loudness of the track to `lufs`.
+ NormalizeLufs {
+ lufs: f32,
+ },
+ /// 12 dB per octave below `hz`. `q` 0.707 is Butterworth (-3 dB at `hz`).
+ Highpass {
+ hz: f32,
+ q: f32,
+ },
+ /// 12 dB per octave above `hz`. `q` 0.707 is Butterworth (-3 dB at `hz`).
+ Lowpass {
+ hz: f32,
+ q: f32,
+ },
+ /// `db` below `hz`, half of `db` at `hz`.
+ LowShelf {
+ hz: f32,
+ db: f32,
+ },
+ /// `db` above `hz`, half of `db` at `hz`.
+ HighShelf {
+ hz: f32,
+ db: f32,
+ },
+ /// Bell: `db` at `hz`, bandwidth `hz / q`.
+ Peak {
+ hz: f32,
+ db: f32,
+ q: f32,
+ },
+ Compress(Compressor),
+ /// Mid/side width: 0 mono, 1 unchanged, above 1 wider.
+ Width {
+ width: f32,
+ },
+}
+
+/// Feed-forward compressor with a peak detector, linked on both channels.
+///
+/// The input level is the larger absolute sample of the two channels. The static curve turns
+/// this level into a gain reduction in dB. A smooth decoupled peak detector (Giannoulis,
+/// Massberg and Reiss, 2012) follows the reduction: it holds the peaks with `release`, and
+/// then smooths the result with `attack`. Thus the compressor reacts to peaks, also on short
+/// hits, and a steady tone gets the gain of the static curve at its peak level.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
+pub struct Compressor {
+ /// Level in dBFS above which the compressor reduces the gain. Default `-18.0`.
+ pub threshold_db: f32,
+ /// Input dB above the threshold for each output dB. `1.0` does nothing, `20.0` and more
+ /// is a limiter. Default `3.0`.
+ pub ratio: f32,
+ /// Time constant in seconds of the gain going down (63% of a step). Default `0.01`.
+ pub attack: f32,
+ /// Time constant in seconds of the gain coming back. Default `0.15`.
+ pub release: f32,
+ /// Width in dB of the soft knee around the threshold, `0.0` is a hard knee. Default `6.0`.
+ pub knee_db: f32,
+ /// Gain in dB after the compression. Default `0.0`.
+ pub makeup_db: f32,
+}
+
+impl Default for Compressor {
+ fn default() -> Self {
+ Self {
+ threshold_db: -18.,
+ ratio: 3.,
+ attack: 0.01,
+ release: 0.15,
+ knee_db: 6.,
+ makeup_db: 0.,
+ }
+ }
+}
+
+impl Compressor {
+ /// Output level in dB for a steady input level in dB.
+ pub fn static_curve(&self, input_db: f32) -> f32 {
+ let over = input_db - self.threshold_db;
+ let slope = 1. / self.ratio.max(1.) - 1.;
+ let knee = self.knee_db.max(0.);
+ if 2. * over <= -knee {
+ input_db
+ } else if 2. * over.abs() < knee {
+ input_db + slope * (over + knee / 2.).powi(2) / (2. * knee)
+ } else {
+ input_db + slope * over
+ }
+ }
+
+ fn process(&self, channels: &mut [Vec<f32>], sample_rate: f64) {
+ let coefficient = |seconds: f32| (-1. / (f64::from(seconds).max(1e-5) * sample_rate)).exp();
+ let (attack, release) = (coefficient(self.attack), coefficient(self.release));
+ let makeup = f64::from(self.makeup_db);
+ let (mut held, mut reduction) = (0f64, 0.);
+
+ for i in 0..channels[0].len() {
+ let peak = channels.iter().fold(0f32, |m, c| m.max(c[i].abs()));
+ let level = 20. * peak.max(1e-9).log10();
+ let target = f64::from(level - self.static_curve(level));
+ held = target.max(release * held + (1. - release) * target);
+ reduction = attack * reduction + (1. - attack) * held;
+ let gain = db_to_gain(makeup - reduction);
+ for channel in channels.iter_mut() {
+ channel[i] = (f64::from(channel[i]) * gain) as f32;
+ }
+ }
+ }
+}
+
+fn db_to_gain(db: f64) -> f64 {
+ 10f64.powf(db / 20.)
+}
+
+/// RBJ Audio EQ Cookbook filters. Frequencies stay below Nyquist.
+fn biquad(effect: &Effect, sample_rate: f64) -> Option<Biquad> {
+ let omega = |hz: f32| TAU * f64::from(hz).clamp(1., sample_rate * 0.49) / sample_rate;
+ let alpha = |w: f64, q: f32| w.sin() / (2. * f64::from(q).max(0.05));
+ Some(match *effect {
+ Effect::Highpass { hz, q } => {
+ let w = omega(hz);
+ let (cos, alpha) = (w.cos(), alpha(w, q));
+ let b = f64::midpoint(1., cos);
+ Biquad::new([b, -2. * b, b], [1. + alpha, -2. * cos, 1. - alpha])
+ }
+ Effect::Lowpass { hz, q } => {
+ let w = omega(hz);
+ let (cos, alpha) = (w.cos(), alpha(w, q));
+ let b = f64::midpoint(1., -cos);
+ Biquad::new([b, 2. * b, b], [1. + alpha, -2. * cos, 1. - alpha])
+ }
+ Effect::Peak { hz, db, q } => {
+ let w = omega(hz);
+ let (cos, alpha) = (w.cos(), alpha(w, q));
+ let a = 10f64.powf(f64::from(db) / 40.);
+ Biquad::new(
+ [1. + alpha * a, -2. * cos, 1. - alpha * a],
+ [1. + alpha / a, -2. * cos, 1. - alpha / a],
+ )
+ }
+ Effect::LowShelf { hz, db } | Effect::HighShelf { hz, db } => {
+ let w = omega(hz);
+ let a = 10f64.powf(f64::from(db) / 40.);
+ // Shelf slope S = 1: the steepest slope without a bump.
+ let (cos, k) = (w.cos(), a.sqrt() * w.sin() * std::f64::consts::SQRT_2);
+ // A high shelf is the low shelf with the sign of `cos` swapped.
+ let (sign, cos) = match effect {
+ Effect::LowShelf { .. } => (1., cos),
+ _ => (-1., -cos),
+ };
+ Biquad::new(
+ [
+ a * ((a + 1.) - (a - 1.) * cos + k),
+ sign * 2. * a * ((a - 1.) - (a + 1.) * cos),
+ a * ((a + 1.) - (a - 1.) * cos - k),
+ ],
+ [
+ (a + 1.) + (a - 1.) * cos + k,
+ sign * -2. * ((a - 1.) + (a + 1.) * cos),
+ (a + 1.) + (a - 1.) * cos - k,
+ ],
+ )
+ }
+ Effect::NormalizeLufs { .. } | Effect::Compress(_) | Effect::Width { .. } => return None,
+ })
+}
+
+/// Seconds of delay of the side signal made for a mono track.
+const MONO_SIDE_DELAY: f64 = 0.012;
+/// Below this frequency the side signal made for a mono track is cut, so the bass stays mono.
+const MONO_SIDE_HIGHPASS: f32 = 250.;
+/// Level of the side signal made for a mono track, for each unit of width.
+const MONO_SIDE_LEVEL: f32 = 0.3;
+
+fn width(channels: &mut Vec<Vec<f32>>, width: f32, sample_rate: f64) {
+ let width = width.max(0.);
+ if let [left, right] = channels.as_mut_slice() {
+ if width == 1. {
+ return;
+ }
+ for (l, r) in left.iter_mut().zip(right.iter_mut()) {
+ let mid = f32::midpoint(*l, *r);
+ let side = (*l - *r) * 0.5 * width;
+ (*l, *r) = (mid + side, mid - side);
+ }
+ } else if width > 0. {
+ // The side is the mono signal, delayed and high-passed. L = M + S and R = M - S, so
+ // the mono sum L + R stays 2M at every frequency.
+ let mid = &channels[0];
+ let delay = (MONO_SIDE_DELAY * sample_rate).round() as usize;
+ let mut highpass = biquad(
+ &Effect::Highpass {
+ hz: MONO_SIDE_HIGHPASS,
+ q: std::f32::consts::FRAC_1_SQRT_2,
+ },
+ sample_rate,
+ )
+ .expect("a highpass is a biquad");
+ let level = (MONO_SIDE_LEVEL * width).min(1.);
+ let side: Vec<f32> = (0..mid.len())
+ .map(|i| {
+ let delayed = i.checked_sub(delay).map_or(0., |j| mid[j]);
+ highpass.process(f64::from(delayed)) as f32 * level
+ })
+ .collect();
+ let right = mid.iter().zip(&side).map(|(m, s)| m - s).collect();
+ channels[0].iter_mut().zip(&side).for_each(|(m, s)| *m += s);
+ channels.push(right);
+ }
+}
+
+/// Runs `effects` in order on one or two channels at `sample_rate`. A mono track becomes
+/// stereo after `Width`. Returns the sum of the gains in dB that `NormalizeLufs` applied.
+pub(crate) fn apply_effects(
+ effects: &[Effect],
+ sample_rate: usize,
+ channels: &mut Vec<Vec<f32>>,
+) -> f32 {
+ let rate = sample_rate as f64;
+ let mut normalize_db = 0.;
+ for effect in effects {
+ match effect {
+ Effect::NormalizeLufs { lufs } => {
+ let (left, right) = (&channels[0], &channels[channels.len() - 1]);
+ // A mono track plays on both sides, so it is measured on both sides.
+ let measured =
+ LoudnessAnalysis::new(left, right, sample_rate).integrated(0..left.len());
+ // Silence and tracks shorter than one 400 ms block have no loudness.
+ if measured.is_finite() {
+ let db = f64::from(*lufs) - measured;
+ let gain = db_to_gain(db) as f32;
+ channels.iter_mut().flatten().for_each(|s| *s *= gain);
+ normalize_db += db as f32;
+ }
+ }
+ Effect::Compress(compressor) => compressor.process(channels, rate),
+ Effect::Width { width: w } => width(channels, *w, rate),
+ filter => {
+ if let Some(filter) = biquad(filter, rate) {
+ for channel in channels.iter_mut() {
+ let mut filter = filter;
+ for s in channel {
+ *s = filter.process(f64::from(*s)) as f32;
+ }
+ }
+ }
+ }
+ }
+ }
+ normalize_db
+}
+
+impl fmt::Display for Effect {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Effect::NormalizeLufs { lufs } => write!(f, "normalize {lufs:.1} LUFS"),
+ Effect::Highpass { hz, q } => write!(f, "highpass {hz:.0} Hz Q {q:.2}"),
+ Effect::Lowpass { hz, q } => write!(f, "lowpass {hz:.0} Hz Q {q:.2}"),
+ Effect::LowShelf { hz, db } => write!(f, "low shelf {hz:.0} Hz {db:+.1} dB"),
+ Effect::HighShelf { hz, db } => write!(f, "high shelf {hz:.0} Hz {db:+.1} dB"),
+ Effect::Peak { hz, db, q } => write!(f, "peak {hz:.0} Hz {db:+.1} dB Q {q:.2}"),
+ Effect::Compress(c) => write!(
+ f,
+ "compress {:.1} dB {:.1}:1 {:.0}/{:.0} ms",
+ c.threshold_db,
+ c.ratio,
+ c.attack * 1000.,
+ c.release * 1000.
+ ),
+ Effect::Width { width } => write!(f, "width {width:.2}"),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const RATE: usize = 48000;
+
+ fn sine(hz: f64, amplitude: f32, seconds: f64) -> Vec<f32> {
+ (0..(seconds * RATE as f64) as usize)
+ .map(|i| amplitude * (TAU * hz * i as f64 / RATE as f64).sin() as f32)
+ .collect()
+ }
+
+ fn rms_db(samples: &[f32]) -> f64 {
+ let mean =
+ samples.iter().map(|s| f64::from(*s).powi(2)).sum::<f64>() / samples.len() as f64;
+ 10. * mean.log10()
+ }
+
+ /// Gain in dB of `effect` for a sine of `hz`, measured after the filter settles.
+ fn response_db(effect: Effect, hz: f64) -> f64 {
+ let mut channels = vec![sine(hz, 0.5, 1.)];
+ apply_effects(&[effect], RATE, &mut channels);
+ let tail = RATE / 2..RATE;
+ rms_db(&channels[0][tail.clone()]) - rms_db(&sine(hz, 0.5, 1.)[tail])
+ }
+
+ #[track_caller]
+ fn assert_near(value: f64, expected: f64, tolerance: f64) {
+ assert!(
+ (value - expected).abs() <= tolerance,
+ "{value:.3} is not {expected} ± {tolerance}"
+ );
+ }
+
+ #[test]
+ fn highpass_and_lowpass_are_butterworth() {
+ let highpass = Effect::Highpass {
+ hz: 200.,
+ q: std::f32::consts::FRAC_1_SQRT_2,
+ };
+ assert_near(response_db(highpass, 200.), -3.01, 0.1);
+ assert!(response_db(highpass, 30.) < -20.);
+ assert_near(response_db(highpass, 2000.), 0., 0.05);
+
+ let lowpass = Effect::Lowpass {
+ hz: 2000.,
+ q: std::f32::consts::FRAC_1_SQRT_2,
+ };
+ assert_near(response_db(lowpass, 2000.), -3.01, 0.1);
+ assert!(response_db(lowpass, 16000.) < -30.);
+ assert_near(response_db(lowpass, 100.), 0., 0.05);
+ }
+
+ #[test]
+ fn shelves_and_peak_reach_their_gain() {
+ let low = Effect::LowShelf { hz: 200., db: 6. };
+ assert_near(response_db(low, 20.), 6., 0.2);
+ assert_near(response_db(low, 200.), 3., 0.1);
+ assert_near(response_db(low, 8000.), 0., 0.1);
+
+ let high = Effect::HighShelf { hz: 4000., db: -9. };
+ assert_near(response_db(high, 18000.), -9., 0.3);
+ assert_near(response_db(high, 4000.), -4.5, 0.1);
+ assert_near(response_db(high, 100.), 0., 0.1);
+
+ let peak = Effect::Peak {
+ hz: 1000.,
+ db: 5.,
+ q: 2.,
+ };
+ assert_near(response_db(peak, 1000.), 5., 0.05);
+ assert_near(response_db(peak, 100.), 0., 0.1);
+ assert_near(response_db(peak, 10000.), 0., 0.1);
+ }
+
+ #[test]
+ fn compressor_follows_its_static_curve() {
+ let compressor = Compressor {
+ threshold_db: -20.,
+ ratio: 4.,
+ attack: 0.005,
+ release: 0.1,
+ knee_db: 6.,
+ makeup_db: 0.,
+ };
+ // A sine with its peaks at -30 dBFS for 1 s, then at 0 dBFS for 1 s.
+ let quiet = sine(1000., 10f32.powf(-30. / 20.), 1.);
+ let mut input = quiet.clone();
+ input.extend(sine(1000., 1., 1.));
+ let mut channels = vec![input.clone(), input];
+ apply_effects(&[Effect::Compress(compressor)], RATE, &mut channels);
+
+ // Below the threshold and the knee the samples do not change at all.
+ assert_eq!(channels[0][..RATE], quiet[..]);
+ assert_eq!(channels[0], channels[1]);
+
+ let peak_db = |range: std::ops::Range<usize>| {
+ 20. * channels[0][range]
+ .iter()
+ .fold(0f32, |m, s| m.max(s.abs()))
+ .log10()
+ };
+ let expected = compressor.static_curve(0.);
+ assert_near(f64::from(expected), -15., 1e-6);
+ // Five attack time constants (25 ms) after the step the level is on the curve.
+ let ms = RATE / 1000;
+ assert_near(
+ f64::from(peak_db(RATE + 25 * ms..RATE + 30 * ms)),
+ -15.,
+ 0.5,
+ );
+ assert_near(f64::from(peak_db(RATE + 500 * ms..2 * RATE)), -15., 0.1);
+ }
+
+ #[test]
+ fn compressor_releases_after_a_hit() {
+ let compressor = Compressor::default();
+ let mut input = sine(1000., 1., 0.5);
+ input.extend(sine(1000., 0.01, 1.));
+ let mut channels = vec![input];
+ apply_effects(&[Effect::Compress(compressor)], RATE, &mut channels);
+ let peak = |range: std::ops::Range<usize>| {
+ channels[0][range].iter().fold(0f32, |m, s| m.max(s.abs()))
+ };
+ // Five release time constants (750 ms) after the hit the gain is back to unity.
+ assert_near(
+ f64::from(peak(RATE / 2 + RATE * 3 / 4..RATE * 3 / 2)),
+ 0.01,
+ 1e-4,
+ );
+ }
+
+ #[test]
+ fn width_scales_the_side() {
+ let left = sine(300., 0.5, 0.5);
+ let right = sine(700., 0.4, 0.5);
+
+ let mut mono = vec![left.clone(), right.clone()];
+ apply_effects(&[Effect::Width { width: 0. }], RATE, &mut mono);
+ assert_eq!(mono[0], mono[1]);
+
+ let mut same = vec![left.clone(), right.clone()];
+ apply_effects(&[Effect::Width { width: 1. }], RATE, &mut same);
+ assert_eq!(same, [left.clone(), right.clone()]);
+
+ let mut wide = vec![left.clone(), right.clone()];
+ apply_effects(&[Effect::Width { width: 1.8 }], RATE, &mut wide);
+ let sum =
+ |c: &[Vec<f32>]| -> Vec<f32> { c[0].iter().zip(&c[1]).map(|(l, r)| l + r).collect() };
+ assert_near(rms_db(&sum(&wide)), rms_db(&sum(&[left, right])), 0.5);
+ }
+
+ #[test]
+ fn width_on_a_mono_track_makes_it_stereo_and_keeps_the_mono_sum() {
+ let tone = sine(1000., 0.5, 0.5);
+ let mut channels = vec![tone.clone()];
+ apply_effects(&[Effect::Width { width: 1.5 }], RATE, &mut channels);
+ assert_eq!(channels.len(), 2);
+ assert_ne!(channels[0], channels[1]);
+ for i in 0..tone.len() {
+ assert!((channels[0][i] + channels[1][i] - 2. * tone[i]).abs() < 1e-6);
+ }
+
+ let mut unchanged = vec![tone.clone()];
+ apply_effects(&[Effect::Width { width: 0. }], RATE, &mut unchanged);
+ assert_eq!(unchanged, [tone]);
+ }
+}
diff --git a/fframes/src/audio_map.rs b/fframes/src/audio_map.rs
index d2b2ac11..05a60089 100644
--- a/fframes/src/audio_map.rs
+++ b/fframes/src/audio_map.rs
@@ -1,4 +1,6 @@
-use crate::{FFramesContext, ResolvedScenesTimeline, ScenesWithAudio, TimeBase, error};
+use crate::{
+ Compressor, Effect, FFramesContext, ResolvedScenesTimeline, ScenesWithAudio, TimeBase, error,
+};
use serde::Serialize;
use std::{
iter::FromIterator,
@@ -137,32 +139,36 @@ impl AudioTimestamp<'_> {
}
}
- /// The timestamp in exact seconds. `eof_base` is added to the file duration for `Eof`
- /// (the start of the range minus the part of the file that is skipped).
+ /// The timestamp in exact seconds. For `Eof` it is the file duration divided by
+ /// `eof_rate` (the playback rate) plus `eof_base` (the start of the range minus the
+ /// timeline time of the part of the file that is skipped).
pub(crate) fn to_seconds(
&self,
filename: &str,
fps: usize,
eof_base: Option<f64>,
+ eof_rate: f64,
resolve_audio_duration: &impl Fn(&str) -> error::Result<f64>,
) -> error::Result<f64> {
Ok(match self {
AudioTimestamp::Frame(frame) => *frame as f64 / fps as f64,
AudioTimestamp::Second(seconds) => f64::from(*seconds),
- AudioTimestamp::Eof => resolve_audio_duration(filename)? + eof_base.unwrap_or(0.),
+ AudioTimestamp::Eof => {
+ resolve_audio_duration(filename)? / eof_rate + eof_base.unwrap_or(0.)
+ }
AudioTimestamp::DurationOfAudio(filename) => resolve_audio_duration(filename)?,
AudioTimestamp::Time { minutes, seconds } => {
f64::from(*minutes) * 60. + f64::from(*seconds)
}
AudioTimestamp::__Add(add) => {
let (a, b) = &**add;
- a.to_seconds(filename, fps, eof_base, resolve_audio_duration)?
- + b.to_seconds(filename, fps, eof_base, resolve_audio_duration)?
+ a.to_seconds(filename, fps, eof_base, eof_rate, resolve_audio_duration)?
+ + b.to_seconds(filename, fps, eof_base, eof_rate, resolve_audio_duration)?
}
AudioTimestamp::__Subtract(sub) => {
let (a, b) = &**sub;
- a.to_seconds(filename, fps, eof_base, resolve_audio_duration)?
- - b.to_seconds(filename, fps, eof_base, resolve_audio_duration)?
+ a.to_seconds(filename, fps, eof_base, eof_rate, resolve_audio_duration)?
+ - b.to_seconds(filename, fps, eof_base, eof_rate, resolve_audio_duration)?
}
}
.max(0.))
@@ -236,7 +242,10 @@ impl Default for Ducking {
}
/// How a track is mixed. Everything defaults to "play the file as is".
-#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
+///
+/// Order: the mixer reads the file at `rate`, runs `effects` in order, then applies
+/// `gain_db`, pan, fades and ducking.
+#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TrackMix {
/// Level in decibels, `0.0` is the file's level.
pub gain_db: f32,
@@ -253,6 +262,10 @@ pub struct TrackMix {
pub duck: Option<Ducking>,
/// This track is a voice: other tracks with `duck` get quieter while it plays.
pub voice: bool,
+ /// Playback speed of the file, `1.0` is the original speed and pitch.
+ pub rate: f32,
+ /// Processing steps in order, see `Effect`.
+ pub effects: Vec<Effect>,
}
impl Default for TrackMix {
@@ -266,6 +279,8 @@ impl Default for TrackMix {
offset: 0.,
duck: None,
voice: false,
+ rate: 1.,
+ effects: Vec::new(),
}
}
}
@@ -297,6 +312,7 @@ impl<'a> AudioTrack<'a> {
}
}
+ /// Level in decibels. It applies after the effects, so it adds to `normalize_lufs`.
pub fn gain_db(mut self, gain_db: f32) -> Self {
self.mix.gain_db = gain_db;
self
@@ -349,6 +365,85 @@ impl<'a> AudioTrack<'a> {
self.mix.duck = Some(ducking);
self
}
+
+ /// Plays the file faster (`2.0`) or slower (`0.5`), with speed and pitch together like a
+ /// tape. `rate(1.06)` is one semitone up. The track's length on the timeline follows: a
+ /// range that ends at `Eof` ends when the file ends at this rate. `offset` stays in
+ /// seconds of the file. The rate applies first, when the file is read, so the effects see
+ /// the changed pitch. Values are clamped to `0.05..=20.0`.
+ pub fn rate(mut self, rate: f32) -> Self {
+ self.mix.rate = rate.clamp(0.05, 20.);
+ self
+ }
+
+ /// Adds an effect after the effects that are already on the track.
+ ///
+ /// The mixer renders a track with effects once per render. It reads the played part of
+ /// the file at the mix rate, then runs the effects in the order of the calls. Gain, pan,
+ /// fades and ducking apply after the effects. Filters run at the mix rate, after `rate`.
+ pub fn effect(mut self, effect: Effect) -> Self {
+ self.mix.effects.push(effect);
+ self
+ }
+
+ /// Changes the level so that the integrated loudness (EBU R128, the value of
+ /// `audio analyze`) of the track is `lufs`. The measurement is on the part of the file
+ /// that plays, after the effects before this one. `gain_db` adds to the result. A track
+ /// shorter than 400 ms or silent does not change. A mono track is measured as it plays,
+ /// on both sides. Usual targets: `-16.0` for voice, `-23.0` for background music.
+ pub fn normalize_lufs(self, lufs: f32) -> Self {
+ self.effect(Effect::NormalizeLufs { lufs })
+ }
+
+ /// Removes the sound below `hz`: 12 dB per octave, Butterworth (-3 dB at `hz`). Call it
+ /// twice for 24 dB per octave (Linkwitz-Riley, -6 dB at `hz`). For another Q, use
+ /// `effect(Effect::Highpass { hz, q })`. Typical: 80 Hz removes rumble from a voice.
+ pub fn highpass(self, hz: f32) -> Self {
+ self.effect(Effect::Highpass {
+ hz,
+ q: std::f32::consts::FRAC_1_SQRT_2,
+ })
+ }
+
+ /// Removes the sound above `hz`: 12 dB per octave, Butterworth (-3 dB at `hz`). Call it
+ /// twice for 24 dB per octave. For another Q, use `effect(Effect::Lowpass { hz, q })`.
+ pub fn lowpass(self, hz: f32) -> Self {
+ self.effect(Effect::Lowpass {
+ hz,
+ q: std::f32::consts::FRAC_1_SQRT_2,
+ })
+ }
+
+ /// Changes the level below `hz` by `db` decibels. At `hz` the change is half of `db`.
+ pub fn low_shelf(self, hz: f32, db: f32) -> Self {
+ self.effect(Effect::LowShelf { hz, db })
+ }
+
+ /// Changes the level above `hz` by `db` decibels. At `hz` the change is half of `db`.
+ pub fn high_shelf(self, hz: f32, db: f32) -> Self {
+ self.effect(Effect::HighShelf { hz, db })
+ }
+
+ /// Bell filter: changes the level at `hz` by `db` decibels. A larger `q` makes the band
+ /// narrower (bandwidth `hz / q`): `0.7` is wide, `4.0` is narrow.
+ pub fn peak(self, hz: f32, db: f32, q: f32) -> Self {
+ self.effect(Effect::Peak { hz, db, q })
+ }
+
+ /// Makes loud parts quieter, see `Compressor`. Put it before `normalize_lufs` to
+ /// normalize the compressed sound.
+ pub fn compress(self, compressor: Compressor) -> Self {
+ self.effect(Effect::Compress(compressor))
+ }
+
+ /// Stereo width through mid/side: `0.0` is mono, `1.0` is unchanged, `2.0` doubles the
+ /// side. The mono sum (left + right) does not change. A mono file becomes stereo: the
+ /// side is the sound delayed by 12 ms, without the bass below 250 Hz, at `0.3 * width`.
+ pub fn width(self, width: f32) -> Self {
+ self.effect(Effect::Width {
+ width: width.max(0.),
+ })
+ }
}
impl<'a> From<(&'a str, AudioDuration<'a>)> for AudioTrack<'a> {
@@ -379,7 +474,8 @@ impl<'a> From<(&'a str, AudioDuration<'a>)> for AudioTrack<'a> {
/// ```
///
/// In this case audio 1 will be playing from second 10 to second 20 and audio 2 will be playing from second 5 to the end of file.
-/// Use `AudioTrack` entries instead of tuples for gain, pan, fades, offsets and ducking.
+/// Use `AudioTrack` entries instead of tuples for gain, pan, fades, offsets, ducking, rate and
+/// effects.
pub struct AudioMap<'a>(pub Option<Vec<AudioTrack<'a>>>);
/// A track with its position on the timeline resolved.
@@ -489,15 +585,20 @@ impl<'a> AudioMap<'a> {
tracks
.iter()
.map(|AudioTrack { file, range, mix }| {
- let start =
- range
- .start
- .to_seconds(file, tb.fps, None, &resolve_audio_duration)?;
+ let start = range.start.to_seconds(
+ file,
+ tb.fps,
+ None,
+ 1.,
+ &resolve_audio_duration,
+ )?;
+ let rate = f64::from(mix.rate);
let end = range.end.to_seconds(
file,
tb.fps,
- Some(start - f64::from(mix.offset)),
+ Some(start - f64::from(mix.offset) / rate),
+ rate,
&resolve_audio_duration,
)?;
@@ -505,7 +606,7 @@ impl<'a> AudioMap<'a> {
file: file.to_string(),
range: TUnit::from_seconds(start + offset, tb)
..TUnit::from_seconds(end.max(start) + offset, tb),
- mix: *mix,
+ mix: mix.clone(),
})
})
.collect::<error::Result<Vec<_>>>()
diff --git a/fframes/src/audio_mix.rs b/fframes/src/audio_mix.rs
index 2ea2e567..324333f1 100644
--- a/fframes/src/audio_mix.rs
+++ b/fframes/src/audio_mix.rs
@@ -3,12 +3,15 @@
//!
//! - tracks start and end at their exact sample, also in the middle of an encoder frame,
//! - each track has gain, pan, fades, a file offset and range-driven ducking (`TrackMix`),
-//! - a Kaiser-windowed sinc resamples sources at other sample rates,
+//! - a Kaiser-windowed sinc resamples sources at other sample rates and plays them at their
+//! `rate`,
+//! - a track with effects (`Effect`) is rendered with its effects once, when the mixer is
+//! built, and is then read from that buffer,
//! - the mixer sums overlapping tracks linearly and runs the sum through a lookahead peak
//! limiter, so loud overlaps neither intermodulate nor clip.
use crate::{
- AudioData, AudioTimelineSamples, AudioTimelineUnit, Ducking, MediaProvider, ResolvedAudioMap,
- TrackMix,
+ AudioData, AudioTimelineSamples, AudioTimelineUnit, Ducking, Effect, MediaProvider,
+ ResolvedAudioMap, TrackMix,
};
use std::collections::VecDeque;
use std::ops::Range;
@@ -255,10 +258,26 @@ impl Limiter {
}
}
+/// Value of `channel` at the source position `position`.
+fn read_sample(resampler: Option<&SincResampler>, channel: &[f32], position: f64) -> f32 {
+ match resampler {
+ None => channel
+ .get(position.round() as usize)
+ .copied()
+ .unwrap_or(0.),
+ Some(resampler) => resampler.sample(channel, position),
+ }
+}
+
struct PreparedTrack<'m> {
file: String,
left: &'m [f32],
right: Option<&'m [f32]>,
+ /// The track after its effects, one or two channels from `range.start` at the output
+ /// rate. `None` for a track without effects, which is read from the file.
+ processed: Option<Vec<Vec<f32>>>,
+ /// Gain in dB that `Effect::NormalizeLufs` applied.
+ normalize_db: f32,
/// Output samples.
range: Range<usize>,
/// Position in the file (source samples) at `range.start`.
@@ -279,14 +298,19 @@ struct PreparedTrack<'m> {
}
impl PreparedTrack<'_> {
- fn source_sample(&self, channel: &[f32], position: f64) -> f32 {
- match &self.resampler {
- None => channel
- .get(position.round() as usize)
- .copied()
- .unwrap_or(0.),
- Some(resampler) => resampler.sample(channel, position),
+ /// Left sample and right sample (`None` for mono) at output sample `n`.
+ fn frame(&self, n: usize) -> (f32, Option<f32>) {
+ if let Some(channels) = &self.processed {
+ let i = n - self.range.start;
+ return (channels[0][i], channels.get(1).map(|right| right[i]));
}
+ let position = self.source_start + (n - self.range.start) as f64 * self.ratio;
+ let resampler = self.resampler.as_ref();
+ (
+ read_sample(resampler, self.left, position),
+ self.right
+ .map(|right| read_sample(resampler, right, position)),
+ )
}
fn envelope(&self, n: usize, sample_rate: f64) -> f32 {
@@ -434,17 +458,46 @@ impl<'m> AudioMixer<'m> {
}
let source_rate = f64::from(audio.sample_rate);
- let ratio = source_rate / rate;
+ let speed = f64::from(track.mix.rate);
+ let ratio = source_rate / rate * speed;
let source_start = f64::from(track.mix.offset) * source_rate;
let natural_end =
range.start as f64 + (audio.samples.len() as f64 - source_start) / ratio;
- let resampler = (audio.sample_rate as usize != sample_rate)
- .then(|| SincResampler::new(source_rate, rate));
+ #[expect(
+ clippy::float_cmp,
+ reason = "1.0 means the file is read sample by sample"
+ )]
+ let resampler = (ratio != 1.).then(|| SincResampler::new(source_rate * speed, rate));
+
+ let mut normalize_db = 0.;
+ let processed = (!track.mix.effects.is_empty()).then(|| {
+ let read = |channel: &[f32]| -> Vec<f32> {
+ (0..range.len())
+ .map(|i| {
+ let position = source_start + i as f64 * ratio;
+ read_sample(resampler.as_ref(), channel, position)
+ })
+ .collect()
+ };
+ let mut channels: Vec<Vec<f32>> = std::iter::once(audio.samples.as_ref())
+ .chain(audio.right.as_deref())
+ .map(read)
+ .collect();
+ normalize_db = crate::audio_effects::apply_effects(
+ &track.mix.effects,
+ sample_rate,
+ &mut channels,
+ );
+ channels
+ });
+ let stereo = processed
+ .as_ref()
+ .map_or(audio.is_stereo(), |channels| channels.len() == 2);
let pan = track.mix.pan.clamp(-1., 1.);
let pan = if pan.abs() < 1e-6 {
(1., 1.)
- } else if audio.is_stereo() {
+ } else if stereo {
// Balance: attenuate the opposite side.
let attenuation = (pan.abs() * std::f32::consts::FRAC_PI_2).cos();
if pan > 0. {
@@ -480,12 +533,14 @@ impl<'m> AudioMixer<'m> {
file: track.file.clone(),
left: audio.samples.as_ref(),
right: audio.right.as_deref(),
+ processed,
+ normalize_db,
source_start,
ratio,
resampler,
gain: db_to_gain(track.mix.gain_db),
pan,
- mix: track.mix,
+ mix: track.mix.clone(),
fade_in: f64::from(track.mix.fade_in) * rate,
fade_out: f64::from(track.mix.fade_out) * rate,
declick_in: options.declick && track.mix.offset > 0.,
@@ -532,16 +587,14 @@ impl<'m> AudioMixer<'m> {
}
for n in from..to {
- let position = track.source_start + (n - track.range.start) as f64 * track.ratio;
let gain = track.envelope(n, rate);
if gain == 0. {
continue;
}
let i = n - start;
- let l = track.source_sample(track.left, position);
- if let Some(right_channel) = track.right {
- let r = track.source_sample(right_channel, position);
+ let (l, r) = track.frame(n);
+ if let Some(r) = r {
left[i] += l * gain * track.pan.0;
right[i] += r * gain * track.pan.1;
} else {
@@ -642,13 +695,13 @@ impl<'m> AudioMixer<'m> {
.filter(|t| t.range.contains(&sample))
.map(|t| {
let position = t.source_start + (sample - t.range.start) as f64 * t.ratio;
- let source_rate = t.ratio * rate;
+ let source_rate = t.ratio * rate / f64::from(t.mix.rate);
let gain = t.envelope(sample, rate);
ActiveTrack {
file: t.file.clone(),
file_seconds: position / source_rate,
gain_db: if gain > 0. {
- 20. * gain.log10()
+ 20. * gain.log10() + t.normalize_db
} else {
f32::NEG_INFINITY
},
@@ -657,6 +710,8 @@ impl<'m> AudioMixer<'m> {
.mix
.duck
.map_or(0., |d| duck_db(&t.duck_under, &d, sample as f64, rate)),
+ rate: t.mix.rate,
+ effects: t.mix.effects.clone(),
}
})
.collect()
@@ -669,11 +724,14 @@ pub struct ActiveTrack {
pub file: String,
/// Position inside the file.
pub file_seconds: f64,
- /// Effective level (gain, fades and ducking) in dB.
+ /// Effective level (gain, `normalize_lufs`, fades and ducking) in dB.
pub gain_db: f32,
pub voice: bool,
/// Current ducking attenuation (0 when not ducked).
pub ducked_db: f32,
+ /// Playback rate of the file.
+ pub rate: f32,
+ pub effects: Vec<Effect>,
}
fn merge_ranges(mut ranges: Vec<Range<f64>>, gap: f64) -> Vec<Range<f64>> {
@@ -943,4 +1001,169 @@ mod tests {
assert_eq!(left.len(), RATE / 2);
assert!((left[0] - 0.5).abs() < 1e-4);
}
+
+ /// FNV-1a over the bits of both channels.
+ fn fingerprint(left: &[f32], right: &[f32]) -> u64 {
+ left.iter()
+ .chain(right)
+ .fold(0xcbf2_9ce4_8422_2325, |hash, s| {
+ (hash ^ u64::from(s.to_bits())).wrapping_mul(0x0100_0000_01b3)
+ })
+ }
+
+ // libm `sin`, `exp` and `powf` can differ in the last bit on other platforms.
+ #[test]
+ #[cfg_attr(
+ not(all(target_os = "linux", target_arch = "x86_64")),
+ ignore = "the fingerprint is from x86_64 Linux"
+ )]
+ fn tracks_without_effects_mix_bit_identical_to_before_effects() {
+ // The fingerprint is from the mixer before effects existed. The mix has resampling,
+ // a stereo file, an offset, pan, fades, ducking, the limiter and a range render.
+ let tone = |frequency: f64, rate: u32, seconds: f64| -> Vec<f32> {
+ (0..(seconds * f64::from(rate)) as usize)
+ .map(|i| {
+ (0.8 * (std::f64::consts::TAU * frequency * i as f64 / f64::from(rate)).sin())
+ as f32
+ })
+ .collect()
+ };
+ let stereo = AudioData::Preloaded(crate::media::PreloadedAudioData {
+ samples: Cow::Owned(tone(220., 48000, 3.)),
+ sample_rate: 48000,
+ right: Some(Cow::Owned(tone(330., 48000, 3.))),
+ });
+ let media = Media(HashMap::from([
+ ("music".into(), stereo),
+ (
+ "voice".into(),
+ audio(tone(440., RATE as u32, 1.5), RATE as u32),
+ ),
+ ("hit".into(), audio(tone(90., 22050, 0.5), 22050)),
+ ]));
+ let map = resolve(
+ AudioMap::from([
+ AudioTrack::new("music", Second(0.)..Eof)
+ .offset(0.3)
+ .gain_db(-3.)
+ .fade_out(0.7)
+ .duck_under_voice(),
+ AudioTrack::new("voice", Second(0.6)..Eof).voice().pan(-0.3),
+ AudioTrack::new("hit", Second(1.234)..Second(1.6))
+ .fade_in(0.05)
+ .fade_curve(crate::FadeCurve::Exponential),
+ ]),
+ &media,
+ );
+ let mut mixer = AudioMixer::new(
+ Some(&map),
+ Some(&media),
+ RATE,
+ RATE / 3..3 * RATE,
+ 3 * RATE,
+ AudioMixOptions::default(),
+ );
+ let (left, right) = mixer.render_all();
+ assert_eq!(fingerprint(&left, &right), 9_847_675_520_623_648_258);
+ }
+
+ fn sine(frequency: f64, amplitude: f32, rate: usize, seconds: f64) -> Vec<f32> {
+ (0..(seconds * rate as f64) as usize)
+ .map(|i| {
+ amplitude
+ * (std::f64::consts::TAU * frequency * i as f64 / rate as f64).sin() as f32
+ })
+ .collect()
+ }
+
+ #[test]
+ fn normalize_lufs_reaches_the_target_after_the_effects_before_it() {
+ let low = sine(60., 0.3, RATE, 4.);
+ let mixed: Vec<f32> = sine(1000., 0.02, RATE, 4.)
+ .iter()
+ .zip(&low)
+ .map(|(a, b)| a + b)
+ .collect();
+ let media = Media(HashMap::from([("take".into(), audio(mixed, RATE as u32))]));
+ let measure = |track: AudioTrack| {
+ let map = resolve(AudioMap::from([track]), &media);
+ let mut mixer = AudioMixer::new(
+ Some(&map),
+ Some(&media),
+ RATE,
+ 0..4 * RATE,
+ 4 * RATE,
+ no_master(),
+ );
+ let (left, right) = mixer.render_all();
+ crate::LoudnessAnalysis::new(&left, &right, RATE).integrated(0..left.len())
+ };
+
+ let take = || AudioTrack::new("take", Second(0.)..Eof);
+ let lufs = measure(take().highpass(200.).normalize_lufs(-16.));
+ assert!((lufs + 16.).abs() < 0.3, "{lufs}");
+ let lufs = measure(take().normalize_lufs(-23.).gain_db(-2.));
+ assert!((lufs + 25.).abs() < 0.3, "{lufs}");
+ }
+
+ #[test]
+ fn rate_changes_pitch_and_length_together() {
+ let media = Media(HashMap::from([(
+ "tone".into(),
+ audio(sine(1000., 0.5, 48000, 0.5), 48000),
+ )]));
+ let map = resolve(
+ AudioMap::from([AudioTrack::new("tone", Second(0.)..Eof).rate(0.5)]),
+ &media,
+ );
+ assert_eq!(map.tracks()[0].range.end.as_usize(), RATE);
+
+ let mut mixer = AudioMixer::new(
+ Some(&map),
+ Some(&media),
+ RATE,
+ 0..2 * RATE,
+ 2 * RATE,
+ no_master(),
+ );
+ let (left, _) = mixer.render_all();
+ let audible = left.iter().rposition(|s| s.abs() > 1e-3).unwrap_or(0);
+ assert!(audible.abs_diff(RATE) < RATE / 100, "{audible}");
+ // 500 Hz: 1000 sign changes in the second that plays.
+ let crossings = left[..RATE]
+ .windows(2)
+ .filter(|w| (w[0] < 0.) != (w[1] < 0.))
+ .count();
+ assert!(crossings.abs_diff(1000) <= 2, "{crossings}");
+ }
+
+ #[test]
+ fn effects_render_the_same_in_a_range_render() {
+ let media = Media(HashMap::from([(
+ "tone".into(),
+ audio(sine(300., 0.8, 48000, 2.), 48000),
+ )]));
+ let map = resolve(
+ AudioMap::from([AudioTrack::new("tone", Second(0.1)..Eof)
+ .rate(1.5)
+ .compress(crate::Compressor::default())
+ .width(1.)
+ .pan(0.4)]),
+ &media,
+ );
+ let mut full = AudioMixer::new(Some(&map), Some(&media), RATE, 0..RATE, RATE, no_master());
+ let (left, right) = full.render_all();
+ assert_ne!(left, right, "width makes the mono file stereo");
+ let mut part = AudioMixer::new(
+ Some(&map),
+ Some(&media),
+ RATE,
+ RATE / 2..RATE,
+ RATE,
+ no_master(),
+ );
+ let (part_left, part_right) = part.render_all();
+ assert_eq!(part_left, left[RATE / 2..]);
+ assert_eq!(part_right, right[RATE / 2..]);
+ }
}
diff --git a/fframes/src/lib.rs b/fframes/src/lib.rs
index 1ce960a8..ae18cdef 100644
--- a/fframes/src/lib.rs
+++ b/fframes/src/lib.rs
@@ -102,6 +102,7 @@
//!
mod audio_analysis;
mod audio_data;
+mod audio_effects;
mod audio_map;
mod audio_mix;
mod audio_window_functions;
@@ -137,6 +138,7 @@ mod video_data;
pub use audio_analysis::*;
pub use audio_data::*;
+pub use audio_effects::*;
pub use audio_map::*;
pub use audio_mix::*;
pub use audio_window_functions::*;
diff --git a/fframes/src/renderer/cli.rs b/fframes/src/renderer/cli.rs
index ef0c1a17..a0f7cdd7 100644
--- a/fframes/src/renderer/cli.rs
+++ b/fframes/src/renderer/cli.rs
@@ -968,6 +968,10 @@ fn timeline<'a, 'm: 'a, V: Video>(json: bool, previewer: &Previewer<'a, 'm, V>)
if mix.duck.is_some() {
extra.push("ducked".into());
}
+ let processing = track_processing(mix.rate, &mix.effects);
+ if let Some(processing) = processing.strip_prefix(", ") {
+ extra.push(processing.to_owned());
+ }
let _ = writeln!(
text,
"audio {:<28} {:>8.3}s..{:.3}s {}",
@@ -1159,6 +1163,28 @@ fn snapshots<'a, 'm: 'a, V: Video>(
})
}
+/// One time of `audio at`.
+#[derive(Serialize)]
+struct AudioAt {
+ spec: String,
+ frame: usize,
+ seconds: f64,
+ tracks: Vec<crate::ActiveTrack>,
+}
+
+/// `, rate 0.50, highpass 80 Hz Q 0.71, ...` for a track that has them.
+fn track_processing(rate: f32, effects: &[crate::Effect]) -> String {
+ let mut text = String::new();
+ #[expect(clippy::float_cmp, reason = "1.0 is the exact default")]
+ if rate != 1. {
+ let _ = write!(text, ", rate {rate:.2}");
+ }
+ for effect in effects {
+ let _ = write!(text, ", {effect}");
+ }
+ text
+}
+
fn mixer_for<'a, 'm: 'a, V: Video>(
previewer: &Previewer<'a, 'm, V>,
range: std::ops::Range<usize>,
@@ -1302,43 +1328,34 @@ fn audio<'a, 'm: 'a, V: Video>(
let mut results = Vec::new();
for (spec, frame) in resolve_frames(previewer, &at)? {
let sample = (frame as f64 / V::FPS as f64 * sample_rate as f64).round() as usize;
- results.push(serde_json::json!({
- "spec": spec,
- "frame": frame,
- "seconds": frame as f64 / V::FPS as f64,
- "tracks": mixer.active_tracks_at(sample),
- }));
+ results.push(AudioAt {
+ spec,
+ frame,
+ seconds: frame as f64 / V::FPS as f64,
+ tracks: mixer.active_tracks_at(sample),
+ });
}
print(json, &results, || {
results
.iter()
.map(|r| {
- let mut text = format!(
- "{} ({:.3}s):",
- r["spec"].as_str().unwrap_or(""),
- r["seconds"].as_f64().unwrap_or(0.)
- );
- let tracks = r["tracks"].as_array().cloned().unwrap_or_default();
- if tracks.is_empty() {
+ let mut text = format!("{} ({:.3}s):", r.spec, r.seconds);
+ if r.tracks.is_empty() {
text.push_str(" silence");
}
- for t in tracks {
+ for t in &r.tracks {
let _ = write!(
text,
- "\n {} at {:.3}s of the file, {:.1} dB{}{}",
- t["file"].as_str().unwrap_or(""),
- t["file_seconds"].as_f64().unwrap_or(0.),
- t["gain_db"].as_f64().unwrap_or(f64::NEG_INFINITY),
- if t["voice"].as_bool() == Some(true) {
- ", voice"
- } else {
- ""
- },
- match t["ducked_db"].as_f64() {
- Some(d) if d < -0.05 => format!(", ducked {d:.1} dB"),
- _ => String::new(),
- }
+ "\n {} at {:.3}s of the file, {:.1} dB",
+ t.file, t.file_seconds, t.gain_db
);
+ if t.voice {
+ text.push_str(", voice");
+ }
+ if t.ducked_db < -0.05 {
+ let _ = write!(text, ", ducked {:.1} dB", t.ducked_db);
+ }
+ text.push_str(&track_processing(t.rate, &t.effects));
}
text
})
diff --git a/fframes/src/renderer/preview.rs b/fframes/src/renderer/preview.rs
index 5415fa2e..01004734 100644
--- a/fframes/src/renderer/preview.rs
+++ b/fframes/src/renderer/preview.rs
@@ -374,7 +374,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
file: track.file.clone(),
start_seconds: track.range.start.to_seconds(&time_base),
end_seconds: track.range.end.to_seconds(&time_base),
- mix: track.mix,
+ mix: track.mix.clone(),
})
.collect()
})