ff-filter 0.14.3

Video and audio filter graph operations - the Rust way
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! Audio filter methods for [`FilterGraphBuilder`].

#[allow(clippy::wildcard_imports)]
use super::*;

impl FilterGraphBuilder {
    // ── Audio filters ─────────────────────────────────────────────────────────

    /// Audio fade-in from silence, starting at `start_sec` seconds and reaching
    /// full volume after `duration_sec` seconds.
    ///
    /// [`build`](Self::build) returns [`FilterError::InvalidConfig`] if
    /// `duration_sec` is ≤ 0.0.
    #[must_use]
    pub fn afade_in(mut self, start_sec: f64, duration_sec: f64) -> Self {
        self.steps.push(FilterStep::AFadeIn {
            start: start_sec,
            duration: duration_sec,
        });
        self
    }

    /// Audio fade-out to silence, starting at `start_sec` seconds and reaching
    /// full silence after `duration_sec` seconds.
    ///
    /// [`build`](Self::build) returns [`FilterError::InvalidConfig`] if
    /// `duration_sec` is ≤ 0.0.
    #[must_use]
    pub fn afade_out(mut self, start_sec: f64, duration_sec: f64) -> Self {
        self.steps.push(FilterStep::AFadeOut {
            start: start_sec,
            duration: duration_sec,
        });
        self
    }

    /// Reverse audio playback using `FFmpeg`'s `areverse` filter.
    ///
    /// **Warning**: `areverse` buffers the entire clip in memory before producing
    /// any output. Only use this on short clips to avoid excessive memory usage.
    #[must_use]
    pub fn areverse(mut self) -> Self {
        self.steps.push(FilterStep::AReverse);
        self
    }

    /// Apply EBU R128 two-pass loudness normalization.
    ///
    /// `target_lufs` is the target integrated loudness (e.g. `−23.0`),
    /// `true_peak_db` is the true-peak ceiling (e.g. `−1.0`), and
    /// `lra` is the target loudness range in LU (e.g. `7.0`).
    ///
    /// Pass 1 measures integrated loudness with the `ebur128` filter.
    /// Pass 2 applies a linear `volume` correction.  All audio frames are
    /// buffered in memory between the two passes — use only for clips that
    /// fit comfortably in RAM.
    ///
    /// [`build`](Self::build) returns [`FilterError::InvalidConfig`] if
    /// `target_lufs >= 0.0`, `true_peak_db > 0.0`, or `lra <= 0.0`.
    #[must_use]
    pub fn loudness_normalize(mut self, target_lufs: f32, true_peak_db: f32, lra: f32) -> Self {
        self.steps.push(FilterStep::LoudnessNormalize {
            target_lufs,
            true_peak_db,
            lra,
        });
        self
    }

    /// Normalize the audio peak level to `target_db` dBFS using a two-pass approach.
    ///
    /// Pass 1 measures the true peak with `astats=metadata=1`.
    /// Pass 2 applies `volume={gain}dB` so the output peak reaches `target_db`.
    /// All audio frames are buffered in memory between the two passes — use only
    /// for clips that fit comfortably in RAM.
    ///
    /// [`build`](Self::build) returns [`FilterError::InvalidConfig`] if
    /// `target_db > 0.0` (cannot normalize above digital full scale).
    #[must_use]
    pub fn normalize_peak(mut self, target_db: f32) -> Self {
        self.steps.push(FilterStep::NormalizePeak { target_db });
        self
    }

    /// Apply a noise gate to suppress audio below a given threshold.
    ///
    /// Uses `FFmpeg`'s `agate` filter. Audio below `threshold_db` (dBFS) is
    /// attenuated; audio above it passes through unmodified. The threshold is
    /// converted from dBFS to the linear amplitude ratio expected by `agate`.
    ///
    /// [`build`](Self::build) returns [`FilterError::InvalidConfig`] if
    /// `attack_ms` or `release_ms` is ≤ 0.0.
    #[must_use]
    pub fn agate(mut self, threshold_db: f32, attack_ms: f32, release_ms: f32) -> Self {
        self.steps.push(FilterStep::ANoiseGate {
            threshold_db,
            attack_ms,
            release_ms,
        });
        self
    }

