deepshrink-core 0.3.1

DeepShrink core: pure, testable logic (size parsing, presets, engine contract).
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
//! Media engine v0.1: video + audio via ffmpeg (external process).
//!
//! - `probe` shells out to ffprobe and maps the result into [`MediaInfo`].
//! - `plan` is pure bitrate budgeting → an [`EncodePlan`] (tested without ffmpeg).
//!   `plan` dispatches on media kind: two-pass video vs single-pass audio.
//! - `run` executes the plan: encode, size verification and (for video) a single
//!   correction retry on overshoot.

use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};

use super::{
    AudioSpec, EncodePlan, EncodeSpec, Engine, EngineError, MediaInfo, Outcome, ShrinkOpts,
    SizeGoal, VideoSpec,
};
use crate::budget;
use crate::detect::{detect_kind, MediaKind};
use crate::options::{AudioChoice, AudioCodec, FpsOpt, ResolutionOpt};

/// Audio bitrate ladder (bits/s, descending) tried when keeping a track under
/// a tight size budget.
const AUDIO_LADDER: &[u64] = &[128_000, 96_000, 64_000, 48_000];

/// Which pass of the encode a progress update belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PassKind {
    Single,
    First,
    Second,
}

/// The ffmpeg engine for video and audio.
#[derive(Debug, Default, Clone, Copy)]
pub struct MediaEngine;

impl MediaEngine {
    pub fn new() -> Self {
        Self
    }

    /// Like [`Engine::run`] but reports progress: `on_progress(pass, fraction)`
    /// is called with `fraction` in 0.0..=1.0 as each pass proceeds.
    pub fn run_with_progress(
        &self,
        plan: &EncodePlan,
        on_progress: &mut dyn FnMut(PassKind, f64),
    ) -> Result<Outcome, EngineError> {
        let tools = deepshrink_ffmpeg::locate()?;

        // VMAF-targeted quality search: applies to CRF-mode video only. Size /
        // audio / passthrough encodes keep their existing single path.
        if let Some(target_vmaf) = plan.target_vmaf {
            if plan.spec.video.crf.is_some() && !plan.spec.audio_only && !plan.spec.passthrough {
                return self.run_crf_search(&tools, plan, target_vmaf, on_progress);
            }
        }

        let mut outcome = self.run_plain(&tools, plan, on_progress)?;

        // Size-targeted video with `--vmaf`: encode to budget, then report the
        // VMAF actually achieved (best effort — a failed measurement is silent).
        if plan.target_vmaf.is_some() && !plan.spec.audio_only && !plan.spec.passthrough {
            outcome.vmaf = self.measure_output(&tools, plan, &plan.output);
        }
        Ok(outcome)
    }

    /// The plain encode: two-pass (with one correction retry) or single-pass,
    /// no VMAF handling. Returns an [`Outcome`] with `vmaf = None`.
    fn run_plain(
        &self,
        tools: &deepshrink_ffmpeg::Tools,
        plan: &EncodePlan,
        on_progress: &mut dyn FnMut(PassKind, f64),
    ) -> Result<Outcome, EngineError> {
        let passlog = passlog_base(plan);
        let total = plan.source_duration_sec;

        if plan.spec.two_pass {
            let args1 = build_pass_args(plan, PassKind::First, &passlog);
            deepshrink_ffmpeg::run_pass(&tools.ffmpeg, &args1, total, &mut |f| {
                on_progress(PassKind::First, f)
            })?;
            let args2 = build_pass_args(plan, PassKind::Second, &passlog);
            deepshrink_ffmpeg::run_pass(&tools.ffmpeg, &args2, total, &mut |f| {
                on_progress(PassKind::Second, f)
            })?;
        } else {
            let args = build_pass_args(plan, PassKind::Single, &passlog);
            deepshrink_ffmpeg::run_pass(&tools.ffmpeg, &args, total, &mut |f| {
                on_progress(PassKind::Single, f)
            })?;
        }

        let mut size = fs::metadata(&plan.output)?.len();

        // Single correction retry: if two-pass overshot the target (VBV slack),
        // scale the video bitrate down proportionally and re-run pass 2.
        if let (Some(target), Some(vbps)) = (plan.target_bytes, plan.spec.video.bitrate_bps) {
            if size > target && plan.spec.two_pass {
                let corrected = (vbps as f64 * (target as f64 / size as f64) * 0.97) as u64;
                if corrected >= budget::ABSOLUTE_MIN_VIDEO_BPS {
                    let mut retry = plan.clone();
                    retry.spec.video.bitrate_bps = Some(corrected);
                    let args = build_pass_args(&retry, PassKind::Second, &passlog);
                    deepshrink_ffmpeg::run_pass(&tools.ffmpeg, &args, total, &mut |f| {
                        on_progress(PassKind::Second, f)
                    })?;
                    size = fs::metadata(&plan.output)?.len();
                }
            }
        }

        cleanup_passlog(&passlog);
        Ok(Outcome {
            output: plan.output.clone(),
            final_bytes: size,
            vmaf: None,
        })
    }

