Skip to main content

ff_preview/proxy/
mod.rs

1//! Proxy file generation for ff-preview.
2//!
3//! This module is only compiled when the `proxy` feature is enabled.
4//! It provides [`ProxyGenerator`] for generating lower-resolution proxy files
5//! from original media using [`ff_pipeline::Pipeline`] internally.
6
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9use std::sync::atomic::{AtomicU32, Ordering};
10
11use ff_filter::{FilterGraph, ScaleAlgorithm};
12use ff_format::VideoCodec;
13use ff_pipeline::{EncoderConfig, Pipeline, Progress};
14
15use crate::error::PreviewError;
16
17// ── ProxyResolution ───────────────────────────────────────────────────────────
18
19/// Output resolution for a proxy file, expressed as a fraction of the source.
20///
21/// The target dimensions are computed as `(src / divisor) & !1` — divided by
22/// the factor and rounded down to the nearest even number so that video codecs
23/// do not reject odd dimensions.
24///
25/// | Variant   | Divisor | 1920×1080 → |
26/// |-----------|---------|-------------|
27/// | `Half`    | 2       | 960×540     |
28/// | `Quarter` | 4       | 480×270     |
29/// | `Eighth`  | 8       | 240×136     |
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum ProxyResolution {
32    /// 1/2 of the original dimensions (e.g. 1920×1080 → 960×540).
33    Half,
34    /// 1/4 of the original dimensions (e.g. 1920×1080 → 480×270).
35    Quarter,
36    /// 1/8 of the original dimensions (e.g. 1920×1080 → 240×136).
37    Eighth,
38}
39
40impl ProxyResolution {
41    fn divisor(self) -> u32 {
42        match self {
43            Self::Half => 2,
44            Self::Quarter => 4,
45            Self::Eighth => 8,
46        }
47    }
48
49    fn suffix(self) -> &'static str {
50        match self {
51            Self::Half => "half",
52            Self::Quarter => "quarter",
53            Self::Eighth => "eighth",
54        }
55    }
56}
57
58// ── ProxyJob ──────────────────────────────────────────────────────────────────
59
60/// A handle to a running background proxy generation job.
61///
62/// Created by [`ProxyGenerator::generate_async`]. Use
63/// [`progress`](Self::progress) for non-blocking progress polling and
64/// [`wait`](Self::wait) to block until the job completes.
65pub struct ProxyJob {
66    handle: std::thread::JoinHandle<Result<PathBuf, PreviewError>>,
67    /// Stores progress as thousandths (0–1000) so it can be read from any
68    /// thread without a lock. Updated by the background thread's progress
69    /// callback on each encoded frame.
70    progress: Arc<AtomicU32>,
71}
72
73impl ProxyJob {
74    /// Current progress in the range `0.0..=1.0`.
75    ///
76    /// Reads an `AtomicU32` — non-blocking and safe to call from any thread.
77    /// Returns `0.0` when the source container does not report a frame count
78    /// or before the first frame is encoded.
79    #[must_use]
80    pub fn progress(&self) -> f64 {
81        f64::from(self.progress.load(Ordering::Relaxed)) / 1000.0
82    }
83
84    /// Returns `true` if the background thread has finished (success or error).
85    ///
86    /// Non-blocking — does not consume the job.
87    #[must_use]
88    pub fn is_done(&self) -> bool {
89        self.handle.is_finished()
90    }
91
92    /// Block until proxy generation completes and return the output path.
93    ///
94    /// # Errors
95    ///
96    /// Returns [`PreviewError`] if proxy generation failed or if the background
97    /// thread panicked (surfaced as `PreviewError::Ffmpeg { code: 0 }`).
98    pub fn wait(self) -> Result<PathBuf, PreviewError> {
99        self.handle.join().unwrap_or_else(|_| {
100            Err(PreviewError::Ffmpeg {
101                code: 0,
102                message: "proxy thread panicked".to_string(),
103            })
104        })
105    }
106}
107
108// ── ProxyGenerator ────────────────────────────────────────────────────────────
109
110/// Generates a lower-resolution proxy file from an original media file.
111///
112/// Proxy files allow smooth real-time playback of high-resolution footage by
113/// substituting a lower-quality copy during editing. Uses
114/// [`ff_pipeline::Pipeline`] internally — no raw `FFmpeg` calls.
115///
116/// # Usage
117///
118/// ```ignore
119/// let output = ProxyGenerator::new(Path::new("4k_clip.mp4"))?
120///     .resolution(ProxyResolution::Half)
121///     .output_dir(Path::new("/tmp/proxies"))
122///     .generate()?;
123/// ```
124///
125/// # Output path
126///
127/// `{output_dir}/{stem}_proxy_{half|quarter|eighth}.mp4`
128pub struct ProxyGenerator {
129    input: PathBuf,
130    resolution: ProxyResolution,
131    codec: VideoCodec,
132    output_dir: Option<PathBuf>,
133}
134
135impl ProxyGenerator {
136    /// Open the input file and prepare for proxy generation.
137    ///
138    /// Probes `input` to confirm it is a valid media file with a video stream.
139    ///
140    /// # Errors
141    ///
142    /// Returns [`PreviewError`] if the file cannot be probed.
143    pub fn new(input: &Path) -> Result<Self, PreviewError> {
144        ff_probe::open(input)?;
145        Ok(Self {
146            input: input.to_path_buf(),
147            resolution: ProxyResolution::Half,
148            codec: VideoCodec::H264,
149            output_dir: None,
150        })
151    }
152
153    /// Set the output resolution (default: [`ProxyResolution::Half`]).
154    #[must_use]
155    pub fn resolution(self, res: ProxyResolution) -> Self {
156        Self {
157            resolution: res,
158            ..self
159        }
160    }
161
162    /// Set the output video codec (default: [`VideoCodec::H264`]).
163    #[must_use]
164    pub fn codec(self, codec: VideoCodec) -> Self {
165        Self { codec, ..self }
166    }
167
168    /// Set the output directory (default: same directory as the input file).
169    #[must_use]
170    pub fn output_dir(self, dir: &Path) -> Self {
171        Self {
172            output_dir: Some(dir.to_path_buf()),
173            ..self
174        }
175    }
176
177    /// Generate the proxy file synchronously.
178    ///
179    /// Returns the path of the generated proxy file on success.
180    ///
181    /// Dimensions are source ÷ resolution factor, rounded down to the nearest
182    /// even number. Default quality: H.264 CRF 23, AAC audio.
183    ///
184    /// # Errors
185    ///
186    /// Returns [`PreviewError`] if probing, filtering, or encoding fails.
187    pub fn generate(self) -> Result<PathBuf, PreviewError> {
188        self.generate_with_callback(|_| true)
189    }
190
191    /// Start proxy generation on a background thread and return immediately.
192    ///
193    /// The returned [`ProxyJob`] lets you poll progress with
194    /// [`ProxyJob::progress`] or block until completion with
195    /// [`ProxyJob::wait`].
196    ///
197    /// Progress is tracked via `ff-pipeline`'s progress callback: each encoded
198    /// frame updates an `AtomicU32` (thousandths of completion, 0–1000). When
199    /// the source container does not report a total frame count, progress stays
200    /// at `0.0` throughout the run.
201    #[must_use]
202    pub fn generate_async(self) -> ProxyJob {
203        let progress = Arc::new(AtomicU32::new(0));
204        let progress_clone = Arc::clone(&progress);
205        let handle = std::thread::spawn(move || {
206            self.generate_with_callback(move |p: &Progress| {
207                let v = p.total_frames.map_or(0u32, |total| {
208                    match p.frames_processed.saturating_mul(1000).checked_div(total) {
209                        // raw is in 0..=1000 after the saturating division — fits in u32.
210                        Some(raw) => u32::try_from(raw.min(1000)).unwrap_or(1000),
211                        None => 0,
212                    }
213                });
214                progress_clone.store(v, Ordering::Relaxed);
215                true // always continue; cancellation is not supported
216            })
217        });
218        ProxyJob { handle, progress }
219    }
220
221    /// Shared pipeline setup used by both [`generate`](Self::generate) and
222    /// [`generate_async`](Self::generate_async).
223    fn generate_with_callback<F>(self, callback: F) -> Result<PathBuf, PreviewError>
224    where
225        F: Fn(&Progress) -> bool + Send + 'static,
226    {
227        let info = ff_probe::open(&self.input)?;
228
229        let (src_w, src_h) = info
230            .resolution()
231            .ok_or_else(|| PreviewError::NoVideoStream {
232                path: self.input.clone(),
233            })?;
234
235        let divisor = self.resolution.divisor();
236        // Round down to the nearest even number so codecs don't reject odd dimensions.
237        let dst_w = (src_w / divisor) & !1;
238        let dst_h = (src_h / divisor) & !1;
239
240        let output_dir = self
241            .output_dir
242            .as_deref()
243            .or_else(|| self.input.parent())
244            .unwrap_or_else(|| Path::new("."));
245
246        let stem = self
247            .input
248            .file_stem()
249            .and_then(|s| s.to_str())
250            .unwrap_or("output");
251
252        let filename = format!("{stem}_proxy_{}.mp4", self.resolution.suffix());
253        let output_path = output_dir.join(&filename);
254
255        log::debug!(
256            "generating proxy input={} output={} src={}x{} dst={}x{}",
257            self.input.display(),
258            output_path.display(),
259            src_w,
260            src_h,
261            dst_w,
262            dst_h
263        );
264
265        // TODO(#385): EncoderConfig has no preset field; add preset=fast when supported.
266        // FilterGraph::build() returns FilterError; convert via PipelineError since
267        // PreviewError only wraps PipelineError (not FilterError directly).
268        let filter = FilterGraph::builder()
269            .scale(dst_w, dst_h, ScaleAlgorithm::Fast)
270            .build()
271            .map_err(ff_pipeline::PipelineError::from)?;
272
273        let config = EncoderConfig::builder()
274            .video_codec(self.codec)
275            // Defaults: CRF 23, AAC audio — matches issue spec.
276            .build();
277
278        let input_str = self.input.to_string_lossy();
279        let output_str = output_path.to_string_lossy();
280
281        Pipeline::builder()
282            .input(input_str.as_ref())
283            .filter(filter)
284            .output(output_str.as_ref(), config)
285            .on_progress(callback)
286            .build()?
287            .run()?;
288
289        Ok(output_path)
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn proxy_resolution_half_should_have_divisor_2() {
299        assert_eq!(ProxyResolution::Half.divisor(), 2);
300        assert_eq!(ProxyResolution::Half.suffix(), "half");
301    }
302
303    #[test]
304    fn proxy_resolution_quarter_should_have_divisor_4() {
305        assert_eq!(ProxyResolution::Quarter.divisor(), 4);
306        assert_eq!(ProxyResolution::Quarter.suffix(), "quarter");
307    }
308
309    #[test]
310    fn proxy_resolution_eighth_should_have_divisor_8() {
311        assert_eq!(ProxyResolution::Eighth.divisor(), 8);
312        assert_eq!(ProxyResolution::Eighth.suffix(), "eighth");
313    }
314
315    #[test]
316    fn proxy_resolution_dimension_should_round_to_even() {
317        // 1079 / 2 = 539 → & !1 = 538 (rounded down to even)
318        let odd: u32 = 1079;
319        let result = (odd / 2) & !1;
320        assert_eq!(result, 538, "odd dimension must be rounded down to even");
321        assert_eq!(result % 2, 0, "result must be even");
322
323        // Even input stays even.
324        let even: u32 = 1080;
325        let result_even = (even / 2) & !1;
326        assert_eq!(result_even, 540);
327
328        // 1/8 of 1920 = 240 (already even).
329        let result_eighth = (1920_u32 / 8) & !1;
330        assert_eq!(result_eighth, 240);
331    }
332
333    #[test]
334    fn proxy_generator_new_should_fail_for_nonexistent_file() {
335        let result = ProxyGenerator::new(Path::new("nonexistent_proxy_test.mp4"));
336        assert!(result.is_err(), "new() must fail for a non-existent file");
337    }
338
339    #[test]
340    fn proxy_job_progress_scaling_should_convert_thousandths_to_fraction() {
341        // The internal atomic stores thousandths (0–1000).
342        // Verify the scaling formula: raw / 1000.0 = fraction.
343        for (raw, expected) in [(0u32, 0.0f64), (500, 0.5), (1000, 1.0), (250, 0.25)] {
344            let frac = f64::from(raw) / 1000.0;
345            assert!(
346                (frac - expected).abs() < f64::EPSILON,
347                "raw={raw} expected={expected} got={frac}"
348            );
349        }
350    }
351
352    #[test]
353    #[ignore = "requires FFmpeg and assets/video/gameplay.mp4; run with -- --include-ignored"]
354    fn proxy_generate_async_should_complete_and_produce_output_file() {
355        let input = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
356            .join("../../assets/video/gameplay.mp4");
357        if !input.exists() {
358            println!("skipping: gameplay.mp4 not found");
359            return;
360        }
361        let tmp = std::env::temp_dir();
362        let job = match ProxyGenerator::new(&input) {
363            Ok(g) => g
364                .resolution(ProxyResolution::Quarter)
365                .output_dir(&tmp)
366                .generate_async(),
367            Err(e) => {
368                println!("skipping: {e}");
369                return;
370            }
371        };
372        match job.wait() {
373            Ok(path) => {
374                assert!(path.exists(), "proxy output file must exist");
375                assert!(
376                    path.to_str()
377                        .map(|s| s.contains("_proxy_quarter"))
378                        .unwrap_or(false),
379                    "output path must contain '_proxy_quarter'"
380                );
381                let _ = std::fs::remove_file(&path);
382            }
383            Err(e) => println!("skipping: generate_async failed: {e}"),
384        }
385    }
386
387    #[test]
388    #[ignore = "requires FFmpeg and assets/video/gameplay.mp4; run with -- --include-ignored"]
389    fn proxy_generator_half_resolution_should_produce_output_file() {
390        let input = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
391            .join("../../assets/video/gameplay.mp4");
392        if !input.exists() {
393            println!("skipping: gameplay.mp4 not found");
394            return;
395        }
396        let tmp = std::env::temp_dir();
397        let result = ProxyGenerator::new(&input)
398            .unwrap()
399            .resolution(ProxyResolution::Half)
400            .output_dir(&tmp)
401            .generate();
402        match result {
403            Ok(path) => {
404                assert!(path.exists(), "proxy output file must exist");
405                assert!(
406                    path.to_str()
407                        .map(|s| s.contains("_proxy_half"))
408                        .unwrap_or(false),
409                    "output path must contain '_proxy_half'"
410                );
411                let _ = std::fs::remove_file(&path);
412            }
413            Err(e) => println!("skipping: proxy generation failed: {e}"),
414        }
415    }
416}