    /// Apply a dynamic range compressor to the audio.
    ///
    /// Uses `FFmpeg`'s `acompressor` filter. Audio peaks above `threshold_db`
    /// (dBFS) are reduced by `ratio`:1.  `makeup_db` applies additional gain
    /// after compression to restore perceived loudness.
    ///
    /// [`build`](Self::build) returns [`FilterError::InvalidConfig`] if
    /// `ratio < 1.0`, `attack_ms ≤ 0.0`, or `release_ms ≤ 0.0`.
    #[must_use]
    pub fn compressor(
        mut self,
        threshold_db: f32,
        ratio: f32,
        attack_ms: f32,
        release_ms: f32,
        makeup_db: f32,
    ) -> Self {
        self.steps.push(FilterStep::ACompressor {
            threshold_db,
            ratio,
            attack_ms,
            release_ms,
            makeup_db,
        });
        self
    }

    /// Downmix stereo audio to mono by equally mixing both channels.
    ///
    /// Uses `FFmpeg`'s `pan` filter with the expression
    /// `mono|c0=0.5*c0+0.5*c1`.  The output has a single channel.
    #[must_use]
    pub fn stereo_to_mono(mut self) -> Self {
        self.steps.push(FilterStep::StereoToMono);
        self
    }

    /// Remap audio channels using `FFmpeg`'s `channelmap` filter.
    ///
    /// `mapping` is a `|`-separated list of output channel names taken from
    /// input channels, e.g. `"FR|FL"` swaps left and right.
    ///
    /// [`build`](Self::build) returns [`FilterError::InvalidConfig`] if
    /// `mapping` is empty.
    #[must_use]
    pub fn channel_map(mut self, mapping: &str) -> Self {
        self.steps.push(FilterStep::ChannelMap {
            mapping: mapping.to_string(),
        });
        self
    }

    /// Shift audio for A/V sync correction.
    ///
    /// Positive `ms`: uses `FFmpeg`'s `adelay` filter to delay the audio
    /// (audio plays later). Negative `ms`: uses `FFmpeg`'s `atrim` filter to
    /// advance the audio by trimming the start (audio plays earlier).
    /// Zero `ms` is a no-op.
    #[must_use]
    pub fn audio_delay(mut self, ms: f64) -> Self {
        self.steps.push(FilterStep::AudioDelay { ms });
        self
    }

    /// Concatenate `n_segments` sequential audio inputs using `FFmpeg`'s `concat` filter.
    ///
    /// Requires `n_segments` audio input slots (push to slots 0 through
    /// `n_segments - 1` in order). [`build`](Self::build) returns
    /// [`FilterError::InvalidConfig`] if `n_segments < 2`.
    #[must_use]
    pub fn concat_audio(mut self, n_segments: u32) -> Self {
        self.steps.push(FilterStep::ConcatAudio { n: n_segments });
        self
    }

    /// Adjust audio volume by `gain_db` decibels (negative = quieter).
    #[must_use]
    pub fn volume(mut self, gain_db: f64) -> Self {
        self.steps.push(FilterStep::Volume(gain_db));
        self
    }

    /// Mix `inputs` audio streams together.
    #[must_use]
    pub fn amix(mut self, inputs: usize) -> Self {
        self.steps.push(FilterStep::Amix(inputs));
        self
    }