    /// Search CRF for the smallest output that still meets `target_vmaf`.
    ///
    /// Each trial is a single-pass CRF encode into `plan.output` followed by a
    /// VMAF measurement against the source. Drives [`budget::search_crf`], so
    /// the search algorithm itself is unit-tested separately. Falls back to a
    /// plain encode if the source resolution is unknown (nothing to measure).
    fn run_crf_search(
        &self,
        tools: &deepshrink_ffmpeg::Tools,
        plan: &EncodePlan,
        target_vmaf: f64,
        on_progress: &mut dyn FnMut(PassKind, f64),
    ) -> Result<Outcome, EngineError> {
        let (ref_w, ref_h) = match (plan.source_width, plan.source_height) {
            (Some(w), Some(h)) => (w, h),
            _ => return self.run_plain(tools, plan, on_progress),
        };
        let ref_fps = plan.source_fps.unwrap_or(0.0);
        let total = plan.source_duration_sec;
        let (lo, hi) = plan.spec.video.codec.crf_search_bounds();
        let n_threads = thread_count();

        let mut err: Option<EngineError> = None;
        let mut last_crf: Option<u8> = None;

        let (chosen_crf, chosen_vmaf) = budget::search_crf(target_vmaf, lo, hi, |crf| {
            if err.is_some() {
                return f64::NEG_INFINITY;
            }
            match encode_at_crf(tools, plan, crf, total, on_progress).and_then(|()| {
                last_crf = Some(crf);
                deepshrink_ffmpeg::measure_vmaf(
                    &tools.ffmpeg,
                    &plan.output,
                    &plan.input,
                    ref_w,
                    ref_h,
                    ref_fps,
                    n_threads,
                )
                .map_err(EngineError::from)
            }) {
                Ok(v) => v,
                Err(e) => {
                    err = Some(e);
                    f64::NEG_INFINITY
                }
            }
        });
        if let Some(e) = err {
            return Err(e);
        }

        // Leave the chosen CRF on disk (the search may have ended elsewhere).
        if last_crf != Some(chosen_crf) {
            encode_at_crf(tools, plan, chosen_crf, total, on_progress)?;
        }
        let size = fs::metadata(&plan.output)?.len();
        Ok(Outcome {
            output: plan.output.clone(),
            final_bytes: size,
            vmaf: Some(chosen_vmaf),
        })
    }

    /// Measure the VMAF of an encoded `output` against the plan's source.
    /// Returns `None` on any failure or when the source dimensions are unknown.
    fn measure_output(
        &self,
        tools: &deepshrink_ffmpeg::Tools,
        plan: &EncodePlan,
        output: &Path,
    ) -> Option<f64> {
        let (w, h) = (plan.source_width?, plan.source_height?);
        let fps = plan.source_fps.unwrap_or(0.0);
        deepshrink_ffmpeg::measure_vmaf(
            &tools.ffmpeg,
            output,
            &plan.input,
            w,
            h,
            fps,
            thread_count(),
        )
        .ok()
    }

