1use crate::media_processing::MediaPath;
4use std::path::PathBuf;
5use std::time::Duration;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum AudioProcessingError {
9 UnsafePath,
10 UnsupportedFormat,
11 InvalidGain,
12 InvalidLoudness,
13 InvalidDucking,
14 InvalidDuration,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq)]
18pub struct LoudnessTarget {
19 pub integrated_lufs: f32,
20 pub true_peak_db: f32,
21}
22
23impl LoudnessTarget {
24 pub fn new(integrated_lufs: f32, true_peak_db: f32) -> Result<Self, AudioProcessingError> {
25 if !integrated_lufs.is_finite()
26 || !(-70.0..=0.0).contains(&integrated_lufs)
27 || !true_peak_db.is_finite()
28 || !(-20.0..=0.0).contains(&true_peak_db)
29 {
30 return Err(AudioProcessingError::InvalidLoudness);
31 }
32 Ok(Self {
33 integrated_lufs,
34 true_peak_db,
35 })
36 }
37}
38
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub struct Ducking {
41 pub reduction_db: f32,
42 pub attack: Duration,
43 pub release: Duration,
44}
45
46impl Ducking {
47 pub fn new(
48 reduction_db: f32,
49 attack: Duration,
50 release: Duration,
51 ) -> Result<Self, AudioProcessingError> {
52 if !reduction_db.is_finite()
53 || !(0.0..=24.0).contains(&reduction_db)
54 || attack.is_zero()
55 || release.is_zero()
56 || attack > Duration::from_secs(10)
57 || release > Duration::from_secs(30)
58 {
59 return Err(AudioProcessingError::InvalidDucking);
60 }
61 Ok(Self {
62 reduction_db,
63 attack,
64 release,
65 })
66 }
67}
68
69#[derive(Debug, Clone, PartialEq)]
70pub struct AudioProcessingSpec {
71 pub input: MediaPath,
72 pub output: MediaPath,
73 pub target: LoudnessTarget,
74 pub gain_db: f32,
75 pub ducking: Option<Ducking>,
76 pub max_duration: Option<Duration>,
77}
78
79impl AudioProcessingSpec {
80 pub fn new(
81 input: impl Into<PathBuf>,
82 output: impl Into<PathBuf>,
83 target: LoudnessTarget,
84 ) -> Result<Self, AudioProcessingError> {
85 let input = MediaPath::new(input).map_err(|_| AudioProcessingError::UnsafePath)?;
86 let output = MediaPath::new(output).map_err(|_| AudioProcessingError::UnsafePath)?;
87 if !is_audio(input.as_path().extension().and_then(|v| v.to_str()))
88 || !is_audio(output.as_path().extension().and_then(|v| v.to_str()))
89 {
90 return Err(AudioProcessingError::UnsupportedFormat);
91 }
92 Ok(Self {
93 input,
94 output,
95 target,
96 gain_db: 0.0,
97 ducking: None,
98 max_duration: None,
99 })
100 }
101 pub fn gain(mut self, gain_db: f32) -> Result<Self, AudioProcessingError> {
102 if !gain_db.is_finite() || !(-24.0..=24.0).contains(&gain_db) {
103 return Err(AudioProcessingError::InvalidGain);
104 }
105 self.gain_db = gain_db;
106 Ok(self)
107 }
108 pub fn duck(mut self, ducking: Ducking) -> Self {
109 self.ducking = Some(ducking);
110 self
111 }
112 pub fn max_duration(mut self, duration: Duration) -> Result<Self, AudioProcessingError> {
113 if duration.is_zero() || duration > Duration::from_secs(86_400) {
114 return Err(AudioProcessingError::InvalidDuration);
115 }
116 self.max_duration = Some(duration);
117 Ok(self)
118 }
119 pub fn command_line(&self) -> Vec<String> {
120 let mut filters = vec![format!(
121 "loudnorm=I={:.1}:TP={:.1}:LRA=11",
122 self.target.integrated_lufs, self.target.true_peak_db
123 )];
124 if self.gain_db != 0.0 {
125 filters.push(format!("volume={:.2}dB", self.gain_db));
126 }
127 if let Some(ducking) = self.ducking {
128 filters.push(format!(
129 "sidechaincompress=threshold=0.125:ratio={:.2}:attack={:.3}:release={:.3}",
130 10.0_f32.powf(ducking.reduction_db / 20.0),
131 ducking.attack.as_secs_f64(),
132 ducking.release.as_secs_f64()
133 ));
134 }
135 let mut args = vec![
136 "-hide_banner".into(),
137 "-nostdin".into(),
138 "-y".into(),
139 "-i".into(),
140 self.input.display(),
141 "-af".into(),
142 filters.join(","),
143 "-c:a".into(),
144 "aac".into(),
145 ];
146 if let Some(duration) = self.max_duration {
147 args.extend(["-t".into(), duration.as_secs_f64().to_string()]);
148 }
149 args.push(self.output.display());
150 args
151 }
152}
153
154fn is_audio(extension: Option<&str>) -> bool {
155 matches!(extension, Some("mp3" | "wav" | "m4a" | "aac" | "ogg"))
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161 #[test]
162 fn builds_normalization_and_ducking_filters() {
163 let target = LoudnessTarget::new(-16.0, -1.5).unwrap();
164 let ducking =
165 Ducking::new(12.0, Duration::from_millis(50), Duration::from_millis(300)).unwrap();
166 let spec = AudioProcessingSpec::new("uploads/music.mp3", "renders/music.m4a", target)
167 .unwrap()
168 .gain(3.0)
169 .unwrap()
170 .duck(ducking);
171 let args = spec.command_line();
172 assert!(args
173 .iter()
174 .any(|arg| arg.contains("loudnorm=I=-16.0:TP=-1.5")));
175 assert!(args.iter().any(|arg| arg.contains("sidechaincompress")));
176 assert!(args.iter().any(|arg| arg.contains("volume=3.00dB")));
177 }
178 #[test]
179 fn rejects_unsafe_formats_and_bounds() {
180 assert_eq!(
181 LoudnessTarget::new(-90.0, -1.0),
182 Err(AudioProcessingError::InvalidLoudness)
183 );
184 assert_eq!(
185 Ducking::new(25.0, Duration::from_secs(1), Duration::from_secs(1)),
186 Err(AudioProcessingError::InvalidDucking)
187 );
188 assert_eq!(
189 AudioProcessingSpec::new(
190 "../music.mp3",
191 "out.m4a",
192 LoudnessTarget::new(-16.0, -1.0).unwrap()
193 ),
194 Err(AudioProcessingError::UnsafePath)
195 );
196 assert_eq!(
197 AudioProcessingSpec::new(
198 "music.exe",
199 "out.m4a",
200 LoudnessTarget::new(-16.0, -1.0).unwrap()
201 ),
202 Err(AudioProcessingError::UnsupportedFormat)
203 );
204 }
205 #[test]
206 fn validates_gain_duration_and_argument_safety() {
207 let target = LoudnessTarget::new(-14.0, -1.0).unwrap();
208 let spec = AudioProcessingSpec::new("in.wav", "out.ogg", target).unwrap();
209 assert_eq!(
210 spec.clone().gain(30.0),
211 Err(AudioProcessingError::InvalidGain)
212 );
213 assert_eq!(
214 spec.clone().max_duration(Duration::ZERO),
215 Err(AudioProcessingError::InvalidDuration)
216 );
217 assert!(!spec.command_line().join(" ").contains(";"));
218 }
219}