    /// Apply a multi-band parametric equalizer.
    ///
    /// Each [`EqBand`] maps to one `FFmpeg` filter node chained in sequence:
    /// - [`EqBand::LowShelf`] → `lowshelf`
    /// - [`EqBand::HighShelf`] → `highshelf`
    /// - [`EqBand::Peak`] → `equalizer`
    ///
    /// [`build`](Self::build) returns [`FilterError::InvalidConfig`] if `bands`
    /// is empty.
    #[must_use]
    pub fn equalizer(mut self, bands: Vec<EqBand>) -> Self {
        self.steps.push(FilterStep::ParametricEq { bands });
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn filter_step_volume_should_produce_correct_args() {
        let step = FilterStep::Volume(-6.0);
        assert_eq!(step.filter_name(), "volume");
        assert_eq!(step.args(), "volume=-6dB");
    }

    #[test]
    fn volume_should_convert_db_to_ffmpeg_string() {
        assert_eq!(FilterStep::Volume(-6.0).args(), "volume=-6dB");
        assert_eq!(FilterStep::Volume(6.0).args(), "volume=6dB");
        assert_eq!(FilterStep::Volume(0.0).args(), "volume=0dB");
    }

    #[test]
    fn filter_step_amix_should_produce_correct_args() {
        let step = FilterStep::Amix(3);
        assert_eq!(step.filter_name(), "amix");
        assert_eq!(step.args(), "inputs=3");
    }

    #[test]
    fn filter_step_parametric_eq_should_have_filter_name_equalizer() {
        let step = FilterStep::ParametricEq {
            bands: vec![EqBand::Peak {
                freq_hz: 1000.0,
                gain_db: 3.0,
                q: 1.0,
            }],
        };
        assert_eq!(step.filter_name(), "equalizer");
    }

    #[test]
    fn eq_band_peak_should_produce_correct_args() {
        let band = EqBand::Peak {
            freq_hz: 1000.0,
            gain_db: 3.0,
            q: 1.0,
        };
        assert_eq!(band.args(), "f=1000:g=3:width_type=q:width=1");
    }

    #[test]
    fn eq_band_low_shelf_should_produce_correct_args() {
        let band = EqBand::LowShelf {
            freq_hz: 200.0,
            gain_db: -3.0,
            slope: 1.0,
        };
        assert_eq!(band.args(), "f=200:g=-3:s=1");
    }

    #[test]
    fn eq_band_high_shelf_should_produce_correct_args() {
        let band = EqBand::HighShelf {
            freq_hz: 8000.0,
            gain_db: 2.0,
            slope: 0.5,
        };
        assert_eq!(band.args(), "f=8000:g=2:s=0.5");
    }

    #[test]
    fn builder_equalizer_with_single_peak_band_should_succeed() {
        let result = FilterGraph::builder()
            .equalizer(vec![EqBand::Peak {
                freq_hz: 1000.0,
                gain_db: 3.0,
                q: 1.0,
            }])
            .build();
        assert!(
            result.is_ok(),
            "equalizer with single Peak band must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_equalizer_with_multiple_bands_should_succeed() {
        let result = FilterGraph::builder()
            .equalizer(vec![
                EqBand::LowShelf {
                    freq_hz: 200.0,
                    gain_db: -2.0,
                    slope: 1.0,
                },
                EqBand::Peak {
                    freq_hz: 1000.0,
                    gain_db: 3.0,
                    q: 1.4,
                },
                EqBand::HighShelf {
                    freq_hz: 8000.0,
                    gain_db: 1.0,
                    slope: 0.5,
                },
            ])
            .build();
        assert!(
            result.is_ok(),
            "equalizer with three bands must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_equalizer_with_empty_bands_should_return_invalid_config() {
        let result = FilterGraph::builder().equalizer(vec![]).build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for empty bands, got {result:?}"
        );
    }

    #[test]
    fn filter_step_afade_in_should_have_correct_filter_name() {
        let step = FilterStep::AFadeIn {
            start: 0.0,
            duration: 1.0,
        };
        assert_eq!(step.filter_name(), "afade");
    }

    #[test]
    fn filter_step_afade_out_should_have_correct_filter_name() {
        let step = FilterStep::AFadeOut {
            start: 4.0,
            duration: 1.0,
        };
        assert_eq!(step.filter_name(), "afade");
    }

    #[test]
    fn filter_step_afade_in_should_produce_correct_args() {
        let step = FilterStep::AFadeIn {
            start: 0.0,
            duration: 1.0,
        };
        assert_eq!(step.args(), "type=in:start_time=0:duration=1");
    }

    #[test]
    fn filter_step_afade_out_should_produce_correct_args() {
        let step = FilterStep::AFadeOut {
            start: 4.0,
            duration: 1.0,
        };
        assert_eq!(step.args(), "type=out:start_time=4:duration=1");
    }

    #[test]
    fn builder_afade_in_with_valid_params_should_succeed() {
        let result = FilterGraph::builder().afade_in(0.0, 1.0).build();
        assert!(
            result.is_ok(),
            "afade_in(0.0, 1.0) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_afade_out_with_valid_params_should_succeed() {
        let result = FilterGraph::builder().afade_out(4.0, 1.0).build();
        assert!(
            result.is_ok(),
            "afade_out(4.0, 1.0) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_afade_in_with_zero_duration_should_return_invalid_config() {
        let result = FilterGraph::builder().afade_in(0.0, 0.0).build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for duration=0.0, got {result:?}"
        );
    }

    #[test]
    fn builder_afade_out_with_negative_duration_should_return_invalid_config() {
        let result = FilterGraph::builder().afade_out(4.0, -1.0).build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for duration=-1.0, got {result:?}"
        );
    }

    #[test]
    fn filter_step_areverse_should_produce_correct_filter_name_and_empty_args() {
        let step = FilterStep::AReverse;
        assert_eq!(step.filter_name(), "areverse");
        assert_eq!(step.args(), "");
    }

    #[test]
    fn builder_areverse_should_succeed() {
        let result = FilterGraph::builder().areverse().build();
        assert!(
            result.is_ok(),
            "areverse must build successfully, got {result:?}"
        );
    }

    #[test]
    fn filter_step_loudness_normalize_should_produce_correct_filter_name() {
        let step = FilterStep::LoudnessNormalize {
            target_lufs: -23.0,
            true_peak_db: -1.0,
            lra: 7.0,
        };
        assert_eq!(step.filter_name(), "ebur128");
    }

    #[test]
    fn filter_step_loudness_normalize_should_produce_correct_args() {
        let step = FilterStep::LoudnessNormalize {
            target_lufs: -23.0,
            true_peak_db: -1.0,
            lra: 7.0,
        };
        assert_eq!(step.args(), "peak=true:metadata=1");
    }

    #[test]
    fn builder_loudness_normalize_with_valid_params_should_succeed() {
        let result = FilterGraph::builder()
            .loudness_normalize(-23.0, -1.0, 7.0)
            .build();
        assert!(
            result.is_ok(),
            "loudness_normalize(-23.0, -1.0, 7.0) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_loudness_normalize_with_zero_target_lufs_should_return_invalid_config() {
        let result = FilterGraph::builder()
            .loudness_normalize(0.0, -1.0, 7.0)
            .build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for target_lufs=0.0, got {result:?}"
        );
    }

    #[test]
    fn builder_loudness_normalize_with_positive_target_lufs_should_return_invalid_config() {
        let result = FilterGraph::builder()
            .loudness_normalize(5.0, -1.0, 7.0)
            .build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for target_lufs=5.0, got {result:?}"
        );
    }

    #[test]
    fn builder_loudness_normalize_with_positive_true_peak_should_return_invalid_config() {
        let result = FilterGraph::builder()
            .loudness_normalize(-23.0, 1.0, 7.0)
            .build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for true_peak_db=1.0, got {result:?}"
        );
    }