    /// Plan a pure-audio encode (single pass, codec + fitted bitrate).
    fn plan_audio(&self, info: &MediaInfo, opts: &ShrinkOpts) -> Result<EncodePlan, EngineError> {
        let duration = info.duration_sec;
        if !duration.is_finite() || duration <= 0.0 {
            return Err(EngineError::Unsupported(format!(
                "could not determine duration of {}",
                info.path.display()
            )));
        }
        let codec = opts.audio_codec;
        let target = target_bytes(&opts.goal, info.size_bytes);

        // "Never make it bigger": stream-copy remux when the source already fits.
        if let Some(tb) = target {
            if info.size_bytes > 0 && info.size_bytes <= tb {
                let src_ext = info
                    .path
                    .extension()
                    .and_then(|e| e.to_str())
                    .unwrap_or("audio");
                let output = opts
                    .output
                    .clone()
                    .unwrap_or_else(|| output_with_ext(&info.path, src_ext));
                return Ok(passthrough_plan(info, output, tb, false));
            }
        }

        // Mono for speech: explicit flag, or a single-channel source.
        let mono = opts.mono || info.audio_channels == Some(1);

        let (bitrate_bps, expected_bytes) = match target {
            Some(tb) => {
                let raw = budget::audio_bitrate_bps(tb, duration).ok_or(EngineError::Infeasible)?;
                if raw < budget::ABSOLUTE_MIN_AUDIO_BPS {
                    return Err(EngineError::Infeasible);
                }
                let bps = budget::snap_audio_bitrate(raw);
                let predicted = (bps as f64 * duration / 8.0 * (1.0 + budget::CONTAINER_OVERHEAD))
                    .round() as u64;
                (bps, Some(predicted))
            }
            None => {
                // Quality mode: a transparent-ish default, lower for speech.
                let bps = if mono { 96_000 } else { 160_000 };
                (bps, None)
            }
        };

        let audio = AudioSpec {
            codec,
            bitrate_bps,
            mono,
            sample_rate: opts.sample_rate,
            vbr: opts.vbr,
        };
        let output = opts
            .output
            .clone()
            .unwrap_or_else(|| output_with_ext(&info.path, codec.extension()));
        let summary = build_audio_summary(&audio, info.audio_channels);

        Ok(EncodePlan {
            input: info.path.clone(),
            output,
            summary,
            expected_bytes,
            target_bytes: target,
            target_vmaf: None,
            source_duration_sec: duration,
            source_width: info.width,
            source_height: info.height,
            source_fps: info.fps,
            spec: EncodeSpec {
                video: placeholder_video_spec(),
                audio: Some(audio),
                faststart: false,
                two_pass: false,
                passthrough: false,
                audio_only: true,
            },
        })
    }
}

impl Engine for MediaEngine {
    fn supports(&self, input: &Path) -> bool {
        matches!(detect_kind(input), MediaKind::Video | MediaKind::Audio)
    }

    fn probe(&self, input: &Path) -> Result<MediaInfo, EngineError> {
        let tools = deepshrink_ffmpeg::locate()?;
        let p = deepshrink_ffmpeg::probe(&tools.ffprobe, input)?;

        let video = p.video_stream();
        let audio = p.audio_stream();
        // Prefer ffprobe's reported size; fall back to the filesystem.
        let size_bytes = p
            .size_bytes()
            .or_else(|| fs::metadata(input).ok().map(|m| m.len()))
            .unwrap_or(0);

        Ok(MediaInfo {
            path: input.to_path_buf(),
            kind: detect_kind(input),
            duration_sec: p.duration_sec().unwrap_or(0.0),
            size_bytes,
            width: video.and_then(|v| v.width),
            height: video.and_then(|v| v.height),
            fps: p.fps(),
            video_codec: video.and_then(|v| v.codec_name.clone()),
            audio_codec: audio.and_then(|a| a.codec_name.clone()),
            audio_channels: audio.and_then(|a| a.channels),
        })
    }

