Skip to main content

deepshrink_core/engine/
media.rs

1//! Media engine v0.1: video + audio via ffmpeg (external process).
2//!
3//! - `probe` shells out to ffprobe and maps the result into [`MediaInfo`].
4//! - `plan` is pure bitrate budgeting → an [`EncodePlan`] (tested without ffmpeg).
5//!   `plan` dispatches on media kind: two-pass video vs single-pass audio.
6//! - `run` executes the plan: encode, size verification and (for video) a single
7//!   correction retry on overshoot.
8
9use std::ffi::OsString;
10use std::fs;
11use std::path::Path;
12
13use super::plan::*;
14use super::{
15    CaptureMeta, EncodePlan, Engine, EngineError, Hdr, MediaInfo, Outcome, ShrinkOpts, VideoSpec,
16};
17use crate::budget;
18use crate::detect::{detect_kind, MediaKind};
19use crate::options::AudioCodec;
20
21/// Which pass of the encode a progress update belongs to.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum PassKind {
24    Single,
25    First,
26    Second,
27}
28
29/// The ffmpeg engine for video and audio.
30#[derive(Debug, Default, Clone)]
31pub struct MediaEngine {
32    /// Stops this engine's runs (see [`MediaEngine::with_cancel`]).
33    cancel: Option<deepshrink_ffmpeg::CancelToken>,
34}
35
36impl MediaEngine {
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    /// An engine whose `run` / `estimate` stop when `cancel` is set: the running
42    /// ffmpeg is killed, the partial output removed, and the call returns an
43    /// error for which [`EngineError::is_cancelled`] is true.
44    pub fn with_cancel(cancel: deepshrink_ffmpeg::CancelToken) -> Self {
45        Self {
46            cancel: Some(cancel),
47        }
48    }
49
50    /// The located ffmpeg / ffprobe, carrying this engine's cancel token.
51    fn tools(&self) -> Result<deepshrink_ffmpeg::Tools, EngineError> {
52        let tools = deepshrink_ffmpeg::locate()?;
53        Ok(match &self.cancel {
54            Some(c) => tools.with_cancel(c.clone()),
55            None => tools,
56        })
57    }
58
59    /// Like [`Engine::run`] but reports progress: `on_progress(pass, fraction)`
60    /// is called with `fraction` in 0.0..=1.0 as each pass proceeds.
61    pub fn run_with_progress(
62        &self,
63        plan: &EncodePlan,
64        on_progress: &mut dyn FnMut(PassKind, f64),
65    ) -> Result<Outcome, EngineError> {
66        let outcome = match self.run_inner(plan, on_progress) {
67            Ok(o) => o,
68            Err(e) => {
69                // A stopped encode leaves nothing behind: no half-written file,
70                // no two-pass log.
71                if e.is_cancelled() && plan.output != plan.input {
72                    let _ = fs::remove_file(&plan.output);
73                    cleanup_passlog(&passlog_base(plan));
74                }
75                return Err(e);
76            }
77        };
78        // Keep the source's modification time too, so the result sorts next to
79        // the original (Finder, Photos imports) instead of "today".
80        if plan.spec.keep_metadata {
81            copy_mtime(&plan.input, &outcome.output);
82        }
83        Ok(outcome)
84    }
85
86    fn run_inner(
87        &self,
88        plan: &EncodePlan,
89        on_progress: &mut dyn FnMut(PassKind, f64),
90    ) -> Result<Outcome, EngineError> {
91        let tools = self.tools()?;
92        let encoder = resolve_encoder(&tools, plan)?;
93        let zscale = wants_zscale(&tools, plan);
94
95        // VMAF-targeted quality search: applies to CRF-mode video only. Size /
96        // audio / passthrough encodes keep their existing single path.
97        if let Some(target_vmaf) = plan.target_vmaf {
98            if plan.spec.video.crf.is_some() && !plan.spec.audio_only && !plan.spec.passthrough {
99                return self.run_crf_search(
100                    &tools,
101                    plan,
102                    encoder,
103                    zscale,
104                    target_vmaf,
105                    on_progress,
106                );
107            }
108        }
109
110        // "Never make it bigger" in quality mode (sizes are guaranteed by the
111        // target path already): predict a CRF video from samples and skip the
112        // encode when it won't save at least `MIN_SAVING`; after any guarded
113        // encode, keep the original if the result doesn't after all.
114        let source = if plan.guard_larger && !plan.spec.passthrough {
115            fs::metadata(&plan.input).map(|m| m.len()).unwrap_or(0)
116        } else {
117            0
118        };
119        if source > 0
120            && plan.target_vmaf.is_none()
121            && !plan.spec.audio_only
122            && plan.spec.video.crf.is_some()
123        {
124            if let Some(predicted) = predict_crf_bytes(&tools, plan, encoder, zscale) {
125                if super::not_worth_it(predicted, source) {
126                    return self.keep_original(&tools, plan, on_progress);
127                }
128            }
129        }
130
131        // A size target is a ceiling, not a quota: when the quality preset's
132        // CRF comfortably fits, encode at it instead of filling the budget.
133        let ceiling = match ceiling_fit(&tools, plan, encoder, zscale) {
134            Some((ceiling, _)) => {
135                let o = self.run_plain(&tools, &ceiling, encoder, zscale, on_progress)?;
136                // Predictions are ±5%; a miss falls back to the budgeted encode.
137                plan.target_bytes
138                    .is_some_and(|t| o.final_bytes <= t)
139                    .then_some(o)
140            }
141            None => None,
142        };
143        let mut outcome = match ceiling {
144            Some(o) => o,
145            None => self.run_plain(&tools, plan, encoder, zscale, on_progress)?,
146        };
147        if source > 0 && super::not_worth_it(outcome.final_bytes, source) {
148            let _ = fs::remove_file(&outcome.output);
149            return self.keep_original(&tools, plan, on_progress);
150        }
151
152        // Size-targeted video with `--vmaf`: encode to budget, then report the
153        // VMAF actually achieved (best effort — a failed measurement is silent).
154        if plan.target_vmaf.is_some() && !plan.spec.audio_only && !plan.spec.passthrough {
155            outcome.vmaf = self.measure_output(&tools, plan, &plan.output);
156        }
157        Ok(outcome)
158    }
159
160    /// The plain encode: two-pass (with one correction retry) or single-pass,
161    /// no VMAF handling. Returns an [`Outcome`] with `vmaf = None`.
162    fn run_plain(
163        &self,
164        tools: &deepshrink_ffmpeg::Tools,
165        plan: &EncodePlan,
166        encoder: &str,
167        zscale: bool,
168        on_progress: &mut dyn FnMut(PassKind, f64),
169    ) -> Result<Outcome, EngineError> {
170        let passlog = passlog_base(plan);
171        let total = plan.source_duration_sec;
172
173        if plan.spec.passthrough {
174            return self.run_passthrough(tools, plan, on_progress);
175        }
176
177        if plan.spec.two_pass {
178            let args1 = build_pass_args(plan, PassKind::First, &passlog, encoder, zscale);
179            tools.run_pass(&args1, total, &mut |f| on_progress(PassKind::First, f))?;
180            let args2 = build_pass_args(plan, PassKind::Second, &passlog, encoder, zscale);
181            tools.run_pass(&args2, total, &mut |f| on_progress(PassKind::Second, f))?;
182        } else {
183            let args = build_pass_args(plan, PassKind::Single, &passlog, encoder, zscale);
184            tools.run_pass(&args, total, &mut |f| on_progress(PassKind::Single, f))?;
185        }
186
187        let mut size = fs::metadata(&plan.output)?.len();
188
189        // Correction retry: if the encode overshot the target (VBV slack),
190        // scale the video bitrate down proportionally and re-run the final
191        // pass. Two-pass needs one; Apple's one-pass encoder is looser, so it
192        // gets up to three.
193        if let (Some(target), Some(mut vbps)) = (plan.target_bytes, plan.spec.video.bitrate_bps) {
194            let (tries, pass) = if plan.spec.two_pass {
195                (1, PassKind::Second)
196            } else if plan.spec.video.hardware {
197                (3, PassKind::Single)
198            } else {
199                (0, PassKind::Single)
200            };
201            for _ in 0..tries {
202                if size <= target {
203                    break;
204                }
205                let Some(corrected) = corrected_bitrate(vbps, target, size) else {
206                    break;
207                };
208                vbps = corrected;
209                let mut retry = plan.clone();
210                retry.spec.video.bitrate_bps = Some(corrected);
211                let args = build_pass_args(&retry, pass, &passlog, encoder, zscale);
212                tools.run_pass(&args, total, &mut |f| on_progress(pass, f))?;
213                size = fs::metadata(&plan.output)?.len();
214            }
215        }
216
217        cleanup_passlog(&passlog);
218        Ok(Outcome {
219            output: plan.output.clone(),
220            final_bytes: size,
221            vmaf: None,
222            already_compact: false,
223        })
224    }
225
226    /// The expected output size of `plan`, without running it — the honest
227    /// preview for a UI. Size targets and audio come straight from the plan
228    /// (pure); a quality-mode (CRF) video is predicted from short sample
229    /// encodes, like the "never bigger" guard does (~2–3 s for any length).
230    /// Compare the result with the source: at or above it, a guarded run keeps
231    /// the original (`Outcome::already_compact`). `None` if it can't be told.
232    pub fn estimate(&self, plan: &EncodePlan) -> Result<Option<u64>, EngineError> {
233        if plan.spec.passthrough {
234            return Ok(fs::metadata(&plan.input).ok().map(|m| m.len()));
235        }
236        if ceiling_plan(plan).is_some() {
237            // A size target: the budget, or less when the quality CRF fits.
238            let tools = self.tools()?;
239            let encoder = resolve_encoder(&tools, plan)?;
240            let zscale = wants_zscale(&tools, plan);
241            let fit = ceiling_fit(&tools, plan, encoder, zscale).map(|(_, bytes)| bytes);
242            return Ok(fit.or(plan.expected_bytes));
243        }
244        if let Some(bytes) = plan.expected_bytes {
245            return Ok(Some(bytes));
246        }
247        if plan.spec.audio_only || plan.spec.video.crf.is_none() {
248            return Ok(None);
249        }
250        let tools = self.tools()?;
251        let encoder = resolve_encoder(&tools, plan)?;
252        let zscale = wants_zscale(&tools, plan);
253        Ok(predict_crf_bytes(&tools, plan, encoder, zscale))
254    }
255
256    /// The guard fired: deliver the source as-is (a byte copy, in its own
257    /// container/extension) instead of a re-encode that would not be smaller.
258    fn keep_original(
259        &self,
260        tools: &deepshrink_ffmpeg::Tools,
261        plan: &EncodePlan,
262        on_progress: &mut dyn FnMut(PassKind, f64),
263    ) -> Result<Outcome, EngineError> {
264        let _ = tools; // no ffmpeg needed: the source is delivered byte-for-byte
265        let output = match plan.input.extension() {
266            Some(ext) => plan.output.with_extension(ext),
267            None => plan.output.clone(),
268        };
269        // A plain copy, not a remux: "kept as-is" must mean identical bytes (a
270        // +faststart remux came out a few KB larger than the source).
271        fs::copy(&plan.input, &output)?;
272        on_progress(PassKind::Single, 1.0);
273        Ok(Outcome {
274            final_bytes: fs::metadata(&output)?.len(),
275            output,
276            vmaf: None,
277            already_compact: true,
278        })
279    }
280
281    /// Passthrough: the source already fits, so its streams are copied as-is.
282    ///
283    /// A stream copy is normally the cheapest and safest path, but it is not
284    /// infallible — some codecs simply cannot be muxed by the container's muxer
285    /// (ffmpeg needs a parser it may not have). Since nothing is being
286    /// re-encoded here, a failed remux falls back to copying the file verbatim:
287    /// the promise of this branch is "you get your file, unchanged and within
288    /// target", and that must hold for every input.
289    fn run_passthrough(
290        &self,
291        tools: &deepshrink_ffmpeg::Tools,
292        plan: &EncodePlan,
293        on_progress: &mut dyn FnMut(PassKind, f64),
294    ) -> Result<Outcome, EngineError> {
295        // Stream copy — the video encoder is never reached.
296        let args = build_pass_args(plan, PassKind::Single, "", "copy", false);
297        let remuxed = tools.run_pass(&args, plan.source_duration_sec, &mut |f| {
298            on_progress(PassKind::Single, f)
299        });
300        if remuxed.is_err() {
301            fs::copy(&plan.input, &plan.output)?;
302            on_progress(PassKind::Single, 1.0);
303        }
304        let size = fs::metadata(&plan.output)?.len();
305        Ok(Outcome {
306            output: plan.output.clone(),
307            final_bytes: size,
308            vmaf: None,
309            already_compact: true,
310        })
311    }
312
313    /// Search CRF for the smallest output that still meets `target_vmaf`.
314    ///
315    /// Each trial is a single-pass CRF encode into `plan.output` followed by a
316    /// VMAF measurement against the source. Drives [`budget::search_crf`], so
317    /// the search algorithm itself is unit-tested separately. Falls back to a
318    /// plain encode if the source resolution is unknown (nothing to measure).
319    fn run_crf_search(
320        &self,
321        tools: &deepshrink_ffmpeg::Tools,
322        plan: &EncodePlan,
323        encoder: &str,
324        zscale: bool,
325        target_vmaf: f64,
326        on_progress: &mut dyn FnMut(PassKind, f64),
327    ) -> Result<Outcome, EngineError> {
328        let (ref_w, ref_h) = match (plan.source_width, plan.source_height) {
329            (Some(w), Some(h)) => (w, h),
330            _ => return self.run_plain(tools, plan, encoder, zscale, on_progress),
331        };
332        let ref_fps = plan.source_fps.unwrap_or(0.0);
333        let total = plan.source_duration_sec;
334        let (lo, hi) = plan.spec.video.codec.crf_search_bounds();
335        let n_threads = thread_count();
336
337        let mut err: Option<EngineError> = None;
338        let mut last_crf: Option<u8> = None;
339
340        let (chosen_crf, chosen_vmaf) = budget::search_crf(target_vmaf, lo, hi, |crf| {
341            if err.is_some() {
342                return f64::NEG_INFINITY;
343            }
344            match encode_at_crf(tools, plan, encoder, zscale, crf, total, on_progress).and_then(
345                |()| {
346                    last_crf = Some(crf);
347                    deepshrink_ffmpeg::measure_vmaf(
348                        &tools.ffmpeg,
349                        &plan.output,
350                        &plan.input,
351                        ref_w,
352                        ref_h,
353                        ref_fps,
354                        n_threads,
355                    )
356                    .map_err(EngineError::from)
357                },
358            ) {
359                Ok(v) => v,
360                Err(e) => {
361                    err = Some(e);
362                    f64::NEG_INFINITY
363                }
364            }
365        });
366        if let Some(e) = err {
367            return Err(e);
368        }
369
370        // Leave the chosen CRF on disk (the search may have ended elsewhere).
371        if last_crf != Some(chosen_crf) {
372            encode_at_crf(tools, plan, encoder, zscale, chosen_crf, total, on_progress)?;
373        }
374        let size = fs::metadata(&plan.output)?.len();
375        Ok(Outcome {
376            output: plan.output.clone(),
377            final_bytes: size,
378            vmaf: Some(chosen_vmaf),
379            already_compact: false,
380        })
381    }
382
383    /// Measure the VMAF of an encoded `output` against the plan's source.
384    /// Returns `None` on any failure or when the source dimensions are unknown.
385    fn measure_output(
386        &self,
387        tools: &deepshrink_ffmpeg::Tools,
388        plan: &EncodePlan,
389        output: &Path,
390    ) -> Option<f64> {
391        let (w, h) = (plan.source_width?, plan.source_height?);
392        let fps = plan.source_fps.unwrap_or(0.0);
393        deepshrink_ffmpeg::measure_vmaf(
394            &tools.ffmpeg,
395            output,
396            &plan.input,
397            w,
398            h,
399            fps,
400            thread_count(),
401        )
402        .ok()
403    }
404}
405
406impl Engine for MediaEngine {
407    fn supports(&self, input: &Path) -> bool {
408        matches!(detect_kind(input), MediaKind::Video | MediaKind::Audio)
409    }
410
411    fn probe(&self, input: &Path) -> Result<MediaInfo, EngineError> {
412        let tools = deepshrink_ffmpeg::locate()?;
413        let p = deepshrink_ffmpeg::probe(&tools.ffprobe, input)?;
414
415        let video = p.video_stream();
416        let audio = p.audio_stream();
417        // Prefer ffprobe's reported size; fall back to the filesystem.
418        let size_bytes = p
419            .size_bytes()
420            .or_else(|| fs::metadata(input).ok().map(|m| m.len()))
421            .unwrap_or(0);
422
423        Ok(MediaInfo {
424            path: input.to_path_buf(),
425            kind: detect_kind(input),
426            duration_sec: p.duration_sec().unwrap_or(0.0),
427            size_bytes,
428            // As shown: a phone's portrait clip is stored landscape + rotation.
429            width: video.and_then(|v| v.display_size().0),
430            height: video.and_then(|v| v.display_size().1),
431            fps: p.fps(),
432            video_codec: video.and_then(|v| v.codec_name.clone()),
433            audio_codec: audio.and_then(|a| a.codec_name.clone()),
434            audio_channels: audio.and_then(|a| a.channels),
435            audio_bitrate_bps: p.audio_bitrate_bps(),
436            capture: capture_meta(&p),
437            hdr: video
438                .and_then(|v| v.color_transfer.as_deref())
439                .and_then(Hdr::from_transfer),
440        })
441    }
442
443    fn plan(&self, info: &MediaInfo, opts: &ShrinkOpts) -> Result<EncodePlan, EngineError> {
444        // ffmpeg is asked about Apple's encoder only when it's requested.
445        let hw = opts.hardware && opts.target_vmaf.is_none() && hardware_encoding_available();
446        super::plan::plan(info, opts, hw)
447    }
448
449    fn run(&self, plan: &EncodePlan) -> Result<Outcome, EngineError> {
450        self.run_with_progress(plan, &mut |_, _| {})
451    }
452}
453
454/// Whether this Mac can encode with Apple's hardware (VideoToolbox) with a
455/// constant-quality target: Apple Silicon and an ffmpeg with the encoders.
456/// Asked once per process (it spawns `ffmpeg -encoders`).
457pub fn hardware_encoding_available() -> bool {
458    static AVAILABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
459    *AVAILABLE.get_or_init(|| {
460        // VideoToolbox's constant quality (`-q:v`) is Apple Silicon only.
461        cfg!(all(target_os = "macos", target_arch = "aarch64"))
462            && deepshrink_ffmpeg::locate().is_ok_and(|t| {
463                deepshrink_ffmpeg::has_encoder(&t.ffmpeg, "h264_videotoolbox")
464                    && deepshrink_ffmpeg::has_encoder(&t.ffmpeg, "hevc_videotoolbox")
465            })
466    })
467}
468
469/// Best-effort: give `output` the modification time of `input`.
470fn copy_mtime(input: &Path, output: &Path) {
471    let Ok(mtime) = fs::metadata(input).and_then(|m| m.modified()) else {
472        return;
473    };
474    if let Ok(f) = fs::File::options().write(true).open(output) {
475        let _ = f.set_modified(mtime);
476    }
477}
478
479/// Read the capture metadata from the probe's container tags.
480fn capture_meta(p: &deepshrink_ffmpeg::Ffprobe) -> CaptureMeta {
481    let tag = |keys: &[&str]| {
482        keys.iter()
483            .find_map(|k| p.format_tag(k))
484            .map(str::to_string)
485    };
486    let created_local = tag(&["com.apple.quicktime.creationdate"]);
487    let created_utc = created_local
488        .as_deref()
489        .and_then(to_utc)
490        .or_else(|| tag(&["creation_time"]));
491    CaptureMeta {
492        created_utc,
493        created_local,
494        location: tag(&["com.apple.quicktime.location.ISO6709", "location"]),
495        make: tag(&["com.apple.quicktime.make", "make"]),
496        model: tag(&["com.apple.quicktime.model", "model"]),
497    }
498}
499
500/// Metadata flags for the output. Keep = map the source's global metadata,
501/// then re-state the capture tags explicitly (`-metadata k=v`): ffmpeg's own
502/// copy of an iPhone's `com.apple.quicktime.*` keys (`use_metadata_tags`) is
503/// not readable by Apple's frameworks, whereas `location` / `make` / `model` /
504/// `date` land in QuickTime user data (©xyz, ©mak, …) that Photos and Finder
505/// read, and `creation_time` sets the movie header. Strip = drop it all.
506fn metadata_args(plan: &EncodePlan) -> (Vec<OsString>, Option<&'static str>) {
507    if !plan.spec.keep_metadata {
508        return (vec!["-map_metadata".into(), "-1".into()], None);
509    }
510    let mut a: Vec<OsString> = vec!["-map_metadata".into(), "0".into()];
511    for (k, v) in &plan.spec.tags {
512        a.push("-metadata".into());
513        a.push(format!("{k}={v}").into());
514    }
515    (a, None)
516}
517
518/// `-movflags` value combining faststart and metadata tags (None = no flag).
519fn movflags(faststart: bool, meta: Option<&'static str>) -> Option<String> {
520    let mut v = String::new();
521    if faststart {
522        v.push_str("+faststart");
523    }
524    if let Some(m) = meta {
525        v.push_str(m);
526    }
527    (!v.is_empty()).then_some(v)
528}
529
530/// [`ceiling_plan`] and its predicted size, if sample encodes say it lands
531/// comfortably under the target (the same ~2–3 s of samples as the
532/// quality-mode preview).
533fn ceiling_fit(
534    tools: &deepshrink_ffmpeg::Tools,
535    plan: &EncodePlan,
536    encoder: &str,
537    zscale: bool,
538) -> Option<(EncodePlan, u64)> {
539    let target = plan.target_bytes?;
540    let ceiling = ceiling_plan(plan)?;
541    let predicted = predict_crf_bytes(tools, &ceiling, encoder, zscale)?;
542    ((predicted as f64) < target as f64 * CEILING_MARGIN).then_some((ceiling, predicted))
543}
544
545/// Whether to tone-map with `zscale` — asked of ffmpeg only for a PQ source.
546fn wants_zscale(tools: &deepshrink_ffmpeg::Tools, plan: &EncodePlan) -> bool {
547    plan.spec.video.to_sdr == Some(Hdr::Pq)
548        && deepshrink_ffmpeg::has_filter(&tools.ffmpeg, "zscale")
549}
550
551/// Predict a CRF video encode's final size from short sample encodes (same
552/// encoder, CRF, preset, scaling, fps; audio at the planned bitrate): three
553/// 3 s windows, or the whole clip when it's under 12 s. `None` if a sample fails.
554fn predict_crf_bytes(
555    tools: &deepshrink_ffmpeg::Tools,
556    plan: &EncodePlan,
557    encoder: &str,
558    zscale: bool,
559) -> Option<u64> {
560    let duration = plan.source_duration_sec;
561    if !duration.is_finite() || duration <= 0.0 {
562        return None;
563    }
564    let (windows, bias) = sample_windows(plan);
565    let mut sample = plan.clone();
566    sample.spec.audio = None;
567    sample.spec.faststart = false;
568    let mut video_bytes = 0u64;
569    let mut sampled = 0.0;
570    for (i, &(start, len)) in windows.iter().enumerate() {
571        sample.output =
572            std::env::temp_dir().join(format!("deepshrink-sample-{}-{i}.mp4", std::process::id()));
573        let mut args = build_pass_args(&sample, PassKind::Single, "", encoder, zscale);
574        let at_input = args.iter().position(|a| a == "-i")?;
575        args.splice(
576            at_input..at_input,
577            [
578                OsString::from("-ss"),
579                OsString::from(format!("{start:.2}")),
580                OsString::from("-t"),
581                OsString::from(format!("{len:.2}")),
582            ],
583        );
584        let ran = tools.run_pass(&args, len, &mut |_| {});
585        let bytes = fs::metadata(&sample.output).map(|m| m.len()).ok();
586        let _ = fs::remove_file(&sample.output);
587        video_bytes += bytes.filter(|_| ran.is_ok())?;
588        sampled += len;
589    }
590    Some(predicted_bytes(plan, video_bytes, sampled, bias))
591}
592
593/// The `-vf` chain: downscale first (fewer pixels to convert), then HDR → SDR.
594///
595/// HLG (phones) was designed to stay watchable as SDR: `colorspace` re-maps
596/// BT.2020 → BT.709 reading the HLG curve as the BT.2020 gamma — side by side
597/// with an iPhone clip it's the closest match to what macOS itself shows, and
598/// it works in every ffmpeg build. PQ (HDR10) needs a real tone-map, which
599/// takes `zscale` (libzimg — in the app's bundled ffmpeg, not in every build);
600/// without it PQ falls back to `colorspace` too: flatter, but 8-bit SDR that plays.
601fn video_filters(video: &VideoSpec, zscale: bool) -> Option<String> {
602    const COLORSPACE: &str = "colorspace=all=bt709:iall=bt2020:itrc=bt2020-10:format=yuv420p";
603    let mut chain = Vec::new();
604    // The cap is the short side: the width of a portrait video.
605    if let Some(h) = video.height {
606        chain.push(if video.portrait {
607            format!("scale={h}:-2")
608        } else {
609            format!("scale=-2:{h}")
610        });
611    }
612    match video.to_sdr {
613        Some(Hdr::Pq) if zscale => chain.push(
614            "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,\
615             tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p"
616                .to_string(),
617        ),
618        Some(_) => chain.push(COLORSPACE.to_string()),
619        None => {}
620    }
621    (!chain.is_empty()).then(|| chain.join(","))
622}
623
624/// Base path for ffmpeg's two-pass log, unique per process + input stem.
625fn passlog_base(plan: &EncodePlan) -> String {
626    let stem = plan
627        .input
628        .file_stem()
629        .map(|s| s.to_string_lossy().into_owned())
630        .unwrap_or_else(|| "ds".to_string());
631    let dir = std::env::temp_dir();
632    dir.join(format!("deepshrink-{}-{}", std::process::id(), stem))
633        .to_string_lossy()
634        .into_owned()
635}
636
637/// Remove the files ffmpeg leaves behind for `-passlogfile <base>`.
638fn cleanup_passlog(base: &str) {
639    for suffix in ["-0.log", "-0.log.mbtree"] {
640        let _ = fs::remove_file(format!("{base}{suffix}"));
641    }
642}
643
644/// Encode a single-pass CRF trial into `plan.output` at the given CRF.
645fn encode_at_crf(
646    tools: &deepshrink_ffmpeg::Tools,
647    plan: &EncodePlan,
648    encoder: &str,
649    zscale: bool,
650    crf: u8,
651    total: f64,
652    on_progress: &mut dyn FnMut(PassKind, f64),
653) -> Result<(), EngineError> {
654    let mut trial = plan.clone();
655    trial.spec.video.crf = Some(crf);
656    trial.spec.video.bitrate_bps = None;
657    trial.spec.two_pass = false;
658    let args = build_pass_args(&trial, PassKind::Single, "", encoder, zscale);
659    tools.run_pass(&args, total, &mut |f| on_progress(PassKind::Single, f))?;
660    Ok(())
661}
662
663/// Threads to hand libvmaf (bounded by available parallelism).
664fn thread_count() -> usize {
665    std::thread::available_parallelism()
666        .map(|n| n.get())
667        .unwrap_or(1)
668}
669
670/// Platform null sink for the discard output of pass 1.
671fn null_sink() -> &'static str {
672    if cfg!(windows) {
673        "NUL"
674    } else {
675        "/dev/null"
676    }
677}
678
679/// Pick the ffmpeg encoder to drive this plan with.
680///
681/// x264/x265 are in every build worth supporting, so they're taken on faith —
682/// asking ffmpeg costs a process spawn per run. AV1 is the exception: builds
683/// disagree on which (if any) AV1 encoder they carry, so it's probed, with
684/// libaom as the fallback and a plain-English error when neither is present
685/// (better than handing the user ffmpeg's "Unknown encoder" dump).
686fn resolve_encoder(
687    tools: &deepshrink_ffmpeg::Tools,
688    plan: &EncodePlan,
689) -> Result<&'static str, EngineError> {
690    let codec = plan.spec.video.codec;
691    // Apple's hardware encoder (availability was checked when planning).
692    if plan.spec.video.hardware && !plan.spec.passthrough && !plan.spec.audio_only {
693        if let Some(hw) = codec.hardware_encoder() {
694            return Ok(hw);
695        }
696    }
697    let primary = codec.encoder();
698    let Some(fallback) = codec.fallback_encoder() else {
699        return Ok(primary);
700    };
701    // Passthrough/audio-only encodes never touch the video encoder.
702    if plan.spec.passthrough || plan.spec.audio_only {
703        return Ok(primary);
704    }
705    if deepshrink_ffmpeg::has_encoder(&tools.ffmpeg, primary) {
706        return Ok(primary);
707    }
708    if deepshrink_ffmpeg::has_encoder(&tools.ffmpeg, fallback) {
709        return Ok(fallback);
710    }
711    Err(EngineError::Unsupported(format!(
712        "this ffmpeg build has no {} encoder (looked for {primary} and {fallback})",
713        codec.label()
714    )))
715}
716
717/// Build the ffmpeg argv for one pass. Video-processing options (codec, filters,
718/// bitrate) are shared across passes; audio/output differ per pass. `encoder` is
719/// the resolved `-c:v` name (see [`resolve_encoder`]) — it can differ from the
720/// codec's default for AV1.
721fn build_pass_args(
722    plan: &EncodePlan,
723    pass: PassKind,
724    passlog: &str,
725    encoder: &str,
726    zscale: bool,
727) -> Vec<OsString> {
728    let s = &plan.spec;
729    let mut a: Vec<OsString> = Vec::new();
730    // Local helper — a macro (not a closure) so it doesn't hold a borrow of `a`
731    // across the direct `a.push(..)` calls used for OsString paths.
732    macro_rules! push {
733        ($arg:expr) => {
734            a.push(OsString::from($arg))
735        };
736    }
737
738    push!("-hide_banner");
739    push!("-y");
740    push!("-loglevel");
741    push!("error");
742    push!("-progress");
743    push!("pipe:1");
744    push!("-nostats");
745    push!("-i");
746    a.push(plan.input.clone().into_os_string());
747
748    let (meta, meta_flag) = metadata_args(plan);
749
750    // Passthrough: stream copy, no re-encode. Output only (single pass).
751    if s.passthrough {
752        push!("-c");
753        push!("copy");
754        a.extend(meta.iter().cloned());
755        if let Some(flags) = movflags(s.faststart, meta_flag) {
756            push!("-movflags");
757            push!(flags);
758        }
759        a.push(plan.output.clone().into_os_string());
760        return a;
761    }
762
763    // Pure audio: drop video, encode the audio track only (single pass).
764    if s.audio_only {
765        push!("-vn");
766        if let Some(au) = &s.audio {
767            push!("-c:a");
768            push!(au.codec.encoder());
769            if au.mono {
770                push!("-ac");
771                push!("1");
772            }
773            if let Some(sr) = au.sample_rate {
774                push!("-ar");
775                push!(sr.to_string());
776            }
777            push!("-b:a");
778            push!(au.bitrate_bps.to_string());
779            // Opus supports VBR; use constrained VBR by default for a tighter
780            // fit to the target, or full VBR when requested.
781            if matches!(au.codec, AudioCodec::Opus) {
782                push!("-vbr");
783                push!(if au.vbr { "on" } else { "constrained" });
784            }
785        }
786        a.extend(meta.iter().cloned());
787        if let Some(flags) = movflags(false, meta_flag) {
788            push!("-movflags");
789            push!(flags);
790        }
791        a.push(plan.output.clone().into_os_string());
792        return a;
793    }
794
795    // Video codec + filters.
796    push!("-c:v");
797    push!(encoder);
798    if let Some(vf) = video_filters(&s.video, zscale) {
799        push!("-vf");
800        push!(vf);
801    }
802    if let Some(f) = s.video.fps {
803        push!("-r");
804        push!(f.to_string());
805    }
806    // The speed knob is per-encoder: `-preset medium` is meaningless (and fatal)
807    // to SVT-AV1, which wants a number.
808    // VideoToolbox has no speed preset — it's fast by construction.
809    let videotoolbox = encoder.ends_with("_videotoolbox");
810    if !videotoolbox {
811        let (speed_flag, speed_value) = s.video.preset.speed_flags(encoder);
812        push!(speed_flag);
813        push!(speed_value);
814    }
815    if let Some(tag) = s.video.codec.mp4_tag() {
816        push!("-tag:v");
817        push!(tag);
818    }
819    // Tone-mapped to SDR: 8-bit, and labelled BT.709 so players don't treat
820    // it as HDR (the source's BT.2020/HLG tags would otherwise carry over).
821    if s.video.to_sdr.is_some() {
822        for (flag, value) in [
823            ("-pix_fmt", "yuv420p"),
824            ("-color_primaries", "bt709"),
825            ("-color_trc", "bt709"),
826            ("-colorspace", "bt709"),
827        ] {
828            push!(flag);
829            push!(value);
830        }
831    }
832
833    // Rate control.
834    match (s.video.bitrate_bps, s.video.crf) {
835        (Some(bps), _) => {
836            push!("-b:v");
837            push!(bps.to_string());
838            if s.two_pass {
839                push!("-pass");
840                push!(match pass {
841                    PassKind::First => "1",
842                    _ => "2",
843                });
844                push!("-passlogfile");
845                push!(passlog);
846            }
847        }
848        (_, Some(crf)) => {
849            // Apple's encoder takes a constant quality (1–100), not a CRF.
850            push!(if videotoolbox { "-q:v" } else { "-crf" });
851            push!(crf.to_string());
852        }
853        _ => {}
854    }
855
856    // Audio + output.
857    match pass {
858        PassKind::First => {
859            // Analysis pass: no audio, discard the muxed output.
860            push!("-an");
861            push!("-f");
862            push!("null");
863            push!(null_sink());
864        }
865        PassKind::Second | PassKind::Single => {
866            match &s.audio {
867                Some(au) => {
868                    push!("-c:a");
869                    push!(au.codec.encoder());
870                    // A mono downmix has to reach ffmpeg here too — the audio
871                    // track of a video is muxed in this pass, not the audio-only
872                    // branch above.
873                    if au.mono {
874                        push!("-ac");
875                        push!("1");
876                    }
877                    push!("-b:a");
878                    push!(au.bitrate_bps.to_string());
879                }
880                None => push!("-an"),
881            }
882            a.extend(meta.iter().cloned());
883            if let Some(flags) = movflags(s.faststart, meta_flag) {
884                push!("-movflags");
885                push!(flags);
886            }
887            a.push(plan.output.clone().into_os_string());
888        }
889    }
890    a
891}
892
893#[cfg(test)]
894mod tests {
895    use super::*;
896    use crate::engine::SizeGoal;
897    use crate::options::{AudioChoice, AudioCodec, QualityPreset, ResolutionOpt, VideoCodec};
898    use crate::size::preset;
899    use std::path::PathBuf;
900
901    /// The encoder `run` would resolve for a plan without probing ffmpeg (every
902    /// codec these tests use has its primary encoder everywhere).
903    fn enc(plan: &EncodePlan) -> &'static str {
904        plan.spec.video.codec.encoder()
905    }
906
907    fn video_info(duration: f64, size: u64, w: u32, h: u32, audio: bool) -> MediaInfo {
908        MediaInfo {
909            path: PathBuf::from("/tmp/clip.mp4"),
910            kind: MediaKind::Video,
911            duration_sec: duration,
912            size_bytes: size,
913            width: Some(w),
914            height: Some(h),
915            fps: Some(30.0),
916            video_codec: Some("h264".into()),
917            audio_codec: if audio { Some("aac".into()) } else { None },
918            audio_channels: if audio { Some(2) } else { None },
919            audio_bitrate_bps: None,
920            capture: CaptureMeta::default(),
921            hdr: None,
922        }
923    }
924
925    fn opts_target(bytes: u64) -> ShrinkOpts {
926        ShrinkOpts {
927            goal: SizeGoal::Target(bytes),
928            ..Default::default()
929        }
930    }
931
932    #[test]
933    fn supports_video_and_audio() {
934        let e = MediaEngine::new();
935        assert!(e.supports(&PathBuf::from("clip.mp4")));
936        assert!(e.supports(&PathBuf::from("lecture.wav")));
937        assert!(!e.supports(&PathBuf::from("photo.jpg")));
938    }
939
940    #[test]
941    fn plan_target_builds_two_pass_with_budget() {
942        let info = video_info(120.0, 300_000_000, 1920, 1080, true);
943        let plan = MediaEngine::new()
944            .plan(&info, &opts_target(8_000_000))
945            .unwrap();
946
947        assert!(plan.spec.two_pass);
948        assert_eq!(plan.target_bytes, Some(8_000_000));
949        assert_eq!(plan.output, PathBuf::from("/tmp/clip.shrink.mp4"));
950        let vbps = plan.spec.video.bitrate_bps.unwrap();
951        assert!(vbps >= budget::ABSOLUTE_MIN_VIDEO_BPS);
952        // 8 MB over 120 s is a low budget → downscale from 1080p.
953        assert!(plan.spec.video.height.is_some());
954        assert!(plan.spec.audio.is_some());
955        // Predicted size should not exceed the target.
956        assert!(plan.expected_bytes.unwrap() <= 8_000_000 + 8_000_000 / 20);
957    }
958
959    #[test]
960    fn plan_video_mono_downmixes_the_audio_track() {
961        let info = video_info(60.0, 100_000_000, 1280, 720, true);
962        let opts = ShrinkOpts {
963            mono: true,
964            ..opts_target(8_000_000)
965        };
966        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
967        let audio = plan.spec.audio.as_ref().expect("kept audio track");
968        assert!(audio.mono, "opts.mono downmixes the video's audio track");
969        // A stereo request stays stereo.
970        let stereo = MediaEngine::new()
971            .plan(&info, &opts_target(8_000_000))
972            .unwrap();
973        assert!(!stereo.spec.audio.as_ref().unwrap().mono);
974    }
975
976    #[test]
977    fn video_mono_reaches_ffmpeg_as_ac_1() {
978        // The plan carrying `mono` is only half the job — the muxing pass of a
979        // video encode has to actually emit `-ac 1`, or the output stays stereo.
980        let info = video_info(60.0, 100_000_000, 1280, 720, true);
981        let plan = MediaEngine::new()
982            .plan(
983                &info,
984                &ShrinkOpts {
985                    mono: true,
986                    ..opts_target(8_000_000)
987                },
988            )
989            .unwrap();
990        let args = build_pass_args(&plan, PassKind::Second, "/tmp/passlog", enc(&plan), false);
991        let joined: Vec<String> = args
992            .iter()
993            .map(|a| a.to_string_lossy().into_owned())
994            .collect();
995        let ac = joined.iter().position(|a| a == "-ac").expect("-ac emitted");
996        assert_eq!(joined[ac + 1], "1");
997
998        // Stereo request → no downmix flag at all.
999        let stereo = MediaEngine::new()
1000            .plan(&info, &opts_target(8_000_000))
1001            .unwrap();
1002        let stereo_args: Vec<String> = build_pass_args(
1003            &stereo,
1004            PassKind::Second,
1005            "/tmp/passlog",
1006            enc(&stereo),
1007            false,
1008        )
1009        .iter()
1010        .map(|a| a.to_string_lossy().into_owned())
1011        .collect();
1012        assert!(!stereo_args.iter().any(|a| a == "-ac"));
1013    }
1014
1015    #[test]
1016    fn plan_preset_discord_sets_target() {
1017        let info = video_info(30.0, 50_000_000, 1280, 720, true);
1018        let opts = ShrinkOpts {
1019            goal: SizeGoal::Preset(preset("discord").unwrap()),
1020            ..Default::default()
1021        };
1022        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1023        assert_eq!(plan.target_bytes, Some(8_000_000));
1024    }
1025
1026    #[test]
1027    fn plan_reduce_targets_complement_of_original() {
1028        let info = video_info(60.0, 100_000_000, 1920, 1080, true);
1029        let opts = ShrinkOpts {
1030            goal: SizeGoal::Reduce(0.70),
1031            ..Default::default()
1032        };
1033        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1034        assert_eq!(plan.target_bytes, Some(30_000_000));
1035    }
1036
1037    #[test]
1038    fn plan_passthrough_when_source_already_fits() {
1039        // Source is 200 KB, target 1 MB → never inflate; stream-copy remux.
1040        let info = video_info(10.0, 200_000, 1280, 720, true);
1041        let plan = MediaEngine::new()
1042            .plan(&info, &opts_target(1_000_000))
1043            .unwrap();
1044        assert!(plan.spec.passthrough);
1045        assert!(!plan.spec.two_pass);
1046        assert_eq!(plan.expected_bytes, Some(200_000));
1047        let args = build_pass_args(&plan, PassKind::Single, "/tmp/passlog", enc(&plan), false);
1048        let joined: Vec<String> = args
1049            .iter()
1050            .map(|a| a.to_string_lossy().into_owned())
1051            .collect();
1052        assert!(joined.contains(&"copy".to_string()));
1053        // Same container as the source: a stream copy must land somewhere its
1054        // codecs are muxable.
1055        assert_eq!(plan.output, PathBuf::from("/tmp/clip.shrink.mp4"));
1056    }
1057
1058    #[test]
1059    fn plan_passthrough_keeps_the_source_container() {
1060        // A .3gp may carry codecs (AMR-NB) that no .mp4 muxer accepts — copying
1061        // its streams into an .mp4 would fail on a file we aren't re-encoding.
1062        let info = MediaInfo {
1063            path: PathBuf::from("/tmp/voice.3gp"),
1064            ..video_info(10.0, 200_000, 320, 240, true)
1065        };
1066        let plan = MediaEngine::new()
1067            .plan(&info, &opts_target(1_000_000))
1068            .unwrap();
1069        assert!(plan.spec.passthrough);
1070        assert_eq!(plan.output, PathBuf::from("/tmp/voice.shrink.3gp"));
1071    }
1072
1073    #[test]
1074    fn plan_infeasible_when_target_too_small() {
1075        let info = video_info(600.0, 500_000_000, 1920, 1080, true);
1076        let err = MediaEngine::new().plan(&info, &opts_target(50_000));
1077        assert!(matches!(err, Err(EngineError::Infeasible)));
1078    }
1079
1080    #[test]
1081    fn plan_quality_mode_uses_crf_single_pass() {
1082        let info = video_info(60.0, 100_000_000, 1920, 1080, true);
1083        let opts = ShrinkOpts {
1084            goal: SizeGoal::Quality,
1085            quality: QualityPreset::Balanced,
1086            ..Default::default()
1087        };
1088        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1089        assert!(!plan.spec.two_pass);
1090        assert_eq!(plan.spec.video.crf, Some(23));
1091        assert!(plan.spec.video.bitrate_bps.is_none());
1092        assert!(plan.expected_bytes.is_none());
1093    }
1094
1095    #[test]
1096    fn plan_drops_audio_when_requested() {
1097        let info = video_info(30.0, 50_000_000, 1280, 720, true);
1098        let opts = ShrinkOpts {
1099            audio: AudioChoice::Drop,
1100            ..opts_target(8_000_000)
1101        };
1102        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1103        assert!(plan.spec.audio.is_none());
1104    }
1105
1106    fn audio_info(duration: f64, size: u64, channels: u32) -> MediaInfo {
1107        MediaInfo {
1108            path: PathBuf::from("/tmp/lecture.wav"),
1109            kind: MediaKind::Audio,
1110            duration_sec: duration,
1111            size_bytes: size,
1112            width: None,
1113            height: None,
1114            fps: None,
1115            video_codec: None,
1116            audio_codec: Some("pcm_s16le".into()),
1117            audio_channels: Some(channels),
1118            audio_bitrate_bps: None,
1119            capture: CaptureMeta::default(),
1120            hdr: None,
1121        }
1122    }
1123
1124    #[test]
1125    fn quality_audio_bitrate_follows_tier_codec_and_channels() {
1126        use QualityPreset::*;
1127        assert_eq!(quality_audio_bps(Balanced, AudioCodec::Aac, false), 128_000);
1128        assert_eq!(quality_audio_bps(Balanced, AudioCodec::Aac, true), 64_000);
1129        assert_eq!(quality_audio_bps(Fast, AudioCodec::Opus, true), 32_000);
1130        assert_eq!(quality_audio_bps(Max, AudioCodec::Mp3, false), 256_000);
1131        // Every tier is strictly smaller → larger, per codec.
1132        for c in [AudioCodec::Aac, AudioCodec::Opus, AudioCodec::Mp3] {
1133            let t: Vec<_> = [Fast, Balanced, Max]
1134                .map(|q| quality_audio_bps(q, c, false))
1135                .into();
1136            assert!(t[0] < t[1] && t[1] < t[2], "{c:?}: {t:?}");
1137        }
1138    }
1139
1140    #[test]
1141    fn a_compact_audiobook_is_kept_in_quality_mode() {
1142        // 1 h mono at 64 kbps (the review case): balanced AAC mono is 64 kbps too.
1143        let mut info = audio_info(3600.0, 64_000 / 8 * 3600, 1);
1144        info.path = PathBuf::from("/tmp/book.mp3");
1145        let plan = MediaEngine::new()
1146            .plan(&info, &ShrinkOpts::default())
1147            .unwrap();
1148        assert!(plan.spec.passthrough, "{}", plan.summary);
1149        assert!(plan.output.to_string_lossy().ends_with(".mp3"));
1150        assert!(plan.summary.contains("already compact"));
1151
1152        // A genuinely smaller recipe still encodes (Opus fast mono = 32 kbps).
1153        let smaller = ShrinkOpts {
1154            audio_codec: AudioCodec::Opus,
1155            quality: QualityPreset::Fast,
1156            ..ShrinkOpts::default()
1157        };
1158        let plan = MediaEngine::new().plan(&info, &smaller).unwrap();
1159        assert!(!plan.spec.passthrough);
1160        assert_eq!(plan.spec.audio.as_ref().unwrap().bitrate_bps, 32_000);
1161        assert!(
1162            plan.guard_larger,
1163            "quality mode keeps the post-encode check"
1164        );
1165
1166        // Opting out re-encodes at the tier bitrate.
1167        let allow = ShrinkOpts {
1168            allow_larger: true,
1169            ..ShrinkOpts::default()
1170        };
1171        let plan = MediaEngine::new().plan(&info, &allow).unwrap();
1172        assert!(!plan.spec.passthrough && !plan.guard_larger);
1173    }
1174
1175    #[test]
1176    fn the_guard_is_for_quality_mode_only() {
1177        let info = video_info(60.0, 50_000_000, 1920, 1080, true);
1178        let quality = MediaEngine::new()
1179            .plan(&info, &ShrinkOpts::default())
1180            .unwrap();
1181        assert!(quality.guard_larger);
1182        let target = MediaEngine::new()
1183            .plan(&info, &opts_target(10_000_000))
1184            .unwrap();
1185        assert!(!target.guard_larger, "a size target is its own guarantee");
1186    }
1187
1188    #[test]
1189    fn plan_audio_single_pass_with_fitted_bitrate() {
1190        // 58 min stereo lecture, target 10 MB.
1191        let info = audio_info(3480.0, 600_000_000, 2);
1192        let plan = MediaEngine::new()
1193            .plan(&info, &opts_target(10_000_000))
1194            .unwrap();
1195        assert!(plan.spec.audio_only);
1196        assert!(!plan.spec.two_pass);
1197        assert_eq!(plan.output, PathBuf::from("/tmp/lecture.shrink.m4a"));
1198        let au = plan.spec.audio.as_ref().unwrap();
1199        // Snapped down to a standard step, never above the raw budget.
1200        assert!(budget::AUDIO_STEPS.contains(&au.bitrate_bps));
1201        assert!(plan.expected_bytes.unwrap() <= 10_000_000 + 10_000_000 / 20);
1202    }
1203
1204    #[test]
1205    fn plan_audio_mono_source_marked_speech() {
1206        let info = audio_info(600.0, 100_000_000, 1);
1207        let plan = MediaEngine::new()
1208            .plan(&info, &opts_target(5_000_000))
1209            .unwrap();
1210        assert!(plan.spec.audio.as_ref().unwrap().mono);
1211    }
1212
1213    #[test]
1214    fn plan_audio_opus_extension_and_vbr_args() {
1215        let info = audio_info(600.0, 100_000_000, 2);
1216        let opts = ShrinkOpts {
1217            audio_codec: AudioCodec::Opus,
1218            mono: true,
1219            ..opts_target(3_000_000)
1220        };
1221        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1222        assert_eq!(plan.output, PathBuf::from("/tmp/lecture.shrink.opus"));
1223        let args = build_pass_args(&plan, PassKind::Single, "/tmp/passlog", enc(&plan), false);
1224        let j: Vec<String> = args
1225            .iter()
1226            .map(|a| a.to_string_lossy().into_owned())
1227            .collect();
1228        assert!(j.contains(&"-vn".to_string()));
1229        assert!(j.contains(&"libopus".to_string()));
1230        assert!(j.contains(&"-ac".to_string())); // mono downmix
1231        assert!(j.contains(&"-vbr".to_string()));
1232    }
1233
1234    #[test]
1235    fn plan_audio_infeasible_when_target_tiny() {
1236        let info = audio_info(3600.0, 500_000_000, 2);
1237        assert!(matches!(
1238            MediaEngine::new().plan(&info, &opts_target(1_000)),
1239            Err(EngineError::Infeasible)
1240        ));
1241    }
1242
1243    #[test]
1244    fn plan_audio_passthrough_when_source_fits() {
1245        let info = audio_info(600.0, 2_000_000, 2);
1246        let plan = MediaEngine::new()
1247            .plan(&info, &opts_target(10_000_000))
1248            .unwrap();
1249        assert!(plan.spec.passthrough);
1250        // Passthrough keeps the source container/extension.
1251        assert_eq!(plan.output, PathBuf::from("/tmp/lecture.shrink.wav"));
1252    }
1253
1254    #[test]
1255    fn pass1_args_have_no_audio_and_null_sink() {
1256        let info = video_info(120.0, 300_000_000, 1920, 1080, true);
1257        let plan = MediaEngine::new()
1258            .plan(&info, &opts_target(8_000_000))
1259            .unwrap();
1260        let args = build_pass_args(&plan, PassKind::First, "/tmp/passlog", enc(&plan), false);
1261        let joined: Vec<String> = args
1262            .iter()
1263            .map(|a| a.to_string_lossy().into_owned())
1264            .collect();
1265        assert!(joined.contains(&"-an".to_string()));
1266        assert!(joined.contains(&"null".to_string()));
1267        assert!(joined.iter().any(|a| a == "1")); // -pass 1
1268        assert!(!joined.iter().any(|a| a.contains("shrink.mp4")));
1269    }
1270
1271    #[test]
1272    fn pass2_args_write_output_with_audio() {
1273        let info = video_info(120.0, 300_000_000, 1920, 1080, true);
1274        let plan = MediaEngine::new()
1275            .plan(&info, &opts_target(8_000_000))
1276            .unwrap();
1277        let args = build_pass_args(&plan, PassKind::Second, "/tmp/passlog", enc(&plan), false);
1278        let joined: Vec<String> = args
1279            .iter()
1280            .map(|a| a.to_string_lossy().into_owned())
1281            .collect();
1282        assert!(joined.iter().any(|a| a.contains("clip.shrink.mp4")));
1283        assert!(joined.contains(&"-c:a".to_string()));
1284        assert!(joined.iter().any(|a| a.contains("+faststart")));
1285        assert!(joined.iter().any(|a| a == "2")); // -pass 2
1286    }
1287
1288    fn joined(plan: &EncodePlan, pass: PassKind) -> Vec<String> {
1289        joined_with(plan, pass, false)
1290    }
1291
1292    fn joined_with(plan: &EncodePlan, pass: PassKind, zscale: bool) -> Vec<String> {
1293        build_pass_args(plan, pass, "/tmp/passlog", enc(plan), zscale)
1294            .iter()
1295            .map(|a| a.to_string_lossy().into_owned())
1296            .collect()
1297    }
1298
1299    #[test]
1300    fn hdr_transfer_is_recognised() {
1301        assert_eq!(Hdr::from_transfer("arib-std-b67"), Some(Hdr::Hlg));
1302        assert_eq!(Hdr::from_transfer("smpte2084"), Some(Hdr::Pq));
1303        assert_eq!(Hdr::from_transfer("bt709"), None);
1304    }
1305
1306    #[test]
1307    fn hdr_is_tone_mapped_to_sdr_for_size_targets_only() {
1308        let mut info = iphone_info();
1309        info.hdr = Some(Hdr::Hlg);
1310        let engine = MediaEngine::new();
1311
1312        // Discord: must play everywhere → 8-bit SDR BT.709.
1313        let target = engine.plan(&info, &opts_target(10_000_000)).unwrap();
1314        assert_eq!(target.spec.video.to_sdr, Some(Hdr::Hlg));
1315        assert!(target.summary.contains("HDR → SDR"));
1316        let vf_of =
1317            |args: &[String]| args[args.iter().position(|a| a == "-vf").unwrap() + 1].clone();
1318        // HLG: the colorspace re-map (closest to what macOS shows), any build.
1319        let hlg = joined_with(&target, PassKind::Second, true);
1320        let vf = vf_of(&hlg);
1321        assert!(
1322            vf.contains("colorspace=all=bt709") && !vf.contains("zscale"),
1323            "{vf}"
1324        );
1325        // Downscale first (a portrait clip: by its width), then convert the
1326        // fewer pixels.
1327        assert!(
1328            vf.find("scale=").unwrap() < vf.find("colorspace").unwrap(),
1329            "{vf}"
1330        );
1331        for pair in [
1332            ["-pix_fmt", "yuv420p"],
1333            ["-color_trc", "bt709"],
1334            ["-colorspace", "bt709"],
1335        ] {
1336            assert!(hlg.windows(2).any(|w| w == pair), "{pair:?}");
1337        }
1338        // PQ: a real tone-map with zscale, the colorspace re-map without it.
1339        let mut pq = target.clone();
1340        pq.spec.video.to_sdr = Some(Hdr::Pq);
1341        let vf = vf_of(&joined_with(&pq, PassKind::Second, true));
1342        assert!(
1343            vf.contains("tonemap=hable") && vf.contains("npl=100"),
1344            "{vf}"
1345        );
1346        let vf = vf_of(&joined_with(&pq, PassKind::Second, false));
1347        assert!(
1348            vf.contains("colorspace=all=bt709") && !vf.contains("zscale"),
1349            "{vf}"
1350        );
1351
1352        // Quality mode keeps HDR and 10-bit as shot.
1353        let quality = engine.plan(&info, &ShrinkOpts::default()).unwrap();
1354        assert_eq!(quality.spec.video.to_sdr, None);
1355        let args = joined(&quality, PassKind::Single);
1356        assert!(!args
1357            .iter()
1358            .any(|a| a == "-pix_fmt" || a.contains("colorspace")));
1359
1360        // An SDR source is left alone even with a target.
1361        let sdr = engine
1362            .plan(&iphone_info(), &opts_target(10_000_000))
1363            .unwrap();
1364        assert_eq!(sdr.spec.video.to_sdr, None);
1365        assert!(!joined(&sdr, PassKind::Second)
1366            .iter()
1367            .any(|a| a == "-pix_fmt"));
1368    }
1369
1370    #[test]
1371    fn a_size_target_is_a_ceiling_at_the_quality_crf() {
1372        let info = video_info(60.0, 200_000_000, 1920, 1080, true);
1373        let engine = MediaEngine::new();
1374        let opts = opts_target(50_000_000);
1375        let plan = engine.plan(&info, &opts).unwrap();
1376        let crf = opts.quality.default_crf(opts.video_codec);
1377        assert_eq!(plan.ceiling_crf, Some(crf));
1378
1379        let ceiling = ceiling_plan(&plan).unwrap();
1380        assert_eq!(ceiling.spec.video.crf, Some(crf));
1381        assert_eq!(ceiling.spec.video.bitrate_bps, None);
1382        assert!(!ceiling.spec.two_pass);
1383        // Same everything else: resolution, audio, output, the target itself.
1384        assert_eq!(ceiling.spec.video.height, plan.spec.video.height);
1385        assert_eq!(ceiling.spec.audio, plan.spec.audio);
1386        assert_eq!(ceiling.output, plan.output);
1387        assert_eq!(ceiling.target_bytes, plan.target_bytes);
1388
1389        // Quality mode and passthrough have no ceiling to try.
1390        let quality = engine.plan(&info, &ShrinkOpts::default()).unwrap();
1391        assert!(quality.ceiling_crf.is_none() && ceiling_plan(&quality).is_none());
1392        let fits = engine.plan(&info, &opts_target(300_000_000)).unwrap();
1393        assert!(fits.spec.passthrough && ceiling_plan(&fits).is_none());
1394    }
1395
1396    #[test]
1397    fn heavy_video_samples_shorter_windows() {
1398        let engine = MediaEngine::new();
1399        let mut info = video_info(120.0, 500_000_000, 1920, 1080, true);
1400        info.fps = Some(30.0);
1401        let plan = engine.plan(&info, &ShrinkOpts::default()).unwrap();
1402        assert_eq!(sample_secs(&plan), 3.0);
1403        info = video_info(120.0, 500_000_000, 3840, 2160, true);
1404        info.fps = Some(60.0);
1405        let plan = engine.plan(&info, &ShrinkOpts::default()).unwrap();
1406        assert_eq!(sample_secs(&plan), MIN_SAMPLE_SECS);
1407    }
1408
1409    #[test]
1410    fn apple_hardware_uses_quality_one_pass_and_no_preset() {
1411        let engine = MediaEngine::new();
1412        let info = video_info(60.0, 200_000_000, 1920, 1080, true);
1413        let mut plan = engine.plan(&info, &ShrinkOpts::default()).unwrap();
1414        // As a plan would be on an Apple Silicon Mac with `hardware: true`.
1415        plan.spec.video.hardware = true;
1416        plan.spec.video.crf = QualityPreset::Balanced.default_hw_quality(VideoCodec::H264);
1417        let args: Vec<String> =
1418            build_pass_args(&plan, PassKind::Single, "", "h264_videotoolbox", false)
1419                .iter()
1420                .map(|a| a.to_string_lossy().into_owned())
1421                .collect();
1422        assert!(args.windows(2).any(|w| w == ["-c:v", "h264_videotoolbox"]));
1423        assert!(args.windows(2).any(|w| w == ["-q:v", "66"]), "{args:?}");
1424        assert!(
1425            !args.iter().any(|a| a == "-crf" || a == "-preset"),
1426            "{args:?}"
1427        );
1428        let mut hw = plan.clone();
1429        hw.spec.passthrough = false;
1430        assert_eq!(
1431            resolve_encoder(
1432                &deepshrink_ffmpeg::Tools {
1433                    ffmpeg: "ffmpeg".into(),
1434                    ffprobe: "ffprobe".into(),
1435                    cancel: Default::default(),
1436                },
1437                &hw
1438            )
1439            .unwrap(),
1440            "h264_videotoolbox"
1441        );
1442        // AV1 has no Apple encoder: the quality map says so.
1443        assert_eq!(
1444            QualityPreset::Balanced.default_hw_quality(VideoCodec::Av1),
1445            None
1446        );
1447    }
1448
1449    #[test]
1450    fn a_portrait_video_is_capped_on_its_short_side() {
1451        let engine = MediaEngine::new();
1452        // As shown (probe applies the rotation): 2160 × 3840, portrait.
1453        let info = video_info(60.0, 200_000_000, 2160, 3840, true);
1454        let opts = ShrinkOpts {
1455            resolution: ResolutionOpt::Height(1080),
1456            ..ShrinkOpts::default()
1457        };
1458        let plan = engine.plan(&info, &opts).unwrap();
1459        assert_eq!(plan.spec.video.height, Some(1080));
1460        assert!(plan.spec.video.portrait);
1461        let args = joined(&plan, PassKind::Single);
1462        let vf = &args[args.iter().position(|a| a == "-vf").unwrap() + 1];
1463        // 1080 × 1920, not 608 × 1080.
1464        assert!(vf.starts_with("scale=1080:-2"), "{vf}");
1465
1466        // Landscape is unchanged: height is the short side.
1467        let info = video_info(60.0, 200_000_000, 3840, 2160, true);
1468        let plan = engine.plan(&info, &opts).unwrap();
1469        assert!(!plan.spec.video.portrait);
1470        let args = joined(&plan, PassKind::Single);
1471        assert!(args.iter().any(|a| a.starts_with("scale=-2:1080")));
1472    }
1473
1474    fn iphone_info() -> MediaInfo {
1475        let mut info = video_info(60.0, 50_000_000, 2160, 3840, true);
1476        info.path = PathBuf::from("/tmp/IMG_3325.MOV");
1477        info.capture = CaptureMeta {
1478            created_utc: to_utc("2026-09-26T20:01:54+0300"),
1479            created_local: Some("2026-09-26T20:01:54+0300".into()),
1480            location: Some("+50.4160+030.2796+155.635/".into()),
1481            make: Some("Apple".into()),
1482            model: Some("iPhone 12 Pro Max".into()),
1483        };
1484        info
1485    }
1486
1487    #[test]
1488    fn metadata_is_kept_by_default_and_strippable() {
1489        let info = iphone_info();
1490        let plan = MediaEngine::new()
1491            .plan(&info, &ShrinkOpts::default())
1492            .unwrap();
1493        let a = joined(&plan, PassKind::Single);
1494        let at = a.iter().position(|x| x == "-map_metadata").unwrap();
1495        assert_eq!(a[at + 1], "0");
1496        // The capture tags are re-stated explicitly — the shooting date (not
1497        // the file's export time) in UTC, and location / make / model.
1498        for tag in [
1499            "creation_time=2026-09-26T17:01:54Z",
1500            "location=+50.4160+030.2796+155.635/",
1501            "make=Apple",
1502            "model=iPhone 12 Pro Max",
1503            "date=2026-09-26T20:01:54+0300",
1504        ] {
1505            assert!(a.contains(&tag.to_string()), "{tag} in {a:?}");
1506        }
1507        assert!(a.contains(&"+faststart".to_string()));
1508
1509        let strip = ShrinkOpts {
1510            keep_metadata: false,
1511            ..ShrinkOpts::default()
1512        };
1513        let plan = MediaEngine::new().plan(&info, &strip).unwrap();
1514        let a = joined(&plan, PassKind::Single);
1515        let at = a.iter().position(|x| x == "-map_metadata").unwrap();
1516        assert_eq!(a[at + 1], "-1");
1517        assert!(!a.iter().any(|x| x.starts_with("location=")));
1518        assert!(a.contains(&"+faststart".to_string()));
1519    }
1520
1521    #[test]
1522    fn apple_local_time_converts_to_utc() {
1523        let utc = |s: &str| to_utc(s);
1524        assert_eq!(
1525            utc("2026-09-26T20:01:54+0300").as_deref(),
1526            Some("2026-09-26T17:01:54Z")
1527        );
1528        assert_eq!(
1529            utc("2026-09-26T20:01:54+03:00").as_deref(),
1530            Some("2026-09-26T17:01:54Z")
1531        );
1532        assert_eq!(
1533            utc("2026-01-01T01:30:00+0300").as_deref(),
1534            Some("2025-12-31T22:30:00Z")
1535        );
1536        assert_eq!(
1537            utc("2026-03-01T23:00:00-0500").as_deref(),
1538            Some("2026-03-02T04:00:00Z")
1539        );
1540        assert_eq!(
1541            utc("2024-02-29T12:00:00.123Z").as_deref(),
1542            Some("2024-02-29T12:00:00Z")
1543        );
1544        assert_eq!(utc("yesterday"), None);
1545    }
1546
1547    #[test]
1548    fn an_iphone_mov_stays_mov_in_quality_mode_only() {
1549        let info = iphone_info();
1550        let out = |opts: &ShrinkOpts| {
1551            let plan = MediaEngine::new().plan(&info, opts).unwrap();
1552            plan.output.to_string_lossy().into_owned()
1553        };
1554        assert!(out(&ShrinkOpts::default()).ends_with(".shrink.mov"));
1555        // Platform presets / size targets are for sharing → MP4.
1556        assert!(out(&opts_target(8_000_000)).ends_with(".shrink.mp4"));
1557        // AV1 has no QuickTime mapping → MP4.
1558        let av1 = ShrinkOpts {
1559            video_codec: VideoCodec::Av1,
1560            ..ShrinkOpts::default()
1561        };
1562        assert!(out(&av1).ends_with(".shrink.mp4"));
1563        // Non-MOV sources are unaffected.
1564        let mp4 = video_info(60.0, 50_000_000, 1920, 1080, true);
1565        let p = MediaEngine::new()
1566            .plan(&mp4, &ShrinkOpts::default())
1567            .unwrap();
1568        assert!(p.output.to_string_lossy().ends_with(".shrink.mp4"));
1569    }
1570
1571    #[test]
1572    fn a_video_audio_track_is_never_upsampled() {
1573        let mut info = video_info(60.0, 50_000_000, 1920, 1080, true);
1574        info.audio_bitrate_bps = Some(64_000);
1575        let bps_of = |info: &MediaInfo, opts: &ShrinkOpts| {
1576            let plan = MediaEngine::new().plan(info, opts).unwrap();
1577            plan.spec.audio.unwrap().bitrate_bps
1578        };
1579        // Quality mode default is 128 kbps — capped at the source's 64 kbps.
1580        assert_eq!(bps_of(&info, &ShrinkOpts::default()), 64_000);
1581        // A size target too: never above the source (the rest goes to video).
1582        assert!(bps_of(&info, &opts_target(20_000_000)) <= 64_000);
1583        // An explicit `--audio 128k` is still honoured as asked.
1584        let explicit = ShrinkOpts {
1585            audio: AudioChoice::Bitrate(128_000),
1586            ..ShrinkOpts::default()
1587        };
1588        assert_eq!(bps_of(&info, &explicit), 128_000);
1589        // Unknown source rate → the default.
1590        info.audio_bitrate_bps = None;
1591        assert_eq!(
1592            bps_of(&info, &ShrinkOpts::default()),
1593            budget::DEFAULT_AUDIO_BPS
1594        );
1595    }
1596
1597    #[test]
1598    fn h265_adds_hvc1_tag() {
1599        let info = video_info(60.0, 100_000_000, 1280, 720, false);
1600        let opts = ShrinkOpts {
1601            video_codec: VideoCodec::H265,
1602            ..opts_target(8_000_000)
1603        };
1604        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1605        let args = build_pass_args(&plan, PassKind::Second, "/tmp/passlog", enc(&plan), false);
1606        let joined: Vec<String> = args
1607            .iter()
1608            .map(|a| a.to_string_lossy().into_owned())
1609            .collect();
1610        assert!(joined.contains(&"hvc1".to_string()));
1611        assert!(joined.contains(&"libx265".to_string()));
1612    }
1613}