    #[test]
    fn builder_loudness_normalize_with_zero_lra_should_return_invalid_config() {
        let result = FilterGraph::builder()
            .loudness_normalize(-23.0, -1.0, 0.0)
            .build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for lra=0.0, got {result:?}"
        );
    }

    #[test]
    fn builder_loudness_normalize_with_negative_lra_should_return_invalid_config() {
        let result = FilterGraph::builder()
            .loudness_normalize(-23.0, -1.0, -7.0)
            .build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for lra=-7.0, got {result:?}"
        );
    }

    #[test]
    fn filter_step_normalize_peak_should_have_correct_filter_name() {
        let step = FilterStep::NormalizePeak { target_db: -1.0 };
        assert_eq!(step.filter_name(), "astats");
    }

    #[test]
    fn filter_step_normalize_peak_should_have_correct_args() {
        let step = FilterStep::NormalizePeak { target_db: -1.0 };
        assert_eq!(step.args(), "metadata=1");
    }

    #[test]
    fn builder_normalize_peak_valid_should_build_successfully() {
        let result = FilterGraph::builder().normalize_peak(-1.0).build();
        assert!(
            result.is_ok(),
            "normalize_peak(-1.0) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_normalize_peak_with_zero_target_db_should_build_successfully() {
        // 0.0 dBFS is the maximum allowed value (digital full scale).
        let result = FilterGraph::builder().normalize_peak(0.0).build();
        assert!(
            result.is_ok(),
            "normalize_peak(0.0) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_normalize_peak_with_positive_target_db_should_return_invalid_config() {
        let result = FilterGraph::builder().normalize_peak(1.0).build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for target_db=1.0, got {result:?}"
        );
    }

    #[test]
    fn filter_step_agate_should_have_correct_filter_name() {
        let step = FilterStep::ANoiseGate {
            threshold_db: -40.0,
            attack_ms: 10.0,
            release_ms: 100.0,
        };
        assert_eq!(step.filter_name(), "agate");
    }

    #[test]
    fn filter_step_agate_should_produce_correct_args_for_minus_40_db() {
        let step = FilterStep::ANoiseGate {
            threshold_db: -40.0,
            attack_ms: 10.0,
            release_ms: 100.0,
        };
        // 10^(-40/20) = 10^(-2) = 0.01
        let args = step.args();
        assert!(
            args.starts_with("threshold=0.010000:"),
            "expected args to start with threshold=0.010000:, got {args}"
        );
        assert!(
            args.contains("attack=10:"),
            "expected attack=10: in args, got {args}"
        );
        assert!(
            args.contains("release=100"),
            "expected release=100 in args, got {args}"
        );
    }

    #[test]
    fn filter_step_agate_should_produce_correct_args_for_zero_db() {
        let step = FilterStep::ANoiseGate {
            threshold_db: 0.0,
            attack_ms: 5.0,
            release_ms: 50.0,
        };
        // 10^(0/20) = 1.0
        let args = step.args();
        assert!(
            args.starts_with("threshold=1.000000:"),
            "expected threshold=1.000000: in args, got {args}"
        );
    }

    #[test]
    fn builder_agate_valid_should_build_successfully() {
        let result = FilterGraph::builder().agate(-40.0, 10.0, 100.0).build();
        assert!(
            result.is_ok(),
            "agate(-40.0, 10.0, 100.0) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_agate_with_zero_attack_should_return_invalid_config() {
        let result = FilterGraph::builder().agate(-40.0, 0.0, 100.0).build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for attack_ms=0.0, got {result:?}"
        );
    }

    #[test]
    fn builder_agate_with_negative_attack_should_return_invalid_config() {
        let result = FilterGraph::builder().agate(-40.0, -1.0, 100.0).build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for attack_ms=-1.0, got {result:?}"
        );
    }

    #[test]
    fn builder_agate_with_zero_release_should_return_invalid_config() {
        let result = FilterGraph::builder().agate(-40.0, 10.0, 0.0).build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for release_ms=0.0, got {result:?}"
        );
    }

    #[test]
    fn builder_agate_with_negative_release_should_return_invalid_config() {
        let result = FilterGraph::builder().agate(-40.0, 10.0, -50.0).build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for release_ms=-50.0, got {result:?}"
        );
    }

    #[test]
    fn filter_step_compressor_should_have_correct_filter_name() {
        let step = FilterStep::ACompressor {
            threshold_db: -20.0,
            ratio: 4.0,
            attack_ms: 10.0,
            release_ms: 100.0,
            makeup_db: 6.0,
        };
        assert_eq!(step.filter_name(), "acompressor");
    }

    #[test]
    fn filter_step_compressor_should_produce_correct_args() {
        let step = FilterStep::ACompressor {
            threshold_db: -20.0,
            ratio: 4.0,
            attack_ms: 10.0,
            release_ms: 100.0,
            makeup_db: 6.0,
        };
        assert_eq!(
            step.args(),
            "threshold=-20dB:ratio=4:attack=10:release=100:makeup=6dB"
        );
    }

    #[test]
    fn builder_compressor_valid_should_build_successfully() {
        let result = FilterGraph::builder()
            .compressor(-20.0, 4.0, 10.0, 100.0, 6.0)
            .build();
        assert!(
            result.is_ok(),
            "compressor(-20.0, 4.0, 10.0, 100.0, 6.0) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_compressor_with_unity_ratio_should_build_successfully() {
        // ratio=1.0 is the minimum valid value (no compression)
        let result = FilterGraph::builder()
            .compressor(-20.0, 1.0, 10.0, 100.0, 0.0)
            .build();
        assert!(
            result.is_ok(),
            "compressor with ratio=1.0 must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_compressor_with_ratio_below_one_should_return_invalid_config() {
        let result = FilterGraph::builder()
            .compressor(-20.0, 0.5, 10.0, 100.0, 0.0)
            .build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for ratio=0.5, got {result:?}"
        );
    }

    #[test]
    fn builder_compressor_with_zero_attack_should_return_invalid_config() {
        let result = FilterGraph::builder()
            .compressor(-20.0, 4.0, 0.0, 100.0, 0.0)
            .build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for attack_ms=0.0, got {result:?}"
        );
    }

    #[test]
    fn builder_compressor_with_zero_release_should_return_invalid_config() {
        let result = FilterGraph::builder()
            .compressor(-20.0, 4.0, 10.0, 0.0, 0.0)
            .build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for release_ms=0.0, got {result:?}"
        );
    }

    #[test]
    fn filter_step_stereo_to_mono_should_have_correct_filter_name() {
        assert_eq!(FilterStep::StereoToMono.filter_name(), "pan");
    }

    #[test]
    fn filter_step_stereo_to_mono_should_produce_correct_args() {
        assert_eq!(FilterStep::StereoToMono.args(), "mono|c0=0.5*c0+0.5*c1");
    }

    #[test]
    fn builder_stereo_to_mono_should_build_successfully() {
        let result = FilterGraph::builder().stereo_to_mono().build();
        assert!(
            result.is_ok(),
            "stereo_to_mono() must build successfully, got {result:?}"
        );
    }

    #[test]
    fn filter_step_channel_map_should_have_correct_filter_name() {
        let step = FilterStep::ChannelMap {
            mapping: "FR|FL".to_string(),
        };
        assert_eq!(step.filter_name(), "channelmap");
    }

    #[test]
    fn filter_step_channel_map_should_produce_correct_args() {
        let step = FilterStep::ChannelMap {
            mapping: "FR|FL".to_string(),
        };
        assert_eq!(step.args(), "map=FR|FL");
    }

    #[test]
    fn builder_channel_map_valid_should_build_successfully() {
        let result = FilterGraph::builder().channel_map("FR|FL").build();
        assert!(
            result.is_ok(),
            "channel_map(\"FR|FL\") must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_channel_map_with_empty_mapping_should_return_invalid_config() {
        let result = FilterGraph::builder().channel_map("").build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for empty mapping, got {result:?}"
        );
    }

    #[test]
    fn filter_step_audio_delay_positive_should_have_correct_filter_name() {
        let step = FilterStep::AudioDelay { ms: 100.0 };
        assert_eq!(step.filter_name(), "adelay");
    }

    #[test]
    fn filter_step_audio_delay_negative_should_have_correct_filter_name() {
        // filter_name() always returns "adelay" (used for validation only);
        // the build loop dispatches to "atrim" at runtime.
        let step = FilterStep::AudioDelay { ms: -100.0 };
        assert_eq!(step.filter_name(), "adelay");
    }

    #[test]
    fn filter_step_audio_delay_positive_should_produce_adelay_args() {
        let step = FilterStep::AudioDelay { ms: 100.0 };
        assert_eq!(step.args(), "delays=100:all=1");
    }

    #[test]
    fn filter_step_audio_delay_zero_should_produce_adelay_args() {
        let step = FilterStep::AudioDelay { ms: 0.0 };
        assert_eq!(step.args(), "delays=0:all=1");
    }

    #[test]
    fn filter_step_audio_delay_negative_should_produce_atrim_args() {
        let step = FilterStep::AudioDelay { ms: -100.0 };
        // -(-100) / 1000 = 0.1 seconds
        assert_eq!(step.args(), "start=0.1");
    }

    #[test]
    fn builder_audio_delay_positive_should_build_successfully() {
        let result = FilterGraph::builder().audio_delay(100.0).build();
        assert!(
            result.is_ok(),
            "audio_delay(100.0) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_audio_delay_zero_should_build_successfully() {
        let result = FilterGraph::builder().audio_delay(0.0).build();
        assert!(
            result.is_ok(),
            "audio_delay(0.0) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_audio_delay_negative_should_build_successfully() {
        let result = FilterGraph::builder().audio_delay(-100.0).build();
        assert!(
            result.is_ok(),
            "audio_delay(-100.0) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn filter_step_concat_audio_should_have_correct_filter_name() {
        let step = FilterStep::ConcatAudio { n: 2 };
        assert_eq!(step.filter_name(), "concat");
    }

    #[test]
    fn filter_step_concat_audio_should_produce_correct_args_for_n2() {
        let step = FilterStep::ConcatAudio { n: 2 };
        assert_eq!(step.args(), "n=2:v=0:a=1");
    }

    #[test]
    fn filter_step_concat_audio_should_produce_correct_args_for_n3() {
        let step = FilterStep::ConcatAudio { n: 3 };
        assert_eq!(step.args(), "n=3:v=0:a=1");
    }

    #[test]
    fn builder_concat_audio_valid_should_build_successfully() {
        let result = FilterGraph::builder().concat_audio(2).build();
        assert!(
            result.is_ok(),
            "concat_audio(2) must build successfully, got {result:?}"
        );
    }

    #[test]
    fn builder_concat_audio_with_n1_should_return_invalid_config() {
        let result = FilterGraph::builder().concat_audio(1).build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for n=1, got {result:?}"
        );
    }

    #[test]
    fn builder_concat_audio_with_n0_should_return_invalid_config() {
        let result = FilterGraph::builder().concat_audio(0).build();
        assert!(
            matches!(result, Err(FilterError::InvalidConfig { .. })),
            "expected InvalidConfig for n=0, got {result:?}"
        );
    }
}