shrivel 0.4.0

Cross-platform FFmpeg orchestrator that transcodes videos to HEVC or AV1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Processing and FFmpeg execution for an individual input file.

use std::fs;
use std::path::Path;
use std::process::{Command, Stdio};

use owo_colors::OwoColorize;

use crate::cli::{AudioCodec, Codec};
use crate::encoder::Encoder;
use crate::job::{self, Plan};
use crate::probe::{self, DurationOrigin, VideoInfo};
use crate::progress::ProgressBars;

const MAX_ERROR_LINES: usize = 15;
pub(super) const BYTES_PER_MB: f64 = 1024.0 * 1024.0;

/// Estimates the output size in bytes based on the source bitrate, CQ, codec, and transformations.
///
/// This is a rough heuristic: we assume a linear-ish relationship where
/// a CQ of 26 roughly preserves the source bitrate for modern codecs,
/// and deviations from 26 scale the bitrate.
pub fn estimate_output_size(
    input_bytes: u64,
    source_bitrate_kbps: u32,
    cq: u8,
    codec: Codec,
    source_width: u32,
    target_width: Option<u32>,
    source_fps: f64,
    target_fps: Option<f64>,
) -> u64 {
    if source_bitrate_kbps == 0 {
        return input_bytes; // Fallback if bitrate is unknown
    }

    // Base CQ is 26.
    // Every point above 26 (lower quality) reduces bitrate.
    // Every point below 26 (higher quality) increases bitrate.
    // Heuristic: +/- 1 CQ point ~= 10% change in bitrate.
    let diff = cq as i16 - 26;
    let cq_factor = (1.0 - (diff as f64 * 0.1)).clamp(0.1, 5.0);

    // Codec-specific coefficients based on partial real-world test data.
    let codec_factor = match codec {
        Codec::Hevc => 0.8,
        Codec::Av1 => 0.6,
    };

    // Resolution factor: area is proportional to width^2 (assuming constant aspect ratio).
    let scale_factor = match target_width {
        Some(tw) if source_width > 0 => (tw as f64 / source_width as f64).powi(2),
        _ => 1.0,
    };

    // FPS factor: linear relationship.
    let fps_factor = match target_fps {
        Some(tf) if source_fps > 0.0 => tf / source_fps,
        _ => 1.0,
    };

    // Global correction factor: we've observed that for low-res/fps conversions,
    // the actual bitrate doesn't drop as much as the math suggests due to a "base bitrate".
    let correction = 2.0;

    (input_bytes as f64 * cq_factor * codec_factor * scale_factor * fps_factor * correction) as u64
}

/// Settings that stay constant for the whole batch.
pub(super) struct Settings {
    pub(super) codec: Codec,
    pub(super) encoder: Encoder,
    pub(super) cq: u8,
    pub(super) audio_codec: AudioCodec,
    pub(super) no_audio: bool,
    pub(super) dynamic_cq: bool,
    pub(super) target_fps: Option<f64>,
    pub(super) denoise: bool,
    pub(super) skip_same_codec: bool,
    pub(super) skip_existing: bool,
    pub(super) scale: Option<u32>,
    pub(super) dry_run: bool,
}

/// What happened to a single file.
pub(super) enum Outcome {
    Converted { input_bytes: u64, output_bytes: u64 },
    Skipped,
    Failed,
}

/// Buffers each file's output so its metadata and result remain together.
struct FileLog<'a> {
    progress: &'a ProgressBars,
    lines: Vec<String>,
}

impl<'a> FileLog<'a> {
    fn new(progress: &'a ProgressBars) -> Self {
        Self {
            progress,
            lines: Vec::new(),
        }
    }

    fn println(&mut self, message: impl Into<String>) {
        self.lines.push(message.into());
    }
}

impl Drop for FileLog<'_> {
    fn drop(&mut self) {
        if !self.lines.is_empty() {
            self.progress.println(self.lines.join("\n"));
        }
    }
}

