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, PathBuf};
12
13use super::{
14    AudioSpec, CaptureMeta, EncodePlan, EncodeSpec, Engine, EngineError, Hdr, MediaInfo, Outcome,
15    ShrinkOpts, SizeGoal, VideoSpec,
16};
17use crate::budget;
18use crate::detect::{detect_kind, MediaKind};
19use crate::options::{AudioChoice, AudioCodec, FpsOpt, QualityPreset, ResolutionOpt, VideoCodec};
20
21/// Audio bitrate ladder (bits/s, descending) tried when keeping a track under
22/// a tight size budget.
23const AUDIO_LADDER: &[u64] = &[128_000, 96_000, 64_000, 48_000];
24
25/// Which pass of the encode a progress update belongs to.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum PassKind {
28    Single,
29    First,
30    Second,
31}
32
33/// The ffmpeg engine for video and audio.
34#[derive(Debug, Default, Clone)]
35pub struct MediaEngine {
36    /// Stops this engine's runs (see [`MediaEngine::with_cancel`]).
37    cancel: Option<deepshrink_ffmpeg::CancelToken>,
38}
39
40impl MediaEngine {
41    pub fn new() -> Self {
42        Self::default()
43    }
44
45    /// An engine whose `run` / `estimate` stop when `cancel` is set: the running
46    /// ffmpeg is killed, the partial output removed, and the call returns an
47    /// error for which [`EngineError::is_cancelled`] is true.
48    pub fn with_cancel(cancel: deepshrink_ffmpeg::CancelToken) -> Self {
49        Self {
50            cancel: Some(cancel),
51        }
52    }
53
54    /// The located ffmpeg / ffprobe, carrying this engine's cancel token.
55    fn tools(&self) -> Result<deepshrink_ffmpeg::Tools, EngineError> {
56        let tools = deepshrink_ffmpeg::locate()?;
57        Ok(match &self.cancel {
58            Some(c) => tools.with_cancel(c.clone()),
59            None => tools,
60        })
61    }
62
63    /// Like [`Engine::run`] but reports progress: `on_progress(pass, fraction)`
64    /// is called with `fraction` in 0.0..=1.0 as each pass proceeds.
65    pub fn run_with_progress(
66        &self,
67        plan: &EncodePlan,
68        on_progress: &mut dyn FnMut(PassKind, f64),
69    ) -> Result<Outcome, EngineError> {
70        let outcome = match self.run_inner(plan, on_progress) {
71            Ok(o) => o,
72            Err(e) => {
73                // A stopped encode leaves nothing behind: no half-written file,
74                // no two-pass log.
75                if e.is_cancelled() && plan.output != plan.input {
76                    let _ = fs::remove_file(&plan.output);
77                    cleanup_passlog(&passlog_base(plan));
78                }
79                return Err(e);
80            }
81        };
82        // Keep the source's modification time too, so the result sorts next to
83        // the original (Finder, Photos imports) instead of "today".
84        if plan.spec.keep_metadata {
85            copy_mtime(&plan.input, &outcome.output);
86        }
87        Ok(outcome)
88    }
89
90    fn run_inner(
91        &self,
92        plan: &EncodePlan,
93        on_progress: &mut dyn FnMut(PassKind, f64),
94    ) -> Result<Outcome, EngineError> {
95        let tools = self.tools()?;
96        let encoder = resolve_encoder(&tools, plan)?;
97        let zscale = wants_zscale(&tools, plan);
98
99        // VMAF-targeted quality search: applies to CRF-mode video only. Size /
100        // audio / passthrough encodes keep their existing single path.
101        if let Some(target_vmaf) = plan.target_vmaf {
102            if plan.spec.video.crf.is_some() && !plan.spec.audio_only && !plan.spec.passthrough {
103                return self.run_crf_search(
104                    &tools,
105                    plan,
106                    encoder,
107                    zscale,
108                    target_vmaf,
109                    on_progress,
110                );
111            }
112        }
113
114        // "Never make it bigger" in quality mode (sizes are guaranteed by the
115        // target path already): predict a CRF video from samples and skip the
116        // encode when it won't save at least `MIN_SAVING`; after any guarded
117        // encode, keep the original if the result doesn't after all.
118        let source = if plan.guard_larger && !plan.spec.passthrough {
119            fs::metadata(&plan.input).map(|m| m.len()).unwrap_or(0)
120        } else {
121            0
122        };
123        if source > 0
124            && plan.target_vmaf.is_none()
125            && !plan.spec.audio_only
126            && plan.spec.video.crf.is_some()
127        {
128            if let Some(predicted) = predict_crf_bytes(&tools, plan, encoder, zscale) {
129                if super::not_worth_it(predicted, source) {
130                    return self.keep_original(&tools, plan, on_progress);
131                }
132            }
133        }
134
135        // A size target is a ceiling, not a quota: when the quality preset's
136        // CRF comfortably fits, encode at it instead of filling the budget.
137        let ceiling = match ceiling_fit(&tools, plan, encoder, zscale) {
138            Some((ceiling, _)) => {
139                let o = self.run_plain(&tools, &ceiling, encoder, zscale, on_progress)?;
140                // Predictions are ±5%; a miss falls back to the budgeted encode.
141                plan.target_bytes
142                    .is_some_and(|t| o.final_bytes <= t)
143                    .then_some(o)
144            }
145            None => None,
146        };
147        let mut outcome = match ceiling {
148            Some(o) => o,
149            None => self.run_plain(&tools, plan, encoder, zscale, on_progress)?,
150        };
151        if source > 0 && super::not_worth_it(outcome.final_bytes, source) {
152            let _ = fs::remove_file(&outcome.output);
153            return self.keep_original(&tools, plan, on_progress);
154        }
155
156        // Size-targeted video with `--vmaf`: encode to budget, then report the
157        // VMAF actually achieved (best effort — a failed measurement is silent).
158        if plan.target_vmaf.is_some() && !plan.spec.audio_only && !plan.spec.passthrough {
159            outcome.vmaf = self.measure_output(&tools, plan, &plan.output);
160        }
161        Ok(outcome)
162    }
163
164    /// The plain encode: two-pass (with one correction retry) or single-pass,
165    /// no VMAF handling. Returns an [`Outcome`] with `vmaf = None`.
166    fn run_plain(
167        &self,
168        tools: &deepshrink_ffmpeg::Tools,
169        plan: &EncodePlan,
170        encoder: &str,
171        zscale: bool,
172        on_progress: &mut dyn FnMut(PassKind, f64),
173    ) -> Result<Outcome, EngineError> {
174        let passlog = passlog_base(plan);
175        let total = plan.source_duration_sec;
176
177        if plan.spec.passthrough {
178            return self.run_passthrough(tools, plan, on_progress);
179        }
180
181        if plan.spec.two_pass {
182            let args1 = build_pass_args(plan, PassKind::First, &passlog, encoder, zscale);
183            tools.run_pass(&args1, total, &mut |f| on_progress(PassKind::First, f))?;
184            let args2 = build_pass_args(plan, PassKind::Second, &passlog, encoder, zscale);
185            tools.run_pass(&args2, total, &mut |f| on_progress(PassKind::Second, f))?;
186        } else {
187            let args = build_pass_args(plan, PassKind::Single, &passlog, encoder, zscale);
188            tools.run_pass(&args, total, &mut |f| on_progress(PassKind::Single, f))?;
189        }
190
191        let mut size = fs::metadata(&plan.output)?.len();
192
193        // Correction retry: if the encode overshot the target (VBV slack),
194        // scale the video bitrate down proportionally and re-run the final
195        // pass. Two-pass needs one; Apple's one-pass encoder is looser, so it
196        // gets up to three.
197        if let (Some(target), Some(mut vbps)) = (plan.target_bytes, plan.spec.video.bitrate_bps) {
198            let (tries, pass) = if plan.spec.two_pass {
199                (1, PassKind::Second)
200            } else if plan.spec.video.hardware {
201                (3, PassKind::Single)
202            } else {
203                (0, PassKind::Single)
204            };
205            for _ in 0..tries {
206                if size <= target {
207                    break;
208                }
209                let corrected = (vbps as f64 * (target as f64 / size as f64) * 0.97) as u64;
210                if corrected < budget::ABSOLUTE_MIN_VIDEO_BPS {
211                    break;
212                }
213                vbps = corrected;
214                let mut retry = plan.clone();
215                retry.spec.video.bitrate_bps = Some(corrected);
216                let args = build_pass_args(&retry, pass, &passlog, encoder, zscale);
217                tools.run_pass(&args, total, &mut |f| on_progress(pass, f))?;
218                size = fs::metadata(&plan.output)?.len();
219            }
220        }
221
222        cleanup_passlog(&passlog);
223        Ok(Outcome {
224            output: plan.output.clone(),
225            final_bytes: size,
226            vmaf: None,
227            already_compact: false,
228        })
229    }
230
231    /// The expected output size of `plan`, without running it — the honest
232    /// preview for a UI. Size targets and audio come straight from the plan
233    /// (pure); a quality-mode (CRF) video is predicted from short sample
234    /// encodes, like the "never bigger" guard does (~2–3 s for any length).
235    /// Compare the result with the source: at or above it, a guarded run keeps
236    /// the original (`Outcome::already_compact`). `None` if it can't be told.
237    pub fn estimate(&self, plan: &EncodePlan) -> Result<Option<u64>, EngineError> {
238        if plan.spec.passthrough {
239            return Ok(fs::metadata(&plan.input).ok().map(|m| m.len()));
240        }
241        if ceiling_plan(plan).is_some() {
242            // A size target: the budget, or less when the quality CRF fits.
243            let tools = self.tools()?;
244            let encoder = resolve_encoder(&tools, plan)?;
245            let zscale = wants_zscale(&tools, plan);
246            let fit = ceiling_fit(&tools, plan, encoder, zscale).map(|(_, bytes)| bytes);
247            return Ok(fit.or(plan.expected_bytes));
248        }
249        if let Some(bytes) = plan.expected_bytes {
250            return Ok(Some(bytes));
251        }
252        if plan.spec.audio_only || plan.spec.video.crf.is_none() {
253            return Ok(None);
254        }
255        let tools = self.tools()?;
256        let encoder = resolve_encoder(&tools, plan)?;
257        let zscale = wants_zscale(&tools, plan);
258        Ok(predict_crf_bytes(&tools, plan, encoder, zscale))
259    }
260
261    /// The guard fired: deliver the source as-is (a byte copy, in its own
262    /// container/extension) instead of a re-encode that would not be smaller.
263    fn keep_original(
264        &self,
265        tools: &deepshrink_ffmpeg::Tools,
266        plan: &EncodePlan,
267        on_progress: &mut dyn FnMut(PassKind, f64),
268    ) -> Result<Outcome, EngineError> {
269        let _ = tools; // no ffmpeg needed: the source is delivered byte-for-byte
270        let output = match plan.input.extension() {
271            Some(ext) => plan.output.with_extension(ext),
272            None => plan.output.clone(),
273        };
274        // A plain copy, not a remux: "kept as-is" must mean identical bytes (a
275        // +faststart remux came out a few KB larger than the source).
276        fs::copy(&plan.input, &output)?;
277        on_progress(PassKind::Single, 1.0);
278        Ok(Outcome {
279            final_bytes: fs::metadata(&output)?.len(),
280            output,
281            vmaf: None,
282            already_compact: true,
283        })
284    }
285
286    /// Passthrough: the source already fits, so its streams are copied as-is.
287    ///
288    /// A stream copy is normally the cheapest and safest path, but it is not
289    /// infallible — some codecs simply cannot be muxed by the container's muxer
290    /// (ffmpeg needs a parser it may not have). Since nothing is being
291    /// re-encoded here, a failed remux falls back to copying the file verbatim:
292    /// the promise of this branch is "you get your file, unchanged and within
293    /// target", and that must hold for every input.
294    fn run_passthrough(
295        &self,
296        tools: &deepshrink_ffmpeg::Tools,
297        plan: &EncodePlan,
298        on_progress: &mut dyn FnMut(PassKind, f64),
299    ) -> Result<Outcome, EngineError> {
300        // Stream copy — the video encoder is never reached.
301        let args = build_pass_args(plan, PassKind::Single, "", "copy", false);
302        let remuxed = tools.run_pass(&args, plan.source_duration_sec, &mut |f| {
303            on_progress(PassKind::Single, f)
304        });
305        if remuxed.is_err() {
306            fs::copy(&plan.input, &plan.output)?;
307            on_progress(PassKind::Single, 1.0);
308        }
309        let size = fs::metadata(&plan.output)?.len();
310        Ok(Outcome {
311            output: plan.output.clone(),
312            final_bytes: size,
313            vmaf: None,
314            already_compact: true,
315        })
316    }
317
318    /// Search CRF for the smallest output that still meets `target_vmaf`.
319    ///
320    /// Each trial is a single-pass CRF encode into `plan.output` followed by a
321    /// VMAF measurement against the source. Drives [`budget::search_crf`], so
322    /// the search algorithm itself is unit-tested separately. Falls back to a
323    /// plain encode if the source resolution is unknown (nothing to measure).
324    fn run_crf_search(
325        &self,
326        tools: &deepshrink_ffmpeg::Tools,
327        plan: &EncodePlan,
328        encoder: &str,
329        zscale: bool,
330        target_vmaf: f64,
331        on_progress: &mut dyn FnMut(PassKind, f64),
332    ) -> Result<Outcome, EngineError> {
333        let (ref_w, ref_h) = match (plan.source_width, plan.source_height) {
334            (Some(w), Some(h)) => (w, h),
335            _ => return self.run_plain(tools, plan, encoder, zscale, on_progress),
336        };
337        let ref_fps = plan.source_fps.unwrap_or(0.0);
338        let total = plan.source_duration_sec;
339        let (lo, hi) = plan.spec.video.codec.crf_search_bounds();
340        let n_threads = thread_count();
341
342        let mut err: Option<EngineError> = None;
343        let mut last_crf: Option<u8> = None;
344
345        let (chosen_crf, chosen_vmaf) = budget::search_crf(target_vmaf, lo, hi, |crf| {
346            if err.is_some() {
347                return f64::NEG_INFINITY;
348            }
349            match encode_at_crf(tools, plan, encoder, zscale, crf, total, on_progress).and_then(
350                |()| {
351                    last_crf = Some(crf);
352                    deepshrink_ffmpeg::measure_vmaf(
353                        &tools.ffmpeg,
354                        &plan.output,
355                        &plan.input,
356                        ref_w,
357                        ref_h,
358                        ref_fps,
359                        n_threads,
360                    )
361                    .map_err(EngineError::from)
362                },
363            ) {
364                Ok(v) => v,
365                Err(e) => {
366                    err = Some(e);
367                    f64::NEG_INFINITY
368                }
369            }
370        });
371        if let Some(e) = err {
372            return Err(e);
373        }
374
375        // Leave the chosen CRF on disk (the search may have ended elsewhere).
376        if last_crf != Some(chosen_crf) {
377            encode_at_crf(tools, plan, encoder, zscale, chosen_crf, total, on_progress)?;
378        }
379        let size = fs::metadata(&plan.output)?.len();
380        Ok(Outcome {
381            output: plan.output.clone(),
382            final_bytes: size,
383            vmaf: Some(chosen_vmaf),
384            already_compact: false,
385        })
386    }
387
388    /// Measure the VMAF of an encoded `output` against the plan's source.
389    /// Returns `None` on any failure or when the source dimensions are unknown.
390    fn measure_output(
391        &self,
392        tools: &deepshrink_ffmpeg::Tools,
393        plan: &EncodePlan,
394        output: &Path,
395    ) -> Option<f64> {
396        let (w, h) = (plan.source_width?, plan.source_height?);
397        let fps = plan.source_fps.unwrap_or(0.0);
398        deepshrink_ffmpeg::measure_vmaf(
399            &tools.ffmpeg,
400            output,
401            &plan.input,
402            w,
403            h,
404            fps,
405            thread_count(),
406        )
407        .ok()
408    }
409
410    /// Plan a pure-audio encode (single pass, codec + fitted bitrate).
411    fn plan_audio(&self, info: &MediaInfo, opts: &ShrinkOpts) -> Result<EncodePlan, EngineError> {
412        let duration = info.duration_sec;
413        if !duration.is_finite() || duration <= 0.0 {
414            return Err(EngineError::Unsupported(format!(
415                "could not determine duration of {}",
416                info.path.display()
417            )));
418        }
419        let codec = opts.audio_codec;
420        let target = target_bytes(&opts.goal, info.size_bytes);
421
422        // "Never make it bigger": stream-copy remux when the source already fits.
423        if let Some(tb) = target {
424            if info.size_bytes > 0 && info.size_bytes <= tb {
425                let src_ext = info
426                    .path
427                    .extension()
428                    .and_then(|e| e.to_str())
429                    .unwrap_or("audio");
430                let output = opts
431                    .output
432                    .clone()
433                    .unwrap_or_else(|| output_with_ext(&info.path, src_ext));
434                return Ok(passthrough_plan(
435                    info,
436                    output,
437                    tb,
438                    false,
439                    opts.keep_metadata,
440                ));
441            }
442        }
443
444        // Mono for speech: explicit flag, or a single-channel source.
445        let mono = opts.mono || info.audio_channels == Some(1);
446
447        let (bitrate_bps, expected_bytes) = match target {
448            Some(tb) => {
449                let raw = budget::audio_bitrate_bps(tb, duration).ok_or(EngineError::Infeasible)?;
450                if raw < budget::ABSOLUTE_MIN_AUDIO_BPS {
451                    return Err(EngineError::Infeasible);
452                }
453                let bps = budget::snap_audio_bitrate(raw);
454                let predicted = (bps as f64 * duration / 8.0 * (1.0 + budget::CONTAINER_OVERHEAD))
455                    .round() as u64;
456                (bps, Some(predicted))
457            }
458            None => {
459                // Quality mode: per tier, codec and channel count.
460                let bps = quality_audio_bps(opts.quality, codec, mono);
461                // Never re-encode lossy audio at (nearly) its own bitrate or
462                // above: that is only generation loss, often a bigger file (a
463                // 64 kbps MP3 audiobook → 160 kbps AAC doubled it). Keep it.
464                if !opts.allow_larger && already_compact_audio(bps, info) {
465                    let src_ext = info
466                        .path
467                        .extension()
468                        .and_then(|e| e.to_str())
469                        .unwrap_or("audio");
470                    let output = opts
471                        .output
472                        .clone()
473                        .unwrap_or_else(|| output_with_ext(&info.path, src_ext));
474                    let mut plan =
475                        passthrough_plan(info, output, info.size_bytes, false, opts.keep_metadata);
476                    plan.summary =
477                        "stream copy (already compact — a re-encode would not be smaller)".into();
478                    return Ok(plan);
479                }
480                // Constant-bitrate estimate (VBR lands close enough for a preview).
481                let predicted = (bps as f64 * duration / 8.0 * (1.0 + budget::CONTAINER_OVERHEAD))
482                    .round() as u64;
483                (bps, Some(predicted))
484            }
485        };
486
487        let audio = AudioSpec {
488            codec,
489            bitrate_bps,
490            mono,
491            sample_rate: opts.sample_rate,
492            vbr: opts.vbr,
493        };
494        let output = opts
495            .output
496            .clone()
497            .unwrap_or_else(|| output_with_ext(&info.path, codec.extension()));
498        let summary = build_audio_summary(&audio, info.audio_channels);
499
500        Ok(EncodePlan {
501            input: info.path.clone(),
502            output,
503            summary,
504            expected_bytes,
505            target_bytes: target,
506            target_vmaf: None,
507            source_duration_sec: duration,
508            source_width: info.width,
509            source_height: info.height,
510            source_fps: info.fps,
511            spec: EncodeSpec {
512                video: placeholder_video_spec(),
513                audio: Some(audio),
514                faststart: false,
515                two_pass: false,
516                passthrough: false,
517                audio_only: true,
518                dpi: None,
519                keep_metadata: opts.keep_metadata,
520                tags: capture_tags(info, opts.keep_metadata),
521            },
522            // A size target is its own guarantee; quality mode gets the guard.
523            guard_larger: target.is_none() && !opts.allow_larger,
524            ceiling_crf: None,
525        })
526    }
527}
528
529impl Engine for MediaEngine {
530    fn supports(&self, input: &Path) -> bool {
531        matches!(detect_kind(input), MediaKind::Video | MediaKind::Audio)
532    }
533
534    fn probe(&self, input: &Path) -> Result<MediaInfo, EngineError> {
535        let tools = deepshrink_ffmpeg::locate()?;
536        let p = deepshrink_ffmpeg::probe(&tools.ffprobe, input)?;
537
538        let video = p.video_stream();
539        let audio = p.audio_stream();
540        // Prefer ffprobe's reported size; fall back to the filesystem.
541        let size_bytes = p
542            .size_bytes()
543            .or_else(|| fs::metadata(input).ok().map(|m| m.len()))
544            .unwrap_or(0);
545
546        Ok(MediaInfo {
547            path: input.to_path_buf(),
548            kind: detect_kind(input),
549            duration_sec: p.duration_sec().unwrap_or(0.0),
550            size_bytes,
551            width: video.and_then(|v| v.width),
552            height: video.and_then(|v| v.height),
553            fps: p.fps(),
554            video_codec: video.and_then(|v| v.codec_name.clone()),
555            audio_codec: audio.and_then(|a| a.codec_name.clone()),
556            audio_channels: audio.and_then(|a| a.channels),
557            audio_bitrate_bps: p.audio_bitrate_bps(),
558            capture: capture_meta(&p),
559            hdr: video
560                .and_then(|v| v.color_transfer.as_deref())
561                .and_then(Hdr::from_transfer),
562        })
563    }
564
565    fn plan(&self, info: &MediaInfo, opts: &ShrinkOpts) -> Result<EncodePlan, EngineError> {
566        match info.kind {
567            MediaKind::Audio => return self.plan_audio(info, opts),
568            MediaKind::Unsupported => {
569                return Err(EngineError::Unsupported(format!(
570                    "{} is not a supported media file",
571                    info.path.display()
572                )))
573            }
574            MediaKind::Video => {}
575        }
576        let duration = info.duration_sec;
577        if !duration.is_finite() || duration <= 0.0 {
578            return Err(EngineError::Unsupported(format!(
579                "could not determine duration of {}",
580                info.path.display()
581            )));
582        }
583        let src_height = info.height.unwrap_or(0);
584
585        let target = target_bytes(&opts.goal, info.size_bytes);
586        let output = opts
587            .output
588            .clone()
589            .unwrap_or_else(|| output_with_ext(&info.path, video_container(info, target, opts)));
590
591        // "Never make it bigger": if the source already fits the target, just
592        // remux (stream copy) instead of re-encoding it up to the target. The
593        // copy stays in the *source* container — an .mp4 cannot hold every codec
594        // a source may carry (an AMR-NB track from a .3gp, say), and a stream
595        // copy must not be the thing that breaks a file we aren't even re-encoding.
596        if let Some(tb) = target {
597            if info.size_bytes > 0 && info.size_bytes <= tb {
598                let src_ext = info
599                    .path
600                    .extension()
601                    .and_then(|e| e.to_str())
602                    .unwrap_or("mp4");
603                let output = opts
604                    .output
605                    .clone()
606                    .unwrap_or_else(|| output_with_ext(&info.path, src_ext));
607                return Ok(passthrough_plan(info, output, tb, true, opts.keep_metadata));
608            }
609        }
610
611        let audio = decide_audio(
612            opts,
613            info.has_audio(),
614            info.audio_bitrate_bps,
615            target,
616            duration,
617        )?;
618        let audio_bps = audio.as_ref().map(|a| a.bitrate_bps).unwrap_or(0);
619
620        // Apple's hardware encoder, when asked for and present. Not for a VMAF
621        // search (its CRF bounds are the software encoder's).
622        let hw_quality = opts
623            .quality
624            .default_hw_quality(opts.video_codec)
625            .filter(|_| {
626                opts.hardware && opts.target_vmaf.is_none() && hardware_encoding_available()
627            });
628        let hardware = hw_quality.is_some();
629        // The quality value for this encoder: CRF, or VideoToolbox's `-q:v`.
630        let quality_value =
631            hw_quality.unwrap_or_else(|| opts.quality.default_crf(opts.video_codec));
632
633        let (video, expected_bytes) = if let Some(tb) = target {
634            let vbps = budget::video_bitrate_bps(tb, duration, audio_bps)
635                .filter(|&b| b >= budget::ABSOLUTE_MIN_VIDEO_BPS)
636                .ok_or(EngineError::Infeasible)?;
637            let height = pick_height(opts.resolution, src_height, vbps);
638            let predicted = ((vbps + audio_bps) as f64 * duration / 8.0
639                * (1.0 + budget::CONTAINER_OVERHEAD))
640                .round() as u64;
641            (
642                VideoSpec {
643                    codec: opts.video_codec,
644                    bitrate_bps: Some(vbps),
645                    crf: None,
646                    height,
647                    fps: pick_fps(opts.fps, info.fps),
648                    preset: opts.quality,
649                    // A size target is for sending: make it play everywhere.
650                    to_sdr: info.hdr,
651                    hardware,
652                },
653                Some(predicted),
654            )
655        } else {
656            // Quality mode: CRF, no hard size guarantee. The CRF default is
657            // codec-aware; a `--vmaf` target refines it via a search in `run`.
658            let crf = quality_value;
659            let height = match opts.resolution {
660                ResolutionOpt::Height(h) => clamp_height(h, src_height),
661                ResolutionOpt::Auto => None,
662            };
663            (
664                VideoSpec {
665                    codec: opts.video_codec,
666                    bitrate_bps: None,
667                    crf: Some(crf),
668                    height,
669                    fps: pick_fps(opts.fps, info.fps),
670                    preset: opts.quality,
671                    // Quality mode keeps HDR (and 10-bit) as shot — except
672                    // Apple's H.264, which is 8-bit only: SDR it is.
673                    to_sdr: info
674                        .hdr
675                        .filter(|_| hardware && opts.video_codec == VideoCodec::H264),
676                    hardware,
677                },
678                None,
679            )
680        };
681
682        // Two-pass is how a bitrate budget is actually hit; the caller can force
683        // it off (faster, looser) but can't force it on in CRF mode, where there
684        // is no budget for a first pass to measure.
685        // Apple's encoder has no two-pass: it hits a budget in one (with the
686        // overshoot retry in `run`).
687        let two_pass = video.bitrate_bps.is_some() && opts.two_pass.unwrap_or(true) && !hardware;
688        let summary = build_summary(&video, audio.as_ref(), two_pass);
689
690        Ok(EncodePlan {
691            input: info.path.clone(),
692            output,
693            summary,
694            expected_bytes,
695            target_bytes: target,
696            target_vmaf: opts.target_vmaf,
697            source_duration_sec: duration,
698            source_width: info.width,
699            source_height: info.height,
700            source_fps: info.fps,
701            spec: EncodeSpec {
702                video,
703                audio,
704                faststart: true,
705                two_pass,
706                passthrough: false,
707                audio_only: false,
708                dpi: None,
709                keep_metadata: opts.keep_metadata,
710                tags: capture_tags(info, opts.keep_metadata),
711            },
712            // A size target is its own guarantee; quality mode gets the guard.
713            guard_larger: target.is_none() && !opts.allow_larger,
714            ceiling_crf: target.map(|_| quality_value),
715        })
716    }
717
718    fn run(&self, plan: &EncodePlan) -> Result<Outcome, EngineError> {
719        self.run_with_progress(plan, &mut |_, _| {})
720    }
721}
722
723/// A placeholder video spec — ignored while `passthrough`/`audio_only` is set.
724fn placeholder_video_spec() -> VideoSpec {
725    VideoSpec {
726        codec: crate::options::VideoCodec::H264,
727        bitrate_bps: None,
728        crf: None,
729        height: None,
730        fps: None,
731        preset: crate::options::QualityPreset::Balanced,
732        to_sdr: None,
733        hardware: false,
734    }
735}
736
737/// Whether this Mac can encode with Apple's hardware (VideoToolbox) with a
738/// constant-quality target: Apple Silicon and an ffmpeg with the encoders.
739/// Asked once per process (it spawns `ffmpeg -encoders`).
740pub fn hardware_encoding_available() -> bool {
741    static AVAILABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
742    *AVAILABLE.get_or_init(|| {
743        // VideoToolbox's constant quality (`-q:v`) is Apple Silicon only.
744        cfg!(all(target_os = "macos", target_arch = "aarch64"))
745            && deepshrink_ffmpeg::locate().is_ok_and(|t| {
746                deepshrink_ffmpeg::has_encoder(&t.ffmpeg, "h264_videotoolbox")
747                    && deepshrink_ffmpeg::has_encoder(&t.ffmpeg, "hevc_videotoolbox")
748            })
749    })
750}
751
752/// A stream-copy remux plan for when the source already fits the target.
753/// `faststart` is only meaningful for MP4/MOV; pass `false` for pure audio.
754fn passthrough_plan(
755    info: &MediaInfo,
756    output: PathBuf,
757    target: u64,
758    faststart: bool,
759    keep_metadata: bool,
760) -> EncodePlan {
761    EncodePlan {
762        input: info.path.clone(),
763        output,
764        summary: "stream copy (already within target)".to_string(),
765        expected_bytes: Some(info.size_bytes),
766        target_bytes: Some(target),
767        target_vmaf: None,
768        source_duration_sec: info.duration_sec,
769        source_width: info.width,
770        source_height: info.height,
771        source_fps: info.fps,
772        spec: EncodeSpec {
773            video: placeholder_video_spec(),
774            audio: None,
775            faststart,
776            two_pass: false,
777            passthrough: true,
778            audio_only: false,
779            dpi: None,
780            keep_metadata,
781            tags: capture_tags(info, keep_metadata),
782        },
783        guard_larger: false,
784        ceiling_crf: None,
785    }
786}
787
788/// Quality-mode audio bitrate by tier, codec and channel count (mono = half).
789/// Opus needs the least for the same quality, MP3 the most.
790fn quality_audio_bps(quality: QualityPreset, codec: AudioCodec, mono: bool) -> u64 {
791    let stereo = match (codec, quality) {
792        (AudioCodec::Opus, QualityPreset::Fast) => 64_000,
793        (AudioCodec::Opus, QualityPreset::Balanced) => 96_000,
794        (AudioCodec::Opus, QualityPreset::Max) => 128_000,
795        (AudioCodec::Mp3, QualityPreset::Fast) => 128_000,
796        (AudioCodec::Mp3, QualityPreset::Balanced) => 160_000,
797        (AudioCodec::Mp3, QualityPreset::Max) => 256_000,
798        (AudioCodec::Aac, QualityPreset::Fast) => 96_000,
799        (AudioCodec::Aac, QualityPreset::Balanced) => 128_000,
800        (AudioCodec::Aac, QualityPreset::Max) => 192_000,
801    };
802    if mono {
803        stereo / 2
804    } else {
805        stereo
806    }
807}
808
809/// A pure-audio source whose own bitrate is at or under ~110% of what we'd
810/// encode at: a re-encode can't meaningfully shrink it. The source rate comes
811/// from size / duration (embedded cover art only raises it — the safe side).
812fn already_compact_audio(bps: u64, info: &MediaInfo) -> bool {
813    if info.duration_sec <= 0.0 || info.size_bytes == 0 {
814        return false;
815    }
816    let source_bps = info.size_bytes as f64 * 8.0 / info.duration_sec;
817    bps as f64 >= source_bps * 0.9
818}
819
820/// Best-effort: give `output` the modification time of `input`.
821fn copy_mtime(input: &Path, output: &Path) {
822    let Ok(mtime) = fs::metadata(input).and_then(|m| m.modified()) else {
823        return;
824    };
825    if let Ok(f) = fs::File::options().write(true).open(output) {
826        let _ = f.set_modified(mtime);
827    }
828}
829
830/// Output container for a video. A QuickTime source (an iPhone `.MOV`) stays
831/// QuickTime in quality mode: only a MOV carries its location / camera tags in
832/// a form Apple's apps read (the MP4 muxer drops them). Size targets and
833/// platform presets get MP4 — the most compatible for sharing. AV1 is always
834/// MP4 (QuickTime has no AV1 mapping).
835fn video_container(info: &MediaInfo, target: Option<u64>, opts: &ShrinkOpts) -> &'static str {
836    let mov_source = info
837        .path
838        .extension()
839        .and_then(|e| e.to_str())
840        .is_some_and(|e| e.eq_ignore_ascii_case("mov"));
841    if mov_source && target.is_none() && opts.video_codec != VideoCodec::Av1 {
842        "mov"
843    } else {
844        "mp4"
845    }
846}
847
848/// Read the capture metadata from the probe's container tags.
849fn capture_meta(p: &deepshrink_ffmpeg::Ffprobe) -> CaptureMeta {
850    let tag = |keys: &[&str]| {
851        keys.iter()
852            .find_map(|k| p.format_tag(k))
853            .map(str::to_string)
854    };
855    let created_local = tag(&["com.apple.quicktime.creationdate"]);
856    let created_utc = created_local
857        .as_deref()
858        .and_then(to_utc)
859        .or_else(|| tag(&["creation_time"]));
860    CaptureMeta {
861        created_utc,
862        created_local,
863        location: tag(&["com.apple.quicktime.location.ISO6709", "location"]),
864        make: tag(&["com.apple.quicktime.make", "make"]),
865        model: tag(&["com.apple.quicktime.model", "model"]),
866    }
867}
868
869/// The explicit output tags for `info`'s capture metadata (empty when
870/// metadata is stripped).
871fn capture_tags(info: &MediaInfo, keep: bool) -> Vec<(String, String)> {
872    if !keep {
873        return Vec::new();
874    }
875    let c = &info.capture;
876    [
877        ("creation_time", c.created_utc.as_ref()),
878        ("date", c.created_local.as_ref()),
879        ("location", c.location.as_ref()),
880        ("make", c.make.as_ref()),
881        ("model", c.model.as_ref()),
882    ]
883    .into_iter()
884    .filter_map(|(k, v)| v.map(|v| (k.to_string(), v.clone())))
885    .collect()
886}
887
888/// `2026-09-26T20:01:54+0300` (also `+03:00`, `Z`, fractional seconds) →
889/// `2026-09-26T17:01:54Z`. `None` if it doesn't parse.
890fn to_utc(s: &str) -> Option<String> {
891    let s = s.trim();
892    let num = |a: usize, b: usize| s.get(a..b)?.parse::<i64>().ok();
893    let (y, mo, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?);
894    let (h, mi, se) = (num(11, 13)?, num(14, 16)?, num(17, 19)?);
895    if s.get(4..5)? != "-" || s.get(10..11).map(|c| c == "T" || c == " ") != Some(true) {
896        return None;
897    }
898    // Offset: skip any fraction, then Z / ±HH[:]MM.
899    let rest = s
900        .get(19..)?
901        .trim_start_matches(|c: char| c == '.' || c.is_ascii_digit());
902    let offset_min = match rest {
903        "" | "Z" | "z" => 0,
904        r if r.starts_with('+') || r.starts_with('-') => {
905            let digits: String = r[1..].chars().filter(char::is_ascii_digit).collect();
906            let (oh, om) = (
907                digits.get(0..2)?.parse::<i64>().ok()?,
908                digits.get(2..4).unwrap_or("00").parse::<i64>().ok()?,
909            );
910            let m = oh * 60 + om;
911            if r.starts_with('-') {
912                -m
913            } else {
914                m
915            }
916        }
917        _ => return None,
918    };
919    let secs = days_from_civil(y, mo, d) * 86_400 + h * 3600 + mi * 60 + se - offset_min * 60;
920    let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
921    let (y, mo, d) = civil_from_days(days);
922    Some(format!(
923        "{y:04}-{mo:02}-{d:02}T{:02}:{:02}:{:02}Z",
924        rem / 3600,
925        rem % 3600 / 60,
926        rem % 60
927    ))
928}
929
930/// Days since 1970-01-01 for a proleptic Gregorian date (H. Hinnant).
931fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
932    let y = if m <= 2 { y - 1 } else { y };
933    let era = y.div_euclid(400);
934    let yoe = y - era * 400;
935    let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + d - 1;
936    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
937    era * 146_097 + doe - 719_468
938}
939
940/// Inverse of [`days_from_civil`].
941fn civil_from_days(z: i64) -> (i64, i64, i64) {
942    let z = z + 719_468;
943    let era = z.div_euclid(146_097);
944    let doe = z - era * 146_097;
945    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
946    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
947    let mp = (5 * doy + 2) / 153;
948    let d = doy - (153 * mp + 2) / 5 + 1;
949    let m = if mp < 10 { mp + 3 } else { mp - 9 };
950    (yoe + era * 400 + i64::from(m <= 2), m, d)
951}
952
953/// Metadata flags for the output. Keep = map the source's global metadata,
954/// then re-state the capture tags explicitly (`-metadata k=v`): ffmpeg's own
955/// copy of an iPhone's `com.apple.quicktime.*` keys (`use_metadata_tags`) is
956/// not readable by Apple's frameworks, whereas `location` / `make` / `model` /
957/// `date` land in QuickTime user data (©xyz, ©mak, …) that Photos and Finder
958/// read, and `creation_time` sets the movie header. Strip = drop it all.
959fn metadata_args(plan: &EncodePlan) -> (Vec<OsString>, Option<&'static str>) {
960    if !plan.spec.keep_metadata {
961        return (vec!["-map_metadata".into(), "-1".into()], None);
962    }
963    let mut a: Vec<OsString> = vec!["-map_metadata".into(), "0".into()];
964    for (k, v) in &plan.spec.tags {
965        a.push("-metadata".into());
966        a.push(format!("{k}={v}").into());
967    }
968    (a, None)
969}
970
971/// `-movflags` value combining faststart and metadata tags (None = no flag).
972fn movflags(faststart: bool, meta: Option<&'static str>) -> Option<String> {
973    let mut v = String::new();
974    if faststart {
975        v.push_str("+faststart");
976    }
977    if let Some(m) = meta {
978        v.push_str(m);
979    }
980    (!v.is_empty()).then_some(v)
981}
982
983/// How far under the target a predicted CRF encode must land to be used
984/// instead of the budget (predictions are within ~5%).
985const CEILING_MARGIN: f64 = 0.9;
986
987/// A size-target plan re-cast as a single-pass CRF encode at the quality
988/// preset's CRF ([`EncodePlan::ceiling_crf`]). `None` for anything else.
989fn ceiling_plan(plan: &EncodePlan) -> Option<EncodePlan> {
990    let crf = plan.ceiling_crf?;
991    if plan.target_bytes.is_none()
992        || plan.spec.passthrough
993        || plan.spec.audio_only
994        || plan.spec.video.bitrate_bps.is_none()
995    {
996        return None;
997    }
998    let mut c = plan.clone();
999    c.spec.video.bitrate_bps = None;
1000    c.spec.video.crf = Some(crf);
1001    c.spec.two_pass = false;
1002    c.summary = build_summary(&c.spec.video, c.spec.audio.as_ref(), false);
1003    Some(c)
1004}
1005
1006/// [`ceiling_plan`] and its predicted size, if sample encodes say it lands
1007/// comfortably under the target (the same ~2–3 s of samples as the
1008/// quality-mode preview).
1009fn ceiling_fit(
1010    tools: &deepshrink_ffmpeg::Tools,
1011    plan: &EncodePlan,
1012    encoder: &str,
1013    zscale: bool,
1014) -> Option<(EncodePlan, u64)> {
1015    let target = plan.target_bytes?;
1016    let ceiling = ceiling_plan(plan)?;
1017    let predicted = predict_crf_bytes(tools, &ceiling, encoder, zscale)?;
1018    ((predicted as f64) < target as f64 * CEILING_MARGIN).then_some((ceiling, predicted))
1019}
1020
1021/// Whether to tone-map with `zscale` — asked of ffmpeg only for a PQ source.
1022fn wants_zscale(tools: &deepshrink_ffmpeg::Tools, plan: &EncodePlan) -> bool {
1023    plan.spec.video.to_sdr == Some(Hdr::Pq)
1024        && deepshrink_ffmpeg::has_filter(&tools.ffmpeg, "zscale")
1025}
1026
1027/// Sample windows for [`predict_crf_bytes`]: three 3-second clips at 20/50/80%.
1028const SAMPLE_SECS: f64 = 3.0;
1029/// The shortest window for heavy video (4K, 60 fps): measured on a 60 s 4K60
1030/// iPhone clip, 1.5 s windows predicted as well as 3 s (+3.3 % vs +3.8 %) in
1031/// half the time; 1 s drifted to +7 %.
1032const MIN_SAMPLE_SECS: f64 = 1.5;
1033
1034/// Sample window length: 3 s up to 1080p30, shorter as the pixel rate grows
1035/// (4K60 → 1.5 s), so a preview of heavy video doesn't take a minute.
1036fn sample_secs(plan: &EncodePlan) -> f64 {
1037    const REFERENCE: f64 = 1920.0 * 1080.0 * 30.0;
1038    let (w, h) = match (plan.source_width, plan.source_height) {
1039        (Some(w), Some(h)) if w > 0 && h > 0 => (w as f64, h as f64),
1040        _ => return SAMPLE_SECS,
1041    };
1042    let fps = plan
1043        .source_fps
1044        .filter(|f| f.is_finite() && *f > 0.0)
1045        .unwrap_or(30.0);
1046    (SAMPLE_SECS * REFERENCE / (w * h * fps)).clamp(MIN_SAMPLE_SECS, SAMPLE_SECS)
1047}
1048/// Each sample starts on a keyframe, so samples over-predict by ~8–10% (a
1049/// 30 s phone clip: 20.4 MB predicted vs 18.7 MB real) — scale that back.
1050const SAMPLE_BIAS: f64 = 0.92;
1051
1052/// Predict a CRF video encode's final size from short sample encodes (same
1053/// encoder, CRF, preset, scaling, fps; audio at the planned bitrate): three
1054/// 3 s windows, or the whole clip when it's under 12 s. `None` if a sample fails.
1055fn predict_crf_bytes(
1056    tools: &deepshrink_ffmpeg::Tools,
1057    plan: &EncodePlan,
1058    encoder: &str,
1059    zscale: bool,
1060) -> Option<u64> {
1061    let duration = plan.source_duration_sec;
1062    if !duration.is_finite() || duration <= 0.0 {
1063        return None;
1064    }
1065    // Long clips: three 3 s windows. Short ones (< 12 s): the whole clip once —
1066    // exact, and still cheap — so no keyframe bias to correct either.
1067    let win = sample_secs(plan);
1068    let (windows, bias): (Vec<(f64, f64)>, f64) = if duration >= win * 4.0 {
1069        (
1070            [0.2, 0.5, 0.8]
1071                .iter()
1072                .map(|at| ((duration * at - win / 2.0).max(0.0), win))
1073                .collect(),
1074            SAMPLE_BIAS,
1075        )
1076    } else {
1077        (vec![(0.0, duration)], 1.0)
1078    };
1079    let mut sample = plan.clone();
1080    sample.spec.audio = None;
1081    sample.spec.faststart = false;
1082    let mut video_bytes = 0u64;
1083    let mut sampled = 0.0;
1084    for (i, &(start, len)) in windows.iter().enumerate() {
1085        sample.output =
1086            std::env::temp_dir().join(format!("deepshrink-sample-{}-{i}.mp4", std::process::id()));
1087        let mut args = build_pass_args(&sample, PassKind::Single, "", encoder, zscale);
1088        let at_input = args.iter().position(|a| a == "-i")?;
1089        args.splice(
1090            at_input..at_input,
1091            [
1092                OsString::from("-ss"),
1093                OsString::from(format!("{start:.2}")),
1094                OsString::from("-t"),
1095                OsString::from(format!("{len:.2}")),
1096            ],
1097        );
1098        let ran = tools.run_pass(&args, len, &mut |_| {});
1099        let bytes = fs::metadata(&sample.output).map(|m| m.len()).ok();
1100        let _ = fs::remove_file(&sample.output);
1101        video_bytes += bytes.filter(|_| ran.is_ok())?;
1102        sampled += len;
1103    }
1104    let video_bps = video_bytes as f64 * 8.0 / sampled * bias;
1105    let audio_bps = plan.spec.audio.as_ref().map(|a| a.bitrate_bps).unwrap_or(0) as f64;
1106    Some(((video_bps + audio_bps) * duration / 8.0 * (1.0 + budget::CONTAINER_OVERHEAD)) as u64)
1107}
1108
1109/// Human-readable summary for a pure-audio plan, e.g.
1110/// "Opus · 22 kbps · mono (speech)".
1111fn build_audio_summary(audio: &AudioSpec, src_channels: Option<u32>) -> String {
1112    let mut parts = vec![
1113        audio.codec.label().to_string(),
1114        format!("{} kbps", audio.bitrate_bps / 1000),
1115    ];
1116    if audio.mono {
1117        // A single-channel source (or --mono) reads as speech.
1118        let note = if src_channels == Some(1) {
1119            "mono"
1120        } else {
1121            "mono (downmix)"
1122        };
1123        parts.push(note.to_string());
1124    }
1125    if let Some(sr) = audio.sample_rate {
1126        parts.push(format!("{} Hz", sr));
1127    }
1128    parts.join(" · ")
1129}
1130
1131/// Resolve the absolute target size (bytes) for a goal, if it imposes one.
1132fn target_bytes(goal: &SizeGoal, original: u64) -> Option<u64> {
1133    match goal {
1134        SizeGoal::Target(b) => Some(*b),
1135        SizeGoal::Reduce(f) => Some(budget::reduce_target_bytes(original, *f)),
1136        SizeGoal::Preset(p) => p.limit_bytes,
1137        SizeGoal::Quality => None,
1138    }
1139}
1140
1141/// Decide the audio track for a video encode.
1142fn decide_audio(
1143    opts: &ShrinkOpts,
1144    has_audio: bool,
1145    source_bps: Option<u64>,
1146    target: Option<u64>,
1147    duration: f64,
1148) -> Result<Option<AudioSpec>, EngineError> {
1149    if !has_audio {
1150        return Ok(None);
1151    }
1152    // A `--mono` request downmixes the kept audio track (speech clips / smaller
1153    // files). A single-channel source stays mono regardless.
1154    let mono = opts.mono;
1155    match opts.audio {
1156        AudioChoice::Drop => Ok(None),
1157        AudioChoice::Bitrate(b) => Ok(Some(AudioSpec {
1158            mono,
1159            ..AudioSpec::cbr(AudioCodec::Aac, b)
1160        })),
1161        AudioChoice::Keep => {
1162            let bps = match target {
1163                Some(tb) => budget::fit_audio_bps(tb, duration, AUDIO_LADDER)
1164                    .ok_or(EngineError::Infeasible)?,
1165                None => budget::DEFAULT_AUDIO_BPS,
1166            };
1167            // Never re-encode the track above its own bitrate: that only adds
1168            // bytes (a 64 kbps phone recording doesn't need 128 kbps AAC). Any
1169            // budget saved here goes to the video.
1170            let bps = match source_bps {
1171                Some(src) => bps.min(src.max(MIN_TRACK_BPS)),
1172                None => bps,
1173            };
1174            Ok(Some(AudioSpec {
1175                mono,
1176                ..AudioSpec::cbr(AudioCodec::Aac, bps)
1177            }))
1178        }
1179    }
1180}
1181
1182/// Floor for a capped audio track (a mis-reported tiny source rate must not
1183/// starve the audio).
1184const MIN_TRACK_BPS: u64 = 32_000;
1185
1186/// Choose the encode height in auto/explicit mode.
1187fn pick_height(res: ResolutionOpt, src_height: u32, vbps: u64) -> Option<u32> {
1188    match res {
1189        ResolutionOpt::Height(h) => clamp_height(h, src_height),
1190        ResolutionOpt::Auto => {
1191            let chosen = budget::choose_height(src_height, vbps);
1192            if src_height > 0 && chosen < src_height {
1193                Some(chosen)
1194            } else {
1195                None
1196            }
1197        }
1198    }
1199}
1200
1201/// Clamp an explicit height to the source (never upscale); `None` if it equals
1202/// the source (no scaling needed).
1203fn clamp_height(requested: u32, src_height: u32) -> Option<u32> {
1204    if src_height == 0 {
1205        return Some(requested);
1206    }
1207    let h = requested.min(src_height);
1208    if h == src_height {
1209        None
1210    } else {
1211        Some(h)
1212    }
1213}
1214
1215/// Choose an fps cap; `None` if uncapped or the cap is ≥ the source rate.
1216fn pick_fps(fps: FpsOpt, src_fps: Option<f64>) -> Option<u32> {
1217    match fps {
1218        FpsOpt::Auto => None,
1219        FpsOpt::Cap(f) => match src_fps {
1220            Some(src) if (f as f64) >= src => None,
1221            _ => Some(f),
1222        },
1223    }
1224}
1225
1226/// Default output path: `<stem>.shrink.<ext>` next to the input.
1227fn output_with_ext(input: &Path, ext: &str) -> PathBuf {
1228    let stem = input
1229        .file_stem()
1230        .map(|s| s.to_string_lossy().into_owned())
1231        .unwrap_or_else(|| "output".to_string());
1232    let mut out = input.parent().map(Path::to_path_buf).unwrap_or_default();
1233    out.push(format!("{stem}.shrink.{ext}"));
1234    out
1235}
1236
1237fn build_summary(video: &VideoSpec, audio: Option<&AudioSpec>, two_pass: bool) -> String {
1238    let mut parts = vec![if video.hardware {
1239        format!("{} (Apple hardware)", video.codec.label())
1240    } else {
1241        video.codec.label().to_string()
1242    }];
1243    match (video.bitrate_bps, video.crf) {
1244        (Some(bps), _) => parts.push(format!("up to {} kbps video", bps / 1000)),
1245        (_, Some(q)) if video.hardware => parts.push(format!("quality {q}")),
1246        (_, Some(crf)) => parts.push(format!("CRF {crf}")),
1247        _ => {}
1248    }
1249    if let Some(a) = audio {
1250        parts.push(format!("{} kbps audio", a.bitrate_bps / 1000));
1251    } else {
1252        parts.push("no audio".to_string());
1253    }
1254    if let Some(h) = video.height {
1255        parts.push(format!("{h}p"));
1256    }
1257    if let Some(f) = video.fps {
1258        parts.push(format!("{f} fps"));
1259    }
1260    if video.to_sdr.is_some() {
1261        parts.push("HDR → SDR".to_string());
1262    }
1263    parts.push(
1264        if two_pass {
1265            "two-pass"
1266        } else if video.hardware {
1267            "one pass"
1268        } else {
1269            "CRF"
1270        }
1271        .to_string(),
1272    );
1273    parts.join(" · ")
1274}
1275
1276/// The `-vf` chain: downscale first (fewer pixels to convert), then HDR → SDR.
1277///
1278/// HLG (phones) was designed to stay watchable as SDR: `colorspace` re-maps
1279/// BT.2020 → BT.709 reading the HLG curve as the BT.2020 gamma — side by side
1280/// with an iPhone clip it's the closest match to what macOS itself shows, and
1281/// it works in every ffmpeg build. PQ (HDR10) needs a real tone-map, which
1282/// takes `zscale` (libzimg — in the app's bundled ffmpeg, not in every build);
1283/// without it PQ falls back to `colorspace` too: flatter, but 8-bit SDR that plays.
1284fn video_filters(video: &VideoSpec, zscale: bool) -> Option<String> {
1285    const COLORSPACE: &str = "colorspace=all=bt709:iall=bt2020:itrc=bt2020-10:format=yuv420p";
1286    let mut chain = Vec::new();
1287    if let Some(h) = video.height {
1288        chain.push(format!("scale=-2:{h}"));
1289    }
1290    match video.to_sdr {
1291        Some(Hdr::Pq) if zscale => chain.push(
1292            "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,\
1293             tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p"
1294                .to_string(),
1295        ),
1296        Some(_) => chain.push(COLORSPACE.to_string()),
1297        None => {}
1298    }
1299    (!chain.is_empty()).then(|| chain.join(","))
1300}
1301
1302/// Base path for ffmpeg's two-pass log, unique per process + input stem.
1303fn passlog_base(plan: &EncodePlan) -> String {
1304    let stem = plan
1305        .input
1306        .file_stem()
1307        .map(|s| s.to_string_lossy().into_owned())
1308        .unwrap_or_else(|| "ds".to_string());
1309    let dir = std::env::temp_dir();
1310    dir.join(format!("deepshrink-{}-{}", std::process::id(), stem))
1311        .to_string_lossy()
1312        .into_owned()
1313}
1314
1315/// Remove the files ffmpeg leaves behind for `-passlogfile <base>`.
1316fn cleanup_passlog(base: &str) {
1317    for suffix in ["-0.log", "-0.log.mbtree"] {
1318        let _ = fs::remove_file(format!("{base}{suffix}"));
1319    }
1320}
1321
1322/// Encode a single-pass CRF trial into `plan.output` at the given CRF.
1323fn encode_at_crf(
1324    tools: &deepshrink_ffmpeg::Tools,
1325    plan: &EncodePlan,
1326    encoder: &str,
1327    zscale: bool,
1328    crf: u8,
1329    total: f64,
1330    on_progress: &mut dyn FnMut(PassKind, f64),
1331) -> Result<(), EngineError> {
1332    let mut trial = plan.clone();
1333    trial.spec.video.crf = Some(crf);
1334    trial.spec.video.bitrate_bps = None;
1335    trial.spec.two_pass = false;
1336    let args = build_pass_args(&trial, PassKind::Single, "", encoder, zscale);
1337    tools.run_pass(&args, total, &mut |f| on_progress(PassKind::Single, f))?;
1338    Ok(())
1339}
1340
1341/// Threads to hand libvmaf (bounded by available parallelism).
1342fn thread_count() -> usize {
1343    std::thread::available_parallelism()
1344        .map(|n| n.get())
1345        .unwrap_or(1)
1346}
1347
1348/// Platform null sink for the discard output of pass 1.
1349fn null_sink() -> &'static str {
1350    if cfg!(windows) {
1351        "NUL"
1352    } else {
1353        "/dev/null"
1354    }
1355}
1356
1357/// Pick the ffmpeg encoder to drive this plan with.
1358///
1359/// x264/x265 are in every build worth supporting, so they're taken on faith —
1360/// asking ffmpeg costs a process spawn per run. AV1 is the exception: builds
1361/// disagree on which (if any) AV1 encoder they carry, so it's probed, with
1362/// libaom as the fallback and a plain-English error when neither is present
1363/// (better than handing the user ffmpeg's "Unknown encoder" dump).
1364fn resolve_encoder(
1365    tools: &deepshrink_ffmpeg::Tools,
1366    plan: &EncodePlan,
1367) -> Result<&'static str, EngineError> {
1368    let codec = plan.spec.video.codec;
1369    // Apple's hardware encoder (availability was checked when planning).
1370    if plan.spec.video.hardware && !plan.spec.passthrough && !plan.spec.audio_only {
1371        if let Some(hw) = codec.hardware_encoder() {
1372            return Ok(hw);
1373        }
1374    }
1375    let primary = codec.encoder();
1376    let Some(fallback) = codec.fallback_encoder() else {
1377        return Ok(primary);
1378    };
1379    // Passthrough/audio-only encodes never touch the video encoder.
1380    if plan.spec.passthrough || plan.spec.audio_only {
1381        return Ok(primary);
1382    }
1383    if deepshrink_ffmpeg::has_encoder(&tools.ffmpeg, primary) {
1384        return Ok(primary);
1385    }
1386    if deepshrink_ffmpeg::has_encoder(&tools.ffmpeg, fallback) {
1387        return Ok(fallback);
1388    }
1389    Err(EngineError::Unsupported(format!(
1390        "this ffmpeg build has no {} encoder (looked for {primary} and {fallback})",
1391        codec.label()
1392    )))
1393}
1394
1395/// Build the ffmpeg argv for one pass. Video-processing options (codec, filters,
1396/// bitrate) are shared across passes; audio/output differ per pass. `encoder` is
1397/// the resolved `-c:v` name (see [`resolve_encoder`]) — it can differ from the
1398/// codec's default for AV1.
1399fn build_pass_args(
1400    plan: &EncodePlan,
1401    pass: PassKind,
1402    passlog: &str,
1403    encoder: &str,
1404    zscale: bool,
1405) -> Vec<OsString> {
1406    let s = &plan.spec;
1407    let mut a: Vec<OsString> = Vec::new();
1408    // Local helper — a macro (not a closure) so it doesn't hold a borrow of `a`
1409    // across the direct `a.push(..)` calls used for OsString paths.
1410    macro_rules! push {
1411        ($arg:expr) => {
1412            a.push(OsString::from($arg))
1413        };
1414    }
1415
1416    push!("-hide_banner");
1417    push!("-y");
1418    push!("-loglevel");
1419    push!("error");
1420    push!("-progress");
1421    push!("pipe:1");
1422    push!("-nostats");
1423    push!("-i");
1424    a.push(plan.input.clone().into_os_string());
1425
1426    let (meta, meta_flag) = metadata_args(plan);
1427
1428    // Passthrough: stream copy, no re-encode. Output only (single pass).
1429    if s.passthrough {
1430        push!("-c");
1431        push!("copy");
1432        a.extend(meta.iter().cloned());
1433        if let Some(flags) = movflags(s.faststart, meta_flag) {
1434            push!("-movflags");
1435            push!(flags);
1436        }
1437        a.push(plan.output.clone().into_os_string());
1438        return a;
1439    }
1440
1441    // Pure audio: drop video, encode the audio track only (single pass).
1442    if s.audio_only {
1443        push!("-vn");
1444        if let Some(au) = &s.audio {
1445            push!("-c:a");
1446            push!(au.codec.encoder());
1447            if au.mono {
1448                push!("-ac");
1449                push!("1");
1450            }
1451            if let Some(sr) = au.sample_rate {
1452                push!("-ar");
1453                push!(sr.to_string());
1454            }
1455            push!("-b:a");
1456            push!(au.bitrate_bps.to_string());
1457            // Opus supports VBR; use constrained VBR by default for a tighter
1458            // fit to the target, or full VBR when requested.
1459            if matches!(au.codec, AudioCodec::Opus) {
1460                push!("-vbr");
1461                push!(if au.vbr { "on" } else { "constrained" });
1462            }
1463        }
1464        a.extend(meta.iter().cloned());
1465        if let Some(flags) = movflags(false, meta_flag) {
1466            push!("-movflags");
1467            push!(flags);
1468        }
1469        a.push(plan.output.clone().into_os_string());
1470        return a;
1471    }
1472
1473    // Video codec + filters.
1474    push!("-c:v");
1475    push!(encoder);
1476    if let Some(vf) = video_filters(&s.video, zscale) {
1477        push!("-vf");
1478        push!(vf);
1479    }
1480    if let Some(f) = s.video.fps {
1481        push!("-r");
1482        push!(f.to_string());
1483    }
1484    // The speed knob is per-encoder: `-preset medium` is meaningless (and fatal)
1485    // to SVT-AV1, which wants a number.
1486    // VideoToolbox has no speed preset — it's fast by construction.
1487    let videotoolbox = encoder.ends_with("_videotoolbox");
1488    if !videotoolbox {
1489        let (speed_flag, speed_value) = s.video.preset.speed_flags(encoder);
1490        push!(speed_flag);
1491        push!(speed_value);
1492    }
1493    if let Some(tag) = s.video.codec.mp4_tag() {
1494        push!("-tag:v");
1495        push!(tag);
1496    }
1497    // Tone-mapped to SDR: 8-bit, and labelled BT.709 so players don't treat
1498    // it as HDR (the source's BT.2020/HLG tags would otherwise carry over).
1499    if s.video.to_sdr.is_some() {
1500        for (flag, value) in [
1501            ("-pix_fmt", "yuv420p"),
1502            ("-color_primaries", "bt709"),
1503            ("-color_trc", "bt709"),
1504            ("-colorspace", "bt709"),
1505        ] {
1506            push!(flag);
1507            push!(value);
1508        }
1509    }
1510
1511    // Rate control.
1512    match (s.video.bitrate_bps, s.video.crf) {
1513        (Some(bps), _) => {
1514            push!("-b:v");
1515            push!(bps.to_string());
1516            if s.two_pass {
1517                push!("-pass");
1518                push!(match pass {
1519                    PassKind::First => "1",
1520                    _ => "2",
1521                });
1522                push!("-passlogfile");
1523                push!(passlog);
1524            }
1525        }
1526        (_, Some(crf)) => {
1527            // Apple's encoder takes a constant quality (1–100), not a CRF.
1528            push!(if videotoolbox { "-q:v" } else { "-crf" });
1529            push!(crf.to_string());
1530        }
1531        _ => {}
1532    }
1533
1534    // Audio + output.
1535    match pass {
1536        PassKind::First => {
1537            // Analysis pass: no audio, discard the muxed output.
1538            push!("-an");
1539            push!("-f");
1540            push!("null");
1541            push!(null_sink());
1542        }
1543        PassKind::Second | PassKind::Single => {
1544            match &s.audio {
1545                Some(au) => {
1546                    push!("-c:a");
1547                    push!(au.codec.encoder());
1548                    // A mono downmix has to reach ffmpeg here too — the audio
1549                    // track of a video is muxed in this pass, not the audio-only
1550                    // branch above.
1551                    if au.mono {
1552                        push!("-ac");
1553                        push!("1");
1554                    }
1555                    push!("-b:a");
1556                    push!(au.bitrate_bps.to_string());
1557                }
1558                None => push!("-an"),
1559            }
1560            a.extend(meta.iter().cloned());
1561            if let Some(flags) = movflags(s.faststart, meta_flag) {
1562                push!("-movflags");
1563                push!(flags);
1564            }
1565            a.push(plan.output.clone().into_os_string());
1566        }
1567    }
1568    a
1569}
1570
1571#[cfg(test)]
1572mod tests {
1573    use super::*;
1574    use crate::options::{AudioCodec, QualityPreset, VideoCodec};
1575    use crate::size::preset;
1576
1577    /// The encoder `run` would resolve for a plan without probing ffmpeg (every
1578    /// codec these tests use has its primary encoder everywhere).
1579    fn enc(plan: &EncodePlan) -> &'static str {
1580        plan.spec.video.codec.encoder()
1581    }
1582
1583    fn video_info(duration: f64, size: u64, w: u32, h: u32, audio: bool) -> MediaInfo {
1584        MediaInfo {
1585            path: PathBuf::from("/tmp/clip.mp4"),
1586            kind: MediaKind::Video,
1587            duration_sec: duration,
1588            size_bytes: size,
1589            width: Some(w),
1590            height: Some(h),
1591            fps: Some(30.0),
1592            video_codec: Some("h264".into()),
1593            audio_codec: if audio { Some("aac".into()) } else { None },
1594            audio_channels: if audio { Some(2) } else { None },
1595            audio_bitrate_bps: None,
1596            capture: CaptureMeta::default(),
1597            hdr: None,
1598        }
1599    }
1600
1601    fn opts_target(bytes: u64) -> ShrinkOpts {
1602        ShrinkOpts {
1603            goal: SizeGoal::Target(bytes),
1604            ..Default::default()
1605        }
1606    }
1607
1608    #[test]
1609    fn supports_video_and_audio() {
1610        let e = MediaEngine::new();
1611        assert!(e.supports(&PathBuf::from("clip.mp4")));
1612        assert!(e.supports(&PathBuf::from("lecture.wav")));
1613        assert!(!e.supports(&PathBuf::from("photo.jpg")));
1614    }
1615
1616    #[test]
1617    fn plan_target_builds_two_pass_with_budget() {
1618        let info = video_info(120.0, 300_000_000, 1920, 1080, true);
1619        let plan = MediaEngine::new()
1620            .plan(&info, &opts_target(8_000_000))
1621            .unwrap();
1622
1623        assert!(plan.spec.two_pass);
1624        assert_eq!(plan.target_bytes, Some(8_000_000));
1625        assert_eq!(plan.output, PathBuf::from("/tmp/clip.shrink.mp4"));
1626        let vbps = plan.spec.video.bitrate_bps.unwrap();
1627        assert!(vbps >= budget::ABSOLUTE_MIN_VIDEO_BPS);
1628        // 8 MB over 120 s is a low budget → downscale from 1080p.
1629        assert!(plan.spec.video.height.is_some());
1630        assert!(plan.spec.audio.is_some());
1631        // Predicted size should not exceed the target.
1632        assert!(plan.expected_bytes.unwrap() <= 8_000_000 + 8_000_000 / 20);
1633    }
1634
1635    #[test]
1636    fn plan_video_mono_downmixes_the_audio_track() {
1637        let info = video_info(60.0, 100_000_000, 1280, 720, true);
1638        let opts = ShrinkOpts {
1639            mono: true,
1640            ..opts_target(8_000_000)
1641        };
1642        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1643        let audio = plan.spec.audio.as_ref().expect("kept audio track");
1644        assert!(audio.mono, "opts.mono downmixes the video's audio track");
1645        // A stereo request stays stereo.
1646        let stereo = MediaEngine::new()
1647            .plan(&info, &opts_target(8_000_000))
1648            .unwrap();
1649        assert!(!stereo.spec.audio.as_ref().unwrap().mono);
1650    }
1651
1652    #[test]
1653    fn video_mono_reaches_ffmpeg_as_ac_1() {
1654        // The plan carrying `mono` is only half the job — the muxing pass of a
1655        // video encode has to actually emit `-ac 1`, or the output stays stereo.
1656        let info = video_info(60.0, 100_000_000, 1280, 720, true);
1657        let plan = MediaEngine::new()
1658            .plan(
1659                &info,
1660                &ShrinkOpts {
1661                    mono: true,
1662                    ..opts_target(8_000_000)
1663                },
1664            )
1665            .unwrap();
1666        let args = build_pass_args(&plan, PassKind::Second, "/tmp/passlog", enc(&plan), false);
1667        let joined: Vec<String> = args
1668            .iter()
1669            .map(|a| a.to_string_lossy().into_owned())
1670            .collect();
1671        let ac = joined.iter().position(|a| a == "-ac").expect("-ac emitted");
1672        assert_eq!(joined[ac + 1], "1");
1673
1674        // Stereo request → no downmix flag at all.
1675        let stereo = MediaEngine::new()
1676            .plan(&info, &opts_target(8_000_000))
1677            .unwrap();
1678        let stereo_args: Vec<String> = build_pass_args(
1679            &stereo,
1680            PassKind::Second,
1681            "/tmp/passlog",
1682            enc(&stereo),
1683            false,
1684        )
1685        .iter()
1686        .map(|a| a.to_string_lossy().into_owned())
1687        .collect();
1688        assert!(!stereo_args.iter().any(|a| a == "-ac"));
1689    }
1690
1691    #[test]
1692    fn plan_preset_discord_sets_target() {
1693        let info = video_info(30.0, 50_000_000, 1280, 720, true);
1694        let opts = ShrinkOpts {
1695            goal: SizeGoal::Preset(preset("discord").unwrap()),
1696            ..Default::default()
1697        };
1698        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1699        assert_eq!(plan.target_bytes, Some(8_000_000));
1700    }
1701
1702    #[test]
1703    fn plan_reduce_targets_complement_of_original() {
1704        let info = video_info(60.0, 100_000_000, 1920, 1080, true);
1705        let opts = ShrinkOpts {
1706            goal: SizeGoal::Reduce(0.70),
1707            ..Default::default()
1708        };
1709        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1710        assert_eq!(plan.target_bytes, Some(30_000_000));
1711    }
1712
1713    #[test]
1714    fn plan_passthrough_when_source_already_fits() {
1715        // Source is 200 KB, target 1 MB → never inflate; stream-copy remux.
1716        let info = video_info(10.0, 200_000, 1280, 720, true);
1717        let plan = MediaEngine::new()
1718            .plan(&info, &opts_target(1_000_000))
1719            .unwrap();
1720        assert!(plan.spec.passthrough);
1721        assert!(!plan.spec.two_pass);
1722        assert_eq!(plan.expected_bytes, Some(200_000));
1723        let args = build_pass_args(&plan, PassKind::Single, "/tmp/passlog", enc(&plan), false);
1724        let joined: Vec<String> = args
1725            .iter()
1726            .map(|a| a.to_string_lossy().into_owned())
1727            .collect();
1728        assert!(joined.contains(&"copy".to_string()));
1729        // Same container as the source: a stream copy must land somewhere its
1730        // codecs are muxable.
1731        assert_eq!(plan.output, PathBuf::from("/tmp/clip.shrink.mp4"));
1732    }
1733
1734    #[test]
1735    fn plan_passthrough_keeps_the_source_container() {
1736        // A .3gp may carry codecs (AMR-NB) that no .mp4 muxer accepts — copying
1737        // its streams into an .mp4 would fail on a file we aren't re-encoding.
1738        let info = MediaInfo {
1739            path: PathBuf::from("/tmp/voice.3gp"),
1740            ..video_info(10.0, 200_000, 320, 240, true)
1741        };
1742        let plan = MediaEngine::new()
1743            .plan(&info, &opts_target(1_000_000))
1744            .unwrap();
1745        assert!(plan.spec.passthrough);
1746        assert_eq!(plan.output, PathBuf::from("/tmp/voice.shrink.3gp"));
1747    }
1748
1749    #[test]
1750    fn plan_infeasible_when_target_too_small() {
1751        let info = video_info(600.0, 500_000_000, 1920, 1080, true);
1752        let err = MediaEngine::new().plan(&info, &opts_target(50_000));
1753        assert!(matches!(err, Err(EngineError::Infeasible)));
1754    }
1755
1756    #[test]
1757    fn plan_quality_mode_uses_crf_single_pass() {
1758        let info = video_info(60.0, 100_000_000, 1920, 1080, true);
1759        let opts = ShrinkOpts {
1760            goal: SizeGoal::Quality,
1761            quality: QualityPreset::Balanced,
1762            ..Default::default()
1763        };
1764        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1765        assert!(!plan.spec.two_pass);
1766        assert_eq!(plan.spec.video.crf, Some(23));
1767        assert!(plan.spec.video.bitrate_bps.is_none());
1768        assert!(plan.expected_bytes.is_none());
1769    }
1770
1771    #[test]
1772    fn plan_drops_audio_when_requested() {
1773        let info = video_info(30.0, 50_000_000, 1280, 720, true);
1774        let opts = ShrinkOpts {
1775            audio: AudioChoice::Drop,
1776            ..opts_target(8_000_000)
1777        };
1778        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1779        assert!(plan.spec.audio.is_none());
1780    }
1781
1782    fn audio_info(duration: f64, size: u64, channels: u32) -> MediaInfo {
1783        MediaInfo {
1784            path: PathBuf::from("/tmp/lecture.wav"),
1785            kind: MediaKind::Audio,
1786            duration_sec: duration,
1787            size_bytes: size,
1788            width: None,
1789            height: None,
1790            fps: None,
1791            video_codec: None,
1792            audio_codec: Some("pcm_s16le".into()),
1793            audio_channels: Some(channels),
1794            audio_bitrate_bps: None,
1795            capture: CaptureMeta::default(),
1796            hdr: None,
1797        }
1798    }
1799
1800    #[test]
1801    fn quality_audio_bitrate_follows_tier_codec_and_channels() {
1802        use QualityPreset::*;
1803        assert_eq!(quality_audio_bps(Balanced, AudioCodec::Aac, false), 128_000);
1804        assert_eq!(quality_audio_bps(Balanced, AudioCodec::Aac, true), 64_000);
1805        assert_eq!(quality_audio_bps(Fast, AudioCodec::Opus, true), 32_000);
1806        assert_eq!(quality_audio_bps(Max, AudioCodec::Mp3, false), 256_000);
1807        // Every tier is strictly smaller → larger, per codec.
1808        for c in [AudioCodec::Aac, AudioCodec::Opus, AudioCodec::Mp3] {
1809            let t: Vec<_> = [Fast, Balanced, Max]
1810                .map(|q| quality_audio_bps(q, c, false))
1811                .into();
1812            assert!(t[0] < t[1] && t[1] < t[2], "{c:?}: {t:?}");
1813        }
1814    }
1815
1816    #[test]
1817    fn a_compact_audiobook_is_kept_in_quality_mode() {
1818        // 1 h mono at 64 kbps (the review case): balanced AAC mono is 64 kbps too.
1819        let mut info = audio_info(3600.0, 64_000 / 8 * 3600, 1);
1820        info.path = PathBuf::from("/tmp/book.mp3");
1821        let plan = MediaEngine::new()
1822            .plan(&info, &ShrinkOpts::default())
1823            .unwrap();
1824        assert!(plan.spec.passthrough, "{}", plan.summary);
1825        assert!(plan.output.to_string_lossy().ends_with(".mp3"));
1826        assert!(plan.summary.contains("already compact"));
1827
1828        // A genuinely smaller recipe still encodes (Opus fast mono = 32 kbps).
1829        let smaller = ShrinkOpts {
1830            audio_codec: AudioCodec::Opus,
1831            quality: QualityPreset::Fast,
1832            ..ShrinkOpts::default()
1833        };
1834        let plan = MediaEngine::new().plan(&info, &smaller).unwrap();
1835        assert!(!plan.spec.passthrough);
1836        assert_eq!(plan.spec.audio.as_ref().unwrap().bitrate_bps, 32_000);
1837        assert!(
1838            plan.guard_larger,
1839            "quality mode keeps the post-encode check"
1840        );
1841
1842        // Opting out re-encodes at the tier bitrate.
1843        let allow = ShrinkOpts {
1844            allow_larger: true,
1845            ..ShrinkOpts::default()
1846        };
1847        let plan = MediaEngine::new().plan(&info, &allow).unwrap();
1848        assert!(!plan.spec.passthrough && !plan.guard_larger);
1849    }
1850
1851    #[test]
1852    fn the_guard_is_for_quality_mode_only() {
1853        let info = video_info(60.0, 50_000_000, 1920, 1080, true);
1854        let quality = MediaEngine::new()
1855            .plan(&info, &ShrinkOpts::default())
1856            .unwrap();
1857        assert!(quality.guard_larger);
1858        let target = MediaEngine::new()
1859            .plan(&info, &opts_target(10_000_000))
1860            .unwrap();
1861        assert!(!target.guard_larger, "a size target is its own guarantee");
1862    }
1863
1864    #[test]
1865    fn plan_audio_single_pass_with_fitted_bitrate() {
1866        // 58 min stereo lecture, target 10 MB.
1867        let info = audio_info(3480.0, 600_000_000, 2);
1868        let plan = MediaEngine::new()
1869            .plan(&info, &opts_target(10_000_000))
1870            .unwrap();
1871        assert!(plan.spec.audio_only);
1872        assert!(!plan.spec.two_pass);
1873        assert_eq!(plan.output, PathBuf::from("/tmp/lecture.shrink.m4a"));
1874        let au = plan.spec.audio.as_ref().unwrap();
1875        // Snapped down to a standard step, never above the raw budget.
1876        assert!(budget::AUDIO_STEPS.contains(&au.bitrate_bps));
1877        assert!(plan.expected_bytes.unwrap() <= 10_000_000 + 10_000_000 / 20);
1878    }
1879
1880    #[test]
1881    fn plan_audio_mono_source_marked_speech() {
1882        let info = audio_info(600.0, 100_000_000, 1);
1883        let plan = MediaEngine::new()
1884            .plan(&info, &opts_target(5_000_000))
1885            .unwrap();
1886        assert!(plan.spec.audio.as_ref().unwrap().mono);
1887    }
1888
1889    #[test]
1890    fn plan_audio_opus_extension_and_vbr_args() {
1891        let info = audio_info(600.0, 100_000_000, 2);
1892        let opts = ShrinkOpts {
1893            audio_codec: AudioCodec::Opus,
1894            mono: true,
1895            ..opts_target(3_000_000)
1896        };
1897        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
1898        assert_eq!(plan.output, PathBuf::from("/tmp/lecture.shrink.opus"));
1899        let args = build_pass_args(&plan, PassKind::Single, "/tmp/passlog", enc(&plan), false);
1900        let j: Vec<String> = args
1901            .iter()
1902            .map(|a| a.to_string_lossy().into_owned())
1903            .collect();
1904        assert!(j.contains(&"-vn".to_string()));
1905        assert!(j.contains(&"libopus".to_string()));
1906        assert!(j.contains(&"-ac".to_string())); // mono downmix
1907        assert!(j.contains(&"-vbr".to_string()));
1908    }
1909
1910    #[test]
1911    fn plan_audio_infeasible_when_target_tiny() {
1912        let info = audio_info(3600.0, 500_000_000, 2);
1913        assert!(matches!(
1914            MediaEngine::new().plan(&info, &opts_target(1_000)),
1915            Err(EngineError::Infeasible)
1916        ));
1917    }
1918
1919    #[test]
1920    fn plan_audio_passthrough_when_source_fits() {
1921        let info = audio_info(600.0, 2_000_000, 2);
1922        let plan = MediaEngine::new()
1923            .plan(&info, &opts_target(10_000_000))
1924            .unwrap();
1925        assert!(plan.spec.passthrough);
1926        // Passthrough keeps the source container/extension.
1927        assert_eq!(plan.output, PathBuf::from("/tmp/lecture.shrink.wav"));
1928    }
1929
1930    #[test]
1931    fn pass1_args_have_no_audio_and_null_sink() {
1932        let info = video_info(120.0, 300_000_000, 1920, 1080, true);
1933        let plan = MediaEngine::new()
1934            .plan(&info, &opts_target(8_000_000))
1935            .unwrap();
1936        let args = build_pass_args(&plan, PassKind::First, "/tmp/passlog", enc(&plan), false);
1937        let joined: Vec<String> = args
1938            .iter()
1939            .map(|a| a.to_string_lossy().into_owned())
1940            .collect();
1941        assert!(joined.contains(&"-an".to_string()));
1942        assert!(joined.contains(&"null".to_string()));
1943        assert!(joined.iter().any(|a| a == "1")); // -pass 1
1944        assert!(!joined.iter().any(|a| a.contains("shrink.mp4")));
1945    }
1946
1947    #[test]
1948    fn pass2_args_write_output_with_audio() {
1949        let info = video_info(120.0, 300_000_000, 1920, 1080, true);
1950        let plan = MediaEngine::new()
1951            .plan(&info, &opts_target(8_000_000))
1952            .unwrap();
1953        let args = build_pass_args(&plan, PassKind::Second, "/tmp/passlog", enc(&plan), false);
1954        let joined: Vec<String> = args
1955            .iter()
1956            .map(|a| a.to_string_lossy().into_owned())
1957            .collect();
1958        assert!(joined.iter().any(|a| a.contains("clip.shrink.mp4")));
1959        assert!(joined.contains(&"-c:a".to_string()));
1960        assert!(joined.iter().any(|a| a.contains("+faststart")));
1961        assert!(joined.iter().any(|a| a == "2")); // -pass 2
1962    }
1963
1964    fn joined(plan: &EncodePlan, pass: PassKind) -> Vec<String> {
1965        joined_with(plan, pass, false)
1966    }
1967
1968    fn joined_with(plan: &EncodePlan, pass: PassKind, zscale: bool) -> Vec<String> {
1969        build_pass_args(plan, pass, "/tmp/passlog", enc(plan), zscale)
1970            .iter()
1971            .map(|a| a.to_string_lossy().into_owned())
1972            .collect()
1973    }
1974
1975    #[test]
1976    fn hdr_transfer_is_recognised() {
1977        assert_eq!(Hdr::from_transfer("arib-std-b67"), Some(Hdr::Hlg));
1978        assert_eq!(Hdr::from_transfer("smpte2084"), Some(Hdr::Pq));
1979        assert_eq!(Hdr::from_transfer("bt709"), None);
1980    }
1981
1982    #[test]
1983    fn hdr_is_tone_mapped_to_sdr_for_size_targets_only() {
1984        let mut info = iphone_info();
1985        info.hdr = Some(Hdr::Hlg);
1986        let engine = MediaEngine::new();
1987
1988        // Discord: must play everywhere → 8-bit SDR BT.709.
1989        let target = engine.plan(&info, &opts_target(10_000_000)).unwrap();
1990        assert_eq!(target.spec.video.to_sdr, Some(Hdr::Hlg));
1991        assert!(target.summary.contains("HDR → SDR"));
1992        let vf_of =
1993            |args: &[String]| args[args.iter().position(|a| a == "-vf").unwrap() + 1].clone();
1994        // HLG: the colorspace re-map (closest to what macOS shows), any build.
1995        let hlg = joined_with(&target, PassKind::Second, true);
1996        let vf = vf_of(&hlg);
1997        assert!(
1998            vf.contains("colorspace=all=bt709") && !vf.contains("zscale"),
1999            "{vf}"
2000        );
2001        // Downscale first, then convert the fewer pixels.
2002        assert!(
2003            vf.find("scale=-2:").unwrap() < vf.find("colorspace").unwrap(),
2004            "{vf}"
2005        );
2006        for pair in [
2007            ["-pix_fmt", "yuv420p"],
2008            ["-color_trc", "bt709"],
2009            ["-colorspace", "bt709"],
2010        ] {
2011            assert!(hlg.windows(2).any(|w| w == pair), "{pair:?}");
2012        }
2013        // PQ: a real tone-map with zscale, the colorspace re-map without it.
2014        let mut pq = target.clone();
2015        pq.spec.video.to_sdr = Some(Hdr::Pq);
2016        let vf = vf_of(&joined_with(&pq, PassKind::Second, true));
2017        assert!(
2018            vf.contains("tonemap=hable") && vf.contains("npl=100"),
2019            "{vf}"
2020        );
2021        let vf = vf_of(&joined_with(&pq, PassKind::Second, false));
2022        assert!(
2023            vf.contains("colorspace=all=bt709") && !vf.contains("zscale"),
2024            "{vf}"
2025        );
2026
2027        // Quality mode keeps HDR and 10-bit as shot.
2028        let quality = engine.plan(&info, &ShrinkOpts::default()).unwrap();
2029        assert_eq!(quality.spec.video.to_sdr, None);
2030        let args = joined(&quality, PassKind::Single);
2031        assert!(!args
2032            .iter()
2033            .any(|a| a == "-pix_fmt" || a.contains("colorspace")));
2034
2035        // An SDR source is left alone even with a target.
2036        let sdr = engine
2037            .plan(&iphone_info(), &opts_target(10_000_000))
2038            .unwrap();
2039        assert_eq!(sdr.spec.video.to_sdr, None);
2040        assert!(!joined(&sdr, PassKind::Second)
2041            .iter()
2042            .any(|a| a == "-pix_fmt"));
2043    }
2044
2045    #[test]
2046    fn a_size_target_is_a_ceiling_at_the_quality_crf() {
2047        let info = video_info(60.0, 200_000_000, 1920, 1080, true);
2048        let engine = MediaEngine::new();
2049        let opts = opts_target(50_000_000);
2050        let plan = engine.plan(&info, &opts).unwrap();
2051        let crf = opts.quality.default_crf(opts.video_codec);
2052        assert_eq!(plan.ceiling_crf, Some(crf));
2053
2054        let ceiling = ceiling_plan(&plan).unwrap();
2055        assert_eq!(ceiling.spec.video.crf, Some(crf));
2056        assert_eq!(ceiling.spec.video.bitrate_bps, None);
2057        assert!(!ceiling.spec.two_pass);
2058        // Same everything else: resolution, audio, output, the target itself.
2059        assert_eq!(ceiling.spec.video.height, plan.spec.video.height);
2060        assert_eq!(ceiling.spec.audio, plan.spec.audio);
2061        assert_eq!(ceiling.output, plan.output);
2062        assert_eq!(ceiling.target_bytes, plan.target_bytes);
2063
2064        // Quality mode and passthrough have no ceiling to try.
2065        let quality = engine.plan(&info, &ShrinkOpts::default()).unwrap();
2066        assert!(quality.ceiling_crf.is_none() && ceiling_plan(&quality).is_none());
2067        let fits = engine.plan(&info, &opts_target(300_000_000)).unwrap();
2068        assert!(fits.spec.passthrough && ceiling_plan(&fits).is_none());
2069    }
2070
2071    #[test]
2072    fn heavy_video_samples_shorter_windows() {
2073        let engine = MediaEngine::new();
2074        let mut info = video_info(120.0, 500_000_000, 1920, 1080, true);
2075        info.fps = Some(30.0);
2076        let plan = engine.plan(&info, &ShrinkOpts::default()).unwrap();
2077        assert_eq!(sample_secs(&plan), 3.0);
2078        info = video_info(120.0, 500_000_000, 3840, 2160, true);
2079        info.fps = Some(60.0);
2080        let plan = engine.plan(&info, &ShrinkOpts::default()).unwrap();
2081        assert_eq!(sample_secs(&plan), MIN_SAMPLE_SECS);
2082    }
2083
2084    #[test]
2085    fn apple_hardware_uses_quality_one_pass_and_no_preset() {
2086        let engine = MediaEngine::new();
2087        let info = video_info(60.0, 200_000_000, 1920, 1080, true);
2088        let mut plan = engine.plan(&info, &ShrinkOpts::default()).unwrap();
2089        // As a plan would be on an Apple Silicon Mac with `hardware: true`.
2090        plan.spec.video.hardware = true;
2091        plan.spec.video.crf = QualityPreset::Balanced.default_hw_quality(VideoCodec::H264);
2092        let args: Vec<String> =
2093            build_pass_args(&plan, PassKind::Single, "", "h264_videotoolbox", false)
2094                .iter()
2095                .map(|a| a.to_string_lossy().into_owned())
2096                .collect();
2097        assert!(args.windows(2).any(|w| w == ["-c:v", "h264_videotoolbox"]));
2098        assert!(args.windows(2).any(|w| w == ["-q:v", "66"]), "{args:?}");
2099        assert!(
2100            !args.iter().any(|a| a == "-crf" || a == "-preset"),
2101            "{args:?}"
2102        );
2103        let mut hw = plan.clone();
2104        hw.spec.passthrough = false;
2105        assert_eq!(
2106            resolve_encoder(
2107                &deepshrink_ffmpeg::Tools {
2108                    ffmpeg: "ffmpeg".into(),
2109                    ffprobe: "ffprobe".into(),
2110                    cancel: Default::default(),
2111                },
2112                &hw
2113            )
2114            .unwrap(),
2115            "h264_videotoolbox"
2116        );
2117        // AV1 has no Apple encoder: the quality map says so.
2118        assert_eq!(
2119            QualityPreset::Balanced.default_hw_quality(VideoCodec::Av1),
2120            None
2121        );
2122    }
2123
2124    fn iphone_info() -> MediaInfo {
2125        let mut info = video_info(60.0, 50_000_000, 2160, 3840, true);
2126        info.path = PathBuf::from("/tmp/IMG_3325.MOV");
2127        info.capture = CaptureMeta {
2128            created_utc: to_utc("2026-09-26T20:01:54+0300"),
2129            created_local: Some("2026-09-26T20:01:54+0300".into()),
2130            location: Some("+50.4160+030.2796+155.635/".into()),
2131            make: Some("Apple".into()),
2132            model: Some("iPhone 12 Pro Max".into()),
2133        };
2134        info
2135    }
2136
2137    #[test]
2138    fn metadata_is_kept_by_default_and_strippable() {
2139        let info = iphone_info();
2140        let plan = MediaEngine::new()
2141            .plan(&info, &ShrinkOpts::default())
2142            .unwrap();
2143        let a = joined(&plan, PassKind::Single);
2144        let at = a.iter().position(|x| x == "-map_metadata").unwrap();
2145        assert_eq!(a[at + 1], "0");
2146        // The capture tags are re-stated explicitly — the shooting date (not
2147        // the file's export time) in UTC, and location / make / model.
2148        for tag in [
2149            "creation_time=2026-09-26T17:01:54Z",
2150            "location=+50.4160+030.2796+155.635/",
2151            "make=Apple",
2152            "model=iPhone 12 Pro Max",
2153            "date=2026-09-26T20:01:54+0300",
2154        ] {
2155            assert!(a.contains(&tag.to_string()), "{tag} in {a:?}");
2156        }
2157        assert!(a.contains(&"+faststart".to_string()));
2158
2159        let strip = ShrinkOpts {
2160            keep_metadata: false,
2161            ..ShrinkOpts::default()
2162        };
2163        let plan = MediaEngine::new().plan(&info, &strip).unwrap();
2164        let a = joined(&plan, PassKind::Single);
2165        let at = a.iter().position(|x| x == "-map_metadata").unwrap();
2166        assert_eq!(a[at + 1], "-1");
2167        assert!(!a.iter().any(|x| x.starts_with("location=")));
2168        assert!(a.contains(&"+faststart".to_string()));
2169    }
2170
2171    #[test]
2172    fn apple_local_time_converts_to_utc() {
2173        let utc = |s: &str| to_utc(s);
2174        assert_eq!(
2175            utc("2026-09-26T20:01:54+0300").as_deref(),
2176            Some("2026-09-26T17:01:54Z")
2177        );
2178        assert_eq!(
2179            utc("2026-09-26T20:01:54+03:00").as_deref(),
2180            Some("2026-09-26T17:01:54Z")
2181        );
2182        assert_eq!(
2183            utc("2026-01-01T01:30:00+0300").as_deref(),
2184            Some("2025-12-31T22:30:00Z")
2185        );
2186        assert_eq!(
2187            utc("2026-03-01T23:00:00-0500").as_deref(),
2188            Some("2026-03-02T04:00:00Z")
2189        );
2190        assert_eq!(
2191            utc("2024-02-29T12:00:00.123Z").as_deref(),
2192            Some("2024-02-29T12:00:00Z")
2193        );
2194        assert_eq!(utc("yesterday"), None);
2195    }
2196
2197    #[test]
2198    fn an_iphone_mov_stays_mov_in_quality_mode_only() {
2199        let info = iphone_info();
2200        let out = |opts: &ShrinkOpts| {
2201            let plan = MediaEngine::new().plan(&info, opts).unwrap();
2202            plan.output.to_string_lossy().into_owned()
2203        };
2204        assert!(out(&ShrinkOpts::default()).ends_with(".shrink.mov"));
2205        // Platform presets / size targets are for sharing → MP4.
2206        assert!(out(&opts_target(8_000_000)).ends_with(".shrink.mp4"));
2207        // AV1 has no QuickTime mapping → MP4.
2208        let av1 = ShrinkOpts {
2209            video_codec: VideoCodec::Av1,
2210            ..ShrinkOpts::default()
2211        };
2212        assert!(out(&av1).ends_with(".shrink.mp4"));
2213        // Non-MOV sources are unaffected.
2214        let mp4 = video_info(60.0, 50_000_000, 1920, 1080, true);
2215        let p = MediaEngine::new()
2216            .plan(&mp4, &ShrinkOpts::default())
2217            .unwrap();
2218        assert!(p.output.to_string_lossy().ends_with(".shrink.mp4"));
2219    }
2220
2221    #[test]
2222    fn a_video_audio_track_is_never_upsampled() {
2223        let mut info = video_info(60.0, 50_000_000, 1920, 1080, true);
2224        info.audio_bitrate_bps = Some(64_000);
2225        let bps_of = |info: &MediaInfo, opts: &ShrinkOpts| {
2226            let plan = MediaEngine::new().plan(info, opts).unwrap();
2227            plan.spec.audio.unwrap().bitrate_bps
2228        };
2229        // Quality mode default is 128 kbps — capped at the source's 64 kbps.
2230        assert_eq!(bps_of(&info, &ShrinkOpts::default()), 64_000);
2231        // A size target too: never above the source (the rest goes to video).
2232        assert!(bps_of(&info, &opts_target(20_000_000)) <= 64_000);
2233        // An explicit `--audio 128k` is still honoured as asked.
2234        let explicit = ShrinkOpts {
2235            audio: AudioChoice::Bitrate(128_000),
2236            ..ShrinkOpts::default()
2237        };
2238        assert_eq!(bps_of(&info, &explicit), 128_000);
2239        // Unknown source rate → the default.
2240        info.audio_bitrate_bps = None;
2241        assert_eq!(
2242            bps_of(&info, &ShrinkOpts::default()),
2243            budget::DEFAULT_AUDIO_BPS
2244        );
2245    }
2246
2247    #[test]
2248    fn h265_adds_hvc1_tag() {
2249        let info = video_info(60.0, 100_000_000, 1280, 720, false);
2250        let opts = ShrinkOpts {
2251            video_codec: VideoCodec::H265,
2252            ..opts_target(8_000_000)
2253        };
2254        let plan = MediaEngine::new().plan(&info, &opts).unwrap();
2255        let args = build_pass_args(&plan, PassKind::Second, "/tmp/passlog", enc(&plan), false);
2256        let joined: Vec<String> = args
2257            .iter()
2258            .map(|a| a.to_string_lossy().into_owned())
2259            .collect();
2260        assert!(joined.contains(&"hvc1".to_string()));
2261        assert!(joined.contains(&"libx265".to_string()));
2262    }
2263}