deepshrink_core/engine/mod.rs
1//! The compression engine contract and shared types.
2//!
3//! Key architectural decision: `core` is designed around the [`Engine`]
4//! interface even while there is exactly one engine (media/ffmpeg). This lets us
5//! plug in images/PDF/office later without rewriting the skeleton.
6//!
7//! Principle: [`Engine::plan`] is a pure, testable function (bitrate math);
8//! side effects are isolated in [`Engine::run`].
9
10pub mod media;
11
12use std::path::{Path, PathBuf};
13use thiserror::Error;
14
15use crate::detect::MediaKind;
16use crate::options::{AudioChoice, AudioCodec, FpsOpt, QualityPreset, ResolutionOpt, VideoCodec};
17use crate::size::Preset;
18
19/// Source file metadata — the result of [`Engine::probe`].
20#[derive(Debug, Clone, PartialEq)]
21pub struct MediaInfo {
22 pub path: PathBuf,
23 pub kind: MediaKind,
24 pub duration_sec: f64,
25 pub size_bytes: u64,
26 pub width: Option<u32>,
27 pub height: Option<u32>,
28 pub fps: Option<f64>,
29 pub video_codec: Option<String>,
30 pub audio_codec: Option<String>,
31 pub audio_channels: Option<u32>,
32}
33
34impl MediaInfo {
35 /// Whether the source carries an audio track.
36 pub fn has_audio(&self) -> bool {
37 self.audio_codec.is_some()
38 }
39}
40
41/// What the user wants in terms of size.
42#[derive(Debug, Clone, PartialEq)]
43pub enum SizeGoal {
44 /// Fit into an absolute size (bytes).
45 Target(u64),
46 /// Reduce by a fraction of the original (0.70 = "by 70%").
47 Reduce(f64),
48 /// Platform preset (sets the target size).
49 Preset(Preset),
50 /// Smart, quality-preserving shrink without a hard limit.
51 Quality,
52}
53
54/// Compression options passed to the engine — the decoded form of the flags.
55#[derive(Debug, Clone, PartialEq)]
56pub struct ShrinkOpts {
57 pub goal: SizeGoal,
58 pub video_codec: VideoCodec,
59 /// What to do with the audio track *inside a video*.
60 pub audio: AudioChoice,
61 pub resolution: ResolutionOpt,
62 pub fps: FpsOpt,
63 pub quality: QualityPreset,
64 /// Codec for a *pure-audio* input.
65 pub audio_codec: AudioCodec,
66 /// Downmix pure audio to mono.
67 pub mono: bool,
68 /// Force a sample rate (Hz) for pure audio; `None` keeps the source rate.
69 pub sample_rate: Option<u32>,
70 /// Prefer VBR where the codec supports it.
71 pub vbr: bool,
72 /// Target VMAF: in quality mode, search CRF for the smallest output that
73 /// still scores at least this. `None` disables VMAF-aware encoding.
74 pub target_vmaf: Option<f64>,
75 /// Explicit output path; when `None` the engine derives one.
76 pub output: Option<PathBuf>,
77}
78
79impl Default for ShrinkOpts {
80 fn default() -> Self {
81 Self {
82 goal: SizeGoal::Quality,
83 video_codec: VideoCodec::H264,
84 audio: AudioChoice::Keep,
85 resolution: ResolutionOpt::Auto,
86 fps: FpsOpt::Auto,
87 quality: QualityPreset::Balanced,
88 audio_codec: AudioCodec::Aac,
89 mono: false,
90 sample_rate: None,
91 vbr: false,
92 target_vmaf: None,
93 output: None,
94 }
95 }
96}
97
98/// Video encoding parameters.
99#[derive(Debug, Clone, PartialEq)]
100pub struct VideoSpec {
101 pub codec: VideoCodec,
102 /// Target average bitrate (bits/s) for two-pass; `None` in CRF/quality mode.
103 pub bitrate_bps: Option<u64>,
104 /// CRF value for quality mode; `None` in bitrate mode.
105 pub crf: Option<u8>,
106 /// Downscale target height; `None` keeps the source resolution.
107 pub height: Option<u32>,
108 /// Frame-rate cap; `None` keeps the source rate.
109 pub fps: Option<u32>,
110 pub preset: QualityPreset,
111}
112
113/// Audio encoding parameters (absent means drop the track).
114#[derive(Debug, Clone, PartialEq)]
115pub struct AudioSpec {
116 pub codec: AudioCodec,
117 pub bitrate_bps: u64,
118 /// Downmix to a single channel.
119 pub mono: bool,
120 /// Resample to this rate (Hz); `None` keeps the source rate.
121 pub sample_rate: Option<u32>,
122 /// Prefer VBR where the codec supports it.
123 pub vbr: bool,
124}
125
126impl AudioSpec {
127 /// A plain CBR/ABR track (used for the audio track inside a video).
128 pub fn cbr(codec: AudioCodec, bitrate_bps: u64) -> Self {
129 Self {
130 codec,
131 bitrate_bps,
132 mono: false,
133 sample_rate: None,
134 vbr: false,
135 }
136 }
137}
138
139/// The full encode recipe.
140#[derive(Debug, Clone, PartialEq)]
141pub struct EncodeSpec {
142 pub video: VideoSpec,
143 /// `None` means `-an` (no audio).
144 pub audio: Option<AudioSpec>,
145 pub faststart: bool,
146 pub two_pass: bool,
147 /// Stream-copy remux only: the source already fits, so never re-encode
148 /// (and never inflate). `video`/`audio` are ignored when set.
149 pub passthrough: bool,
150 /// Pure-audio encode: emit `-vn` and use `audio` only (`video` is ignored).
151 pub audio_only: bool,
152}
153
154/// The encode plan — the result of [`Engine::plan`]. Usable for `--dry-run`.
155#[derive(Debug, Clone, PartialEq)]
156pub struct EncodePlan {
157 pub input: PathBuf,
158 pub output: PathBuf,
159 /// Human-readable description of the plan (codec, bitrates, passes).
160 pub summary: String,
161 /// Expected final size in bytes, if predictable.
162 pub expected_bytes: Option<u64>,
163 /// The hard size cap, if any (drives the post-encode correction retry).
164 pub target_bytes: Option<u64>,
165 /// Target VMAF for a CRF search, if requested (quality mode only).
166 pub target_vmaf: Option<f64>,
167 /// Source duration in seconds (for progress reporting).
168 pub source_duration_sec: f64,
169 /// Source resolution and frame rate — the reference for VMAF measurement.
170 pub source_width: Option<u32>,
171 pub source_height: Option<u32>,
172 pub source_fps: Option<f64>,
173 pub spec: EncodeSpec,
174}
175
176/// The execution result — the result of [`Engine::run`].
177#[derive(Debug, Clone, PartialEq)]
178pub struct Outcome {
179 pub output: PathBuf,
180 pub final_bytes: u64,
181 /// Measured VMAF of the result vs the source, if a measurement was taken.
182 pub vmaf: Option<f64>,
183}
184
185/// Engine errors.
186#[derive(Debug, Error)]
187pub enum EngineError {
188 #[error("input not supported by this engine: {0}")]
189 Unsupported(String),
190 #[error("cannot reach target size at a reasonable quality")]
191 Infeasible,
192 #[error("not yet implemented: {0}")]
193 NotImplemented(&'static str),
194 #[error(transparent)]
195 Ffmpeg(#[from] deepshrink_ffmpeg::FfmpegError),
196 #[error(transparent)]
197 Io(#[from] std::io::Error),
198}
199
200/// The compression engine contract. The one v0.1 implementation is [`media::MediaEngine`].
201pub trait Engine {
202 /// Whether this engine handles the given file.
203 fn supports(&self, input: &Path) -> bool;
204 /// Read metadata (side effect: run a probe, e.g. ffprobe).
205 fn probe(&self, input: &Path) -> Result<MediaInfo, EngineError>;
206 /// Build the encode plan. Pure function — tested without encoding.
207 fn plan(&self, info: &MediaInfo, opts: &ShrinkOpts) -> Result<EncodePlan, EngineError>;
208 /// Execute the plan (side effect: run the encoder binary).
209 fn run(&self, plan: &EncodePlan) -> Result<Outcome, EngineError>;
210}