    fn plan(&self, info: &MediaInfo, opts: &ShrinkOpts) -> Result<EncodePlan, EngineError> {
        match info.kind {
            MediaKind::Audio => return self.plan_audio(info, opts),
            MediaKind::Unsupported => {
                return Err(EngineError::Unsupported(format!(
                    "{} is not a supported media file",
                    info.path.display()
                )))
            }
            MediaKind::Video => {}
        }
        let duration = info.duration_sec;
        if !duration.is_finite() || duration <= 0.0 {
            return Err(EngineError::Unsupported(format!(
                "could not determine duration of {}",
                info.path.display()
            )));
        }
        let src_height = info.height.unwrap_or(0);

        let target = target_bytes(&opts.goal, info.size_bytes);
        let output = opts
            .output
            .clone()
            .unwrap_or_else(|| output_with_ext(&info.path, "mp4"));

        // "Never make it bigger": if the source already fits the target, just
        // remux (stream copy) instead of re-encoding it up to the target.
        if let Some(tb) = target {
            if info.size_bytes > 0 && info.size_bytes <= tb {
                return Ok(passthrough_plan(info, output, tb, true));
            }
        }

        let audio = decide_audio(opts, info.has_audio(), target, duration)?;
        let audio_bps = audio.as_ref().map(|a| a.bitrate_bps).unwrap_or(0);

        let (video, expected_bytes) = if let Some(tb) = target {
            let vbps = budget::video_bitrate_bps(tb, duration, audio_bps)
                .filter(|&b| b >= budget::ABSOLUTE_MIN_VIDEO_BPS)
                .ok_or(EngineError::Infeasible)?;
            let height = pick_height(opts.resolution, src_height, vbps);
            let predicted = ((vbps + audio_bps) as f64 * duration / 8.0
                * (1.0 + budget::CONTAINER_OVERHEAD))
                .round() as u64;
            (
                VideoSpec {
                    codec: opts.video_codec,
                    bitrate_bps: Some(vbps),
                    crf: None,
                    height,
                    fps: pick_fps(opts.fps, info.fps),
                    preset: opts.quality,
                },
                Some(predicted),
            )
        } else {
            // Quality mode: CRF, no hard size guarantee. The CRF default is
            // codec-aware; a `--vmaf` target refines it via a search in `run`.
            let crf = opts.quality.default_crf(opts.video_codec);
            let height = match opts.resolution {
                ResolutionOpt::Height(h) => clamp_height(h, src_height),
                ResolutionOpt::Auto => None,
            };
            (
                VideoSpec {
                    codec: opts.video_codec,
                    bitrate_bps: None,
                    crf: Some(crf),
                    height,
                    fps: pick_fps(opts.fps, info.fps),
                    preset: opts.quality,
                },
                None,
            )
        };

        let two_pass = video.bitrate_bps.is_some();
        let summary = build_summary(&video, audio.as_ref(), two_pass);

        Ok(EncodePlan {
            input: info.path.clone(),
            output,
            summary,
            expected_bytes,
            target_bytes: target,
            target_vmaf: opts.target_vmaf,
            source_duration_sec: duration,
            source_width: info.width,
            source_height: info.height,
            source_fps: info.fps,
            spec: EncodeSpec {
                video,
                audio,
                faststart: true,
                two_pass,
                passthrough: false,
                audio_only: false,
            },
        })
    }

    fn run(&self, plan: &EncodePlan) -> Result<Outcome, EngineError> {
        self.run_with_progress(plan, &mut |_, _| {})
    }
}

/// A placeholder video spec — ignored while `passthrough`/`audio_only` is set.
fn placeholder_video_spec() -> VideoSpec {
    VideoSpec {
        codec: crate::options::VideoCodec::H264,
        bitrate_bps: None,
        crf: None,
        height: None,
        fps: None,
        preset: crate::options::QualityPreset::Balanced,
    }
}

/// A stream-copy remux plan for when the source already fits the target.
/// `faststart` is only meaningful for MP4/MOV; pass `false` for pure audio.
fn passthrough_plan(info: &MediaInfo, output: PathBuf, target: u64, faststart: bool) -> EncodePlan {
    EncodePlan {
        input: info.path.clone(),
        output,
        summary: "stream copy (already within target)".to_string(),
        expected_bytes: Some(info.size_bytes),
        target_bytes: Some(target),
        target_vmaf: None,
        source_duration_sec: info.duration_sec,
        source_width: info.width,
        source_height: info.height,
        source_fps: info.fps,
        spec: EncodeSpec {
            video: placeholder_video_spec(),
            audio: None,
            faststart,
            two_pass: false,
            passthrough: true,
            audio_only: false,
        },
    }
}

/// Human-readable summary for a pure-audio plan, e.g.
/// "Opus · 22 kbps · mono (speech)".
fn build_audio_summary(audio: &AudioSpec, src_channels: Option<u32>) -> String {
    let mut parts = vec![
        audio.codec.label().to_string(),
        format!("{} kbps", audio.bitrate_bps / 1000),
    ];
    if audio.mono {
        // A single-channel source (or --mono) reads as speech.
        let note = if src_channels == Some(1) {
            "mono"
        } else {
            "mono (downmix)"
        };
        parts.push(note.to_string());
    }
    if let Some(sr) = audio.sample_rate {
        parts.push(format!("{} Hz", sr));
    }
    parts.join(" · ")
}

/// Resolve the absolute target size (bytes) for a goal, if it imposes one.
fn target_bytes(goal: &SizeGoal, original: u64) -> Option<u64> {
    match goal {
        SizeGoal::Target(b) => Some(*b),
        SizeGoal::Reduce(f) => Some(budget::reduce_target_bytes(original, *f)),
        SizeGoal::Preset(p) => p.limit_bytes,
        SizeGoal::Quality => None,
    }
}