/// Converts one file and reports the result on the terminal.
pub(super) fn convert_one(
    settings: &Settings,
    input: &Path,
    input_root: &Path,
    output_dir: &Path,
    progress: &ProgressBars,
    file_name: &std::borrow::Cow<'_, str>,
) -> Outcome {
    let mut log = FileLog::new(progress);
    let output = match output_path(input, input_root, output_dir) {
        Some(path) => path,
        None => {
            log.println(format!(
                "     {} cannot determine path relative to input",
                "[ERR]".red()
            ));
            return Outcome::Failed;
        }
    };

    if !settings.dry_run
        && let Some(parent) = output.parent()
        && let Err(err) = fs::create_dir_all(parent)
    {
        log.println(format!(
            "     {} cannot create output directory {}: {err}",
            "[ERR]".red(),
            parent.display()
        ));
        return Outcome::Failed;
    }

    log.println(format!("\n{} {}", "[>>]".cyan(), file_name.cyan()));

    let info = match probe::probe(input) {
        Ok(info) => info,
        Err(err) => {
            log.println(format!("     {} {err:#}", "[ERR]".red()));
            return Outcome::Failed;
        }
    };
    log.println(
        format!(
            "     Codec: {} | Bitrate: {} kbps | FPS: {} | Duration: {:.1}s",
            info.codec, info.bitrate_kbps, info.fps, info.duration
        )
        .bright_black()
        .to_string(),
    );

    let target_codec_name = match settings.codec {
        Codec::Hevc => "hevc",
        Codec::Av1 => "av1",
    };
    if settings.skip_same_codec && info.codec == target_codec_name {
        log.println(format!(
            "     {}",
            format!("[SKIP] Already {target_codec_name}.").yellow()
        ));
        return Outcome::Skipped;
    }
    if settings.skip_existing && output.exists() {
        log.println(format!("     {}", "[SKIP] Output already exists.".yellow()));
        return Outcome::Skipped;
    }

    let mut cq = settings.cq;
    if settings.dynamic_cq {
        cq = job::calculate_cq(settings.cq, info.bitrate_kbps);
    }
    log.println(
        format!(
            "     CQ: {cq} (normalized){}",
            if settings.dynamic_cq && cq != settings.cq {
                format!(" (dynamic: {} -> {})", settings.cq, cq)
                    .bright_black()
                    .to_string()
            } else {
                "".to_string()
            }
        )
        .bright_black()
        .to_string(),
    );

    let mut filters = Vec::new();
    let mut force_cfr = false;
    if settings.denoise {
        filters.push("hqdn3d=3:3:8:8".to_string());
    }
    if let Some(scale) = settings.scale {
        // scale=width:-2 ensures the height is proportional and divisible by 2.
        // We explicitly use bicubic interpolation to ensure consistent behavior.
        filters.push(format!("scale={scale}:-2:flags=bicubic"));
    }
    if let Some(target) = settings.target_fps {
        if job::fps_change_needed(info.fps, target) {
            filters.push(format!("fps={target}"));
            // Constant frame rate avoids leftover variable-frame-rate drift.
            force_cfr = true;
            log.println(
                format!("     FPS: {} -> {target}", info.fps)
                    .bright_black()
                    .to_string(),
            );
        } else {
            log.println(
                format!("     FPS: already {}, no change", info.fps)
                    .bright_black()
                    .to_string(),
            );
        }
    }

    let plan = Plan {
        codec: settings.codec,
        encoder: settings.encoder,
        input,
        output: &output,
        cq,
        audio_codec: settings.audio_codec,
        no_audio: settings.no_audio,
        filters,
        force_cfr,
    };
    let args = plan.ffmpeg_args();

    if settings.dry_run {
        let rendered: Vec<String> = args.iter().map(|a| quote(&a.to_string_lossy())).collect();
        log.println(format!(
            "     {} ffmpeg {}",
            "[DRY]".magenta(),
            rendered.join(" ")
        ));

        let input_bytes = fs::metadata(input).map(|m| m.len()).unwrap_or(0);
        let estimated_bytes = estimate_output_size(
            input_bytes,
            info.bitrate_kbps,
            cq,
            settings.codec,
            info.width,
            settings.scale,
            info.fps,
            settings.target_fps,
        );
        log.println(
            format!(
                "     {} estimated size: {:.1} MB -> {:.1} MB",
                "[EST]".bright_black(),
                input_bytes as f64 / BYTES_PER_MB,
                estimated_bytes as f64 / BYTES_PER_MB
            )
            .bright_black()
            .to_string(),
        );

        return Outcome::Converted {
            input_bytes,
            output_bytes: estimated_bytes,
        };
    }

    let mut child = match Command::new("ffmpeg")
        .args(&args)
        .stdin(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(child) => child,
        Err(err) => {
            log.println(format!(
                "     {} could not start ffmpeg: {err}",
                "[ERR]".red()
            ));
            return Outcome::Failed;
        }
    };

    let mut stderr = match child.stderr.take() {
        Some(s) => s,
        None => {
            log.println(format!("     {} failed to take stderr", "[ERR]".red()));
            return Outcome::Failed;
        }
    };
    // Keep a reusable buffer with writable space for each stderr read.
    let mut buffer = [0u8; 8192];
    let mut total_err_output = String::new();
    let mut pending_progress = String::new();

    let file_progress = progress.file(info.duration, file_name);

    use std::io::Read;
    loop {
        let bytes_read = stderr.read(&mut buffer).unwrap_or(0);
        if bytes_read == 0 {
            break;
        }
        let chunk = String::from_utf8_lossy(&buffer[..bytes_read]);
        total_err_output.push_str(&chunk);
        pending_progress.push_str(&chunk);

        // `-progress pipe:2` emits machine-readable `out_time=HH:MM:SS...`
        // lines, independently of FFmpeg's log level.
        while let Some(newline) = pending_progress.find('\n') {
            let line = pending_progress[..newline].trim().to_owned();
            pending_progress.drain(..=newline);
            if let Some(time) = line.strip_prefix("out_time=") {
                if let Some(seconds) = parse_ffmpeg_time(time.trim()) {
                    if let Some(ref p) = file_progress {
                        p.set_seconds(seconds);
                    }
                }
            }
        }
    }

    if let Some(p) = file_progress {
        p.finish();
    }

    let status = match child.wait() {
        Ok(s) => s,
        Err(err) => {
            log.println(format!(
                "     {} failed to wait for ffmpeg: {err}",
                "[ERR]".red()
            ));
            return Outcome::Failed;
        }
    };

    if status.success() {
        // Validate the output duration to catch silent failures or truncated files.
        if let Ok(out_info) = probe::probe(&output) {
            if duration_mismatch(&info, &out_info) {
                log.println(format!(
                    "     {} output duration {:.1}s differs from source {:.1}s, something went wrong",
                    "[ERR]".red(),
                    out_info.duration,
                    info.duration
                ));
                let _ = fs::remove_file(&output);
                return Outcome::Failed;
            }
        } else {
            log.println(format!(
                "     {} could not probe output for validation",
                "[ERR]".red()
            ));
            let _ = fs::remove_file(&output);
            return Outcome::Failed;
        }

        let input_bytes = fs::metadata(input).map(|m| m.len()).unwrap_or(0);
        let output_bytes = fs::metadata(&output).map(|m| m.len()).unwrap_or(0);
        let ratio = if input_bytes > 0 {
            output_bytes as f64 / input_bytes as f64 * 100.0
        } else {
            0.0
        };
        let line = format!(
            "     [OK] {:.1} MB -> {:.1} MB ({:.1}%)",
            input_bytes as f64 / BYTES_PER_MB,
            output_bytes as f64 / BYTES_PER_MB,
            ratio
        );
        if ratio <= 100.0 {
            log.println(line.green().to_string());
        } else {
            log.println(line.yellow().to_string());
        }
        Outcome::Converted {
            input_bytes,
            output_bytes,
        }
    } else {
        log.println(format!("     {}", "[ERR] Conversion failed".red()));
        let lines: Vec<_> = total_err_output.lines().collect();
        for line in lines.iter().rev().take(MAX_ERROR_LINES).rev() {
            log.println(format!("     {}", line.bright_black()));
        }
        let _ = fs::remove_file(&output);
        Outcome::Failed
    }
}

