1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum ProxyResolution {
32 Half,
34 Quarter,
36 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
58pub struct ProxyJob {
66 handle: std::thread::JoinHandle<Result<PathBuf, PreviewError>>,
67 progress: Arc<AtomicU32>,
71}
72
73impl ProxyJob {
74 #[must_use]
80 pub fn progress(&self) -> f64 {
81 f64::from(self.progress.load(Ordering::Relaxed)) / 1000.0
82 }
83
84 #[must_use]
88 pub fn is_done(&self) -> bool {
89 self.handle.is_finished()
90 }
91
92 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
108pub struct ProxyGenerator {
129 input: PathBuf,
130 resolution: ProxyResolution,
131 codec: VideoCodec,
132 output_dir: Option<PathBuf>,
133}
134
135impl ProxyGenerator {
136 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 #[must_use]
155 pub fn resolution(self, res: ProxyResolution) -> Self {
156 Self {
157 resolution: res,
158 ..self
159 }
160 }
161
162 #[must_use]
164 pub fn codec(self, codec: VideoCodec) -> Self {
165 Self { codec, ..self }
166 }
167
168 #[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 pub fn generate(self) -> Result<PathBuf, PreviewError> {
188 self.generate_with_callback(|_| true)
189 }
190
191 #[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 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 })
217 });
218 ProxyJob { handle, progress }
219 }
220
221 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 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 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 .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 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 let even: u32 = 1080;
325 let result_even = (even / 2) & !1;
326 assert_eq!(result_even, 540);
327
328 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 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}