/// Decide the audio track for a video encode.
fn decide_audio(
    opts: &ShrinkOpts,
    has_audio: bool,
    target: Option<u64>,
    duration: f64,
) -> Result<Option<AudioSpec>, EngineError> {
    if !has_audio {
        return Ok(None);
    }
    match opts.audio {
        AudioChoice::Drop => Ok(None),
        AudioChoice::Bitrate(b) => Ok(Some(AudioSpec::cbr(AudioCodec::Aac, b))),
        AudioChoice::Keep => {
            let bps = match target {
                Some(tb) => budget::fit_audio_bps(tb, duration, AUDIO_LADDER)
                    .ok_or(EngineError::Infeasible)?,
                None => budget::DEFAULT_AUDIO_BPS,
            };
            Ok(Some(AudioSpec::cbr(AudioCodec::Aac, bps)))
        }
    }
}

/// Choose the encode height in auto/explicit mode.
fn pick_height(res: ResolutionOpt, src_height: u32, vbps: u64) -> Option<u32> {
    match res {
        ResolutionOpt::Height(h) => clamp_height(h, src_height),
        ResolutionOpt::Auto => {
            let chosen = budget::choose_height(src_height, vbps);
            if src_height > 0 && chosen < src_height {
                Some(chosen)
            } else {
                None
            }
        }
    }
}

/// Clamp an explicit height to the source (never upscale); `None` if it equals
/// the source (no scaling needed).
fn clamp_height(requested: u32, src_height: u32) -> Option<u32> {
    if src_height == 0 {
        return Some(requested);
    }
    let h = requested.min(src_height);
    if h == src_height {
        None
    } else {
        Some(h)
    }
}

/// Choose an fps cap; `None` if uncapped or the cap is ≥ the source rate.
fn pick_fps(fps: FpsOpt, src_fps: Option<f64>) -> Option<u32> {
    match fps {
        FpsOpt::Auto => None,
        FpsOpt::Cap(f) => match src_fps {
            Some(src) if (f as f64) >= src => None,
            _ => Some(f),
        },
    }
}

/// Default output path: `<stem>.shrink.<ext>` next to the input.
fn output_with_ext(input: &Path, ext: &str) -> PathBuf {
    let stem = input
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "output".to_string());
    let mut out = input.parent().map(Path::to_path_buf).unwrap_or_default();
    out.push(format!("{stem}.shrink.{ext}"));
    out
}

fn build_summary(video: &VideoSpec, audio: Option<&AudioSpec>, two_pass: bool) -> String {
    let mut parts = vec![video.codec.label().to_string()];
    match (video.bitrate_bps, video.crf) {
        (Some(bps), _) => parts.push(format!("{} kbps video", bps / 1000)),
        (_, Some(crf)) => parts.push(format!("CRF {crf}")),
        _ => {}
    }
    if let Some(a) = audio {
        parts.push(format!("{} kbps audio", a.bitrate_bps / 1000));
    } else {
        parts.push("no audio".to_string());
    }
    if let Some(h) = video.height {
        parts.push(format!("{h}p"));
    }
    if let Some(f) = video.fps {
        parts.push(format!("{f} fps"));
    }
    parts.push(if two_pass { "two-pass" } else { "CRF" }.to_string());
    parts.join(" · ")
}

/// Base path for ffmpeg's two-pass log, unique per process + input stem.
fn passlog_base(plan: &EncodePlan) -> String {
    let stem = plan
        .input
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "ds".to_string());
    let dir = std::env::temp_dir();
    dir.join(format!("deepshrink-{}-{}", std::process::id(), stem))
        .to_string_lossy()
        .into_owned()
}

/// Remove the files ffmpeg leaves behind for `-passlogfile <base>`.
fn cleanup_passlog(base: &str) {
    for suffix in ["-0.log", "-0.log.mbtree"] {
        let _ = fs::remove_file(format!("{base}{suffix}"));
    }
}

/// Encode a single-pass CRF trial into `plan.output` at the given CRF.
fn encode_at_crf(
    tools: &deepshrink_ffmpeg::Tools,
    plan: &EncodePlan,
    crf: u8,
    total: f64,
    on_progress: &mut dyn FnMut(PassKind, f64),
) -> Result<(), EngineError> {
    let mut trial = plan.clone();
    trial.spec.video.crf = Some(crf);
    trial.spec.video.bitrate_bps = None;
    trial.spec.two_pass = false;
    let args = build_pass_args(&trial, PassKind::Single, "");
    deepshrink_ffmpeg::run_pass(&tools.ffmpeg, &args, total, &mut |f| {
        on_progress(PassKind::Single, f)
    })?;
    Ok(())
}