/// Compare durations only when both are valid and describe the same ffprobe scope.
fn duration_mismatch(source: &VideoInfo, output: &VideoInfo) -> bool {
    source.duration_origin != DurationOrigin::Unknown
        && source.duration_origin == output.duration_origin
        && source.duration.is_finite()
        && output.duration.is_finite()
        && source.duration > 0.0
        && output.duration > 0.0
        && (output.duration - source.duration).abs() > 0.5
}

/// Maps an input file to the matching path under the output directory.
pub(super) fn output_path(
    input: &Path,
    input_root: &Path,
    output_root: &Path,
) -> Option<std::path::PathBuf> {
    input
        .strip_prefix(input_root)
        .ok()
        .map(|relative_path| output_root.join(relative_path))
}

fn parse_ffmpeg_time(s: &str) -> Option<f64> {
    let parts: Vec<&str> = s.split(':').collect();
    if parts.len() != 3 {
        return None;
    }
    let h: f64 = parts[0].parse().ok()?;
    let m: f64 = parts[1].parse().ok()?;
    let s: f64 = parts[2].parse().ok()?;
    Some(h * 3600.0 + m * 60.0 + s)
}

/// Quotes an argument for display only, so printed dry-run commands can be
/// pasted into a shell. The command itself is never run through a shell.
pub(super) fn quote(arg: &str) -> String {
    let needs_quotes = arg.is_empty()
        || arg
            .chars()
            .any(|c| c.is_whitespace() || "\"'$&|;<>()*?[]{}!\\`".contains(c));
    if needs_quotes {
        format!("\"{}\"", arg.replace('"', "\\\""))
    } else {
        arg.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::{duration_mismatch, quote};
    use crate::probe::{DurationOrigin, VideoInfo};

    fn info(duration: f64, duration_origin: DurationOrigin) -> VideoInfo {
        VideoInfo {
            codec: String::new(),
            bitrate_kbps: 0,
            fps: 0.0,
            duration,
            duration_origin,
            width: 0,
            height: 0,
        }
    }

    #[test]
    fn quote_leaves_plain_arguments_alone() {
        assert_eq!(quote("-hide_banner"), "-hide_banner");
        assert_eq!(quote("0:a?"), "\"0:a?\"");
    }

    #[test]
    fn quote_wraps_arguments_with_spaces() {
        assert_eq!(quote("my video.mp4"), "\"my video.mp4\"");
        assert_eq!(quote(""), "\"\"");
    }

    #[test]
    fn duration_validation_requires_valid_matching_scopes() {
        let stream_source = info(10.0, DurationOrigin::Stream);
        assert!(!duration_mismatch(
            &stream_source,
            &info(10.6, DurationOrigin::Format)
        ));
        assert!(!duration_mismatch(
            &stream_source,
            &info(0.0, DurationOrigin::Unknown)
        ));
        assert!(!duration_mismatch(
            &info(0.0, DurationOrigin::Unknown),
            &info(20.0, DurationOrigin::Stream)
        ));
        assert!(duration_mismatch(
            &stream_source,
            &info(10.6, DurationOrigin::Stream)
        ));
        assert!(!duration_mismatch(
            &stream_source,
            &info(10.5, DurationOrigin::Stream)
        ));
    }
}