/// Threads to hand libvmaf (bounded by available parallelism).
fn thread_count() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
}

/// Platform null sink for the discard output of pass 1.
fn null_sink() -> &'static str {
    if cfg!(windows) {
        "NUL"
    } else {
        "/dev/null"
    }
}

/// Build the ffmpeg argv for one pass. Video-processing options (codec, filters,
/// bitrate) are shared across passes; audio/output differ per pass.
fn build_pass_args(plan: &EncodePlan, pass: PassKind, passlog: &str) -> Vec<OsString> {
    let s = &plan.spec;
    let mut a: Vec<OsString> = Vec::new();
    // Local helper — a macro (not a closure) so it doesn't hold a borrow of `a`
    // across the direct `a.push(..)` calls used for OsString paths.
    macro_rules! push {
        ($arg:expr) => {
            a.push(OsString::from($arg))
        };
    }

    push!("-hide_banner");
    push!("-y");
    push!("-loglevel");
    push!("error");
    push!("-progress");
    push!("pipe:1");
    push!("-nostats");
    push!("-i");
    a.push(plan.input.clone().into_os_string());

    // Passthrough: stream copy, no re-encode. Output only (single pass).
    if s.passthrough {
        push!("-c");
        push!("copy");
        if s.faststart {
            push!("-movflags");
            push!("+faststart");
        }
        a.push(plan.output.clone().into_os_string());
        return a;
    }

    // Pure audio: drop video, encode the audio track only (single pass).
    if s.audio_only {
        push!("-vn");
        if let Some(au) = &s.audio {
            push!("-c:a");
            push!(au.codec.encoder());
            if au.mono {
                push!("-ac");
                push!("1");
            }
            if let Some(sr) = au.sample_rate {
                push!("-ar");
                push!(sr.to_string());
            }
            push!("-b:a");
            push!(au.bitrate_bps.to_string());
            // Opus supports VBR; use constrained VBR by default for a tighter
            // fit to the target, or full VBR when requested.
            if matches!(au.codec, AudioCodec::Opus) {
                push!("-vbr");
                push!(if au.vbr { "on" } else { "constrained" });
            }
        }
        a.push(plan.output.clone().into_os_string());
        return a;
    }

    // Video codec + filters.
    push!("-c:v");
    push!(s.video.codec.encoder());
    if let Some(h) = s.video.height {
        push!("-vf");
        push!(format!("scale=-2:{h}"));
    }
    if let Some(f) = s.video.fps {
        push!("-r");
        push!(f.to_string());
    }
    push!("-preset");
    push!(s.video.preset.encoder_preset());
    if let Some(tag) = s.video.codec.mp4_tag() {
        push!("-tag:v");
        push!(tag);
    }

    // Rate control.
    match (s.video.bitrate_bps, s.video.crf) {
        (Some(bps), _) => {
            push!("-b:v");
            push!(bps.to_string());
            if s.two_pass {
                push!("-pass");
                push!(match pass {
                    PassKind::First => "1",
                    _ => "2",
                });
                push!("-passlogfile");
                push!(passlog);
            }
        }
        (_, Some(crf)) => {
            push!("-crf");
            push!(crf.to_string());
        }
        _ => {}
    }

    // Audio + output.
    match pass {
        PassKind::First => {
            // Analysis pass: no audio, discard the muxed output.
            push!("-an");
            push!("-f");
            push!("null");
            push!(null_sink());
        }
        PassKind::Second | PassKind::Single => {
            match &s.audio {
                Some(au) => {
                    push!("-c:a");
                    push!(au.codec.encoder());
                    push!("-b:a");
                    push!(au.bitrate_bps.to_string());
                }
                None => push!("-an"),
            }
            if s.faststart {
                push!("-movflags");
                push!("+faststart");
            }
            a.push(plan.output.clone().into_os_string());
        }
    }
    a
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::options::{AudioCodec, QualityPreset, VideoCodec};
    use crate::size::preset;

    fn video_info(duration: f64, size: u64, w: u32, h: u32, audio: bool) -> MediaInfo {
        MediaInfo {
            path: PathBuf::from("/tmp/clip.mp4"),
            kind: MediaKind::Video,
            duration_sec: duration,
            size_bytes: size,
            width: Some(w),
            height: Some(h),
            fps: Some(30.0),
            video_codec: Some("h264".into()),
            audio_codec: if audio { Some("aac".into()) } else { None },
            audio_channels: if audio { Some(2) } else { None },
        }
    }

    fn opts_target(bytes: u64) -> ShrinkOpts {
        ShrinkOpts {
            goal: SizeGoal::Target(bytes),
            ..Default::default()
        }
    }

    #[test]
    fn supports_video_and_audio() {
        let e = MediaEngine::new();
        assert!(e.supports(&PathBuf::from("clip.mp4")));
        assert!(e.supports(&PathBuf::from("lecture.wav")));
        assert!(!e.supports(&PathBuf::from("photo.jpg")));
    }

    #[test]
    fn plan_target_builds_two_pass_with_budget() {
        let info = video_info(120.0, 300_000_000, 1920, 1080, true);
        let plan = MediaEngine::new()
            .plan(&info, &opts_target(8_000_000))
            .unwrap();

        assert!(plan.spec.two_pass);
        assert_eq!(plan.target_bytes, Some(8_000_000));
        assert_eq!(plan.output, PathBuf::from("/tmp/clip.shrink.mp4"));
        let vbps = plan.spec.video.bitrate_bps.unwrap();
        assert!(vbps >= budget::ABSOLUTE_MIN_VIDEO_BPS);
        // 8 MB over 120 s is a low budget → downscale from 1080p.
        assert!(plan.spec.video.height.is_some());
        assert!(plan.spec.audio.is_some());
        // Predicted size should not exceed the target.
        assert!(plan.expected_bytes.unwrap() <= 8_000_000 + 8_000_000 / 20);
    }

    #[test]
    fn plan_preset_discord_sets_target() {
        let info = video_info(30.0, 50_000_000, 1280, 720, true);
        let opts = ShrinkOpts {
            goal: SizeGoal::Preset(preset("discord").unwrap()),
            ..Default::default()
        };
        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
        assert_eq!(plan.target_bytes, Some(8_000_000));
    }

    #[test]
    fn plan_reduce_targets_complement_of_original() {
        let info = video_info(60.0, 100_000_000, 1920, 1080, true);
        let opts = ShrinkOpts {
            goal: SizeGoal::Reduce(0.70),
            ..Default::default()
        };
        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
        assert_eq!(plan.target_bytes, Some(30_000_000));
    }

    #[test]
    fn plan_passthrough_when_source_already_fits() {
        // Source is 200 KB, target 1 MB → never inflate; stream-copy remux.
        let info = video_info(10.0, 200_000, 1280, 720, true);
        let plan = MediaEngine::new()
            .plan(&info, &opts_target(1_000_000))
            .unwrap();
        assert!(plan.spec.passthrough);
        assert!(!plan.spec.two_pass);
        assert_eq!(plan.expected_bytes, Some(200_000));
        let args = build_pass_args(&plan, PassKind::Single, "/tmp/passlog");
        let joined: Vec<String> = args
            .iter()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(joined.contains(&"copy".to_string()));
    }

    #[test]
    fn plan_infeasible_when_target_too_small() {
        let info = video_info(600.0, 500_000_000, 1920, 1080, true);
        let err = MediaEngine::new().plan(&info, &opts_target(50_000));
        assert!(matches!(err, Err(EngineError::Infeasible)));
    }

    #[test]
    fn plan_quality_mode_uses_crf_single_pass() {
        let info = video_info(60.0, 100_000_000, 1920, 1080, true);
        let opts = ShrinkOpts {
            goal: SizeGoal::Quality,
            quality: QualityPreset::Balanced,
            ..Default::default()
        };
        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
        assert!(!plan.spec.two_pass);
        assert_eq!(plan.spec.video.crf, Some(23));
        assert!(plan.spec.video.bitrate_bps.is_none());
        assert!(plan.expected_bytes.is_none());
    }

    #[test]
    fn plan_drops_audio_when_requested() {
        let info = video_info(30.0, 50_000_000, 1280, 720, true);
        let opts = ShrinkOpts {
            audio: AudioChoice::Drop,
            ..opts_target(8_000_000)
        };
        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
        assert!(plan.spec.audio.is_none());
    }

    fn audio_info(duration: f64, size: u64, channels: u32) -> MediaInfo {
        MediaInfo {
            path: PathBuf::from("/tmp/lecture.wav"),
            kind: MediaKind::Audio,
            duration_sec: duration,
            size_bytes: size,
            width: None,
            height: None,
            fps: None,
            video_codec: None,
            audio_codec: Some("pcm_s16le".into()),
            audio_channels: Some(channels),
        }
    }

    #[test]
    fn plan_audio_single_pass_with_fitted_bitrate() {
        // 58 min stereo lecture, target 10 MB.
        let info = audio_info(3480.0, 600_000_000, 2);
        let plan = MediaEngine::new()
            .plan(&info, &opts_target(10_000_000))
            .unwrap();
        assert!(plan.spec.audio_only);
        assert!(!plan.spec.two_pass);
        assert_eq!(plan.output, PathBuf::from("/tmp/lecture.shrink.m4a"));
        let au = plan.spec.audio.as_ref().unwrap();
        // Snapped down to a standard step, never above the raw budget.
        assert!(budget::AUDIO_STEPS.contains(&au.bitrate_bps));
        assert!(plan.expected_bytes.unwrap() <= 10_000_000 + 10_000_000 / 20);
    }

    #[test]
    fn plan_audio_mono_source_marked_speech() {
        let info = audio_info(600.0, 100_000_000, 1);
        let plan = MediaEngine::new()
            .plan(&info, &opts_target(5_000_000))
            .unwrap();
        assert!(plan.spec.audio.as_ref().unwrap().mono);
    }

    #[test]
    fn plan_audio_opus_extension_and_vbr_args() {
        let info = audio_info(600.0, 100_000_000, 2);
        let opts = ShrinkOpts {
            audio_codec: AudioCodec::Opus,
            mono: true,
            ..opts_target(3_000_000)
        };
        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
        assert_eq!(plan.output, PathBuf::from("/tmp/lecture.shrink.opus"));
        let args = build_pass_args(&plan, PassKind::Single, "/tmp/passlog");
        let j: Vec<String> = args
            .iter()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(j.contains(&"-vn".to_string()));
        assert!(j.contains(&"libopus".to_string()));
        assert!(j.contains(&"-ac".to_string())); // mono downmix
        assert!(j.contains(&"-vbr".to_string()));
    }

    #[test]
    fn plan_audio_infeasible_when_target_tiny() {
        let info = audio_info(3600.0, 500_000_000, 2);
        assert!(matches!(
            MediaEngine::new().plan(&info, &opts_target(1_000)),
            Err(EngineError::Infeasible)
        ));
    }

    #[test]
    fn plan_audio_passthrough_when_source_fits() {
        let info = audio_info(600.0, 2_000_000, 2);
        let plan = MediaEngine::new()
            .plan(&info, &opts_target(10_000_000))
            .unwrap();
        assert!(plan.spec.passthrough);
        // Passthrough keeps the source container/extension.
        assert_eq!(plan.output, PathBuf::from("/tmp/lecture.shrink.wav"));
    }

    #[test]
    fn pass1_args_have_no_audio_and_null_sink() {
        let info = video_info(120.0, 300_000_000, 1920, 1080, true);
        let plan = MediaEngine::new()
            .plan(&info, &opts_target(8_000_000))
            .unwrap();
        let args = build_pass_args(&plan, PassKind::First, "/tmp/passlog");
        let joined: Vec<String> = args
            .iter()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(joined.contains(&"-an".to_string()));
        assert!(joined.contains(&"null".to_string()));
        assert!(joined.iter().any(|a| a == "1")); // -pass 1
        assert!(!joined.iter().any(|a| a.contains("shrink.mp4")));
    }

    #[test]
    fn pass2_args_write_output_with_audio() {
        let info = video_info(120.0, 300_000_000, 1920, 1080, true);
        let plan = MediaEngine::new()
            .plan(&info, &opts_target(8_000_000))
            .unwrap();
        let args = build_pass_args(&plan, PassKind::Second, "/tmp/passlog");
        let joined: Vec<String> = args
            .iter()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(joined.iter().any(|a| a.contains("clip.shrink.mp4")));
        assert!(joined.contains(&"-c:a".to_string()));
        assert!(joined.contains(&"+faststart".to_string()));
        assert!(joined.iter().any(|a| a == "2")); // -pass 2
    }

    #[test]
    fn h265_adds_hvc1_tag() {
        let info = video_info(60.0, 100_000_000, 1280, 720, false);
        let opts = ShrinkOpts {
            video_codec: VideoCodec::H265,
            ..opts_target(8_000_000)
        };
        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
        let args = build_pass_args(&plan, PassKind::Second, "/tmp/passlog");
        let joined: Vec<String> = args
            .iter()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(joined.contains(&"hvc1".to_string()));
        assert!(joined.contains(&"libx265".to_string()));
    }
}