oximedia-cli 0.1.8

Command-line interface for OxiMedia
Documentation
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
//! FFmpeg-compatible command handler.
//!
//! Accepts raw FFmpeg-style arguments, passes them through the
//! `oximedia-compat-ffmpeg` translation layer, prints any diagnostics,
//! and then executes each resulting transcode job by delegating to the
//! native `transcode` module.

use anyhow::{Context, Result};
use colored::Colorize;
use oximedia_compat_ffmpeg::{parse_and_translate, DiagnosticKind, ParsedFilter, TranscodeJob};
use std::path::PathBuf;
use tracing::warn;

use crate::progress::ProgressFormat;
use crate::transcode::{self, TranscodeOptions};

// ─────────────────────────────────────────────────────────────────────────────
// Public entry point
// ─────────────────────────────────────────────────────────────────────────────

/// Run the FFmpeg-compatible command with the provided argument list.
///
/// The `dry_run` flag suppresses actual execution and only prints the plan.
/// The `--explain` flag prints a human-readable translation table then exits.
pub async fn run(args: Vec<String>) -> Result<()> {
    if args.is_empty() {
        print_ffcompat_help();
        return Ok(());
    }

    // Check for --explain anywhere in args (OxiMedia extension).
    let explain_mode = args.iter().any(|a| a == "--explain");

    // Check for --dry-run / --plan anywhere in args (OxiMedia extension).
    // We remove it before passing to the compat parser so it doesn't confuse
    // the FFmpeg arg parser.
    let dry_run = args
        .iter()
        .any(|a| a == "--dry-run" || a == "--plan" || a == "-dry-run");

    let filtered_args: Vec<String> = args
        .into_iter()
        .filter(|a| a != "--dry-run" && a != "--plan" && a != "-dry-run" && a != "--explain")
        .collect();

    let result = parse_and_translate(&filtered_args);

    // Print diagnostics to stderr using FFmpeg-style formatting.
    for diag in &result.diagnostics {
        match &diag.kind {
            DiagnosticKind::PatentCodecSubstituted { from, to } => {
                eprintln!(
                    "{} Codec '{}' is a patent codec. Using '{}' instead.",
                    "warning:".yellow().bold(),
                    from,
                    to
                );
            }
            DiagnosticKind::UnknownOptionIgnored { option } => {
                eprintln!(
                    "{} Option '{}' not supported. Ignoring.",
                    "warning:".yellow().bold(),
                    option
                );
            }
            DiagnosticKind::FilterNotSupported { filter } => {
                eprintln!(
                    "{} Filter '{}' not supported. Skipping.",
                    "warning:".yellow().bold(),
                    filter
                );
            }
            DiagnosticKind::UnsupportedFeature { description } => {
                eprintln!("{} {}.", "warning:".yellow().bold(), description);
            }
            DiagnosticKind::Info { message } => {
                println!("{} {}", "info:".cyan(), message);
            }
            DiagnosticKind::Error { message } => {
                eprintln!("{} {}", "error:".red().bold(), message);
                if let Some(hint) = &diag.suggestion {
                    eprintln!("  {} {}", "hint:".yellow(), hint);
                }
            }
            DiagnosticKind::Warning { message } => {
                eprintln!("{} {}", "warning:".yellow().bold(), message);
                if let Some(hint) = &diag.suggestion {
                    eprintln!("  {} {}", "hint:".cyan(), hint);
                }
            }
        }
    }

    if result.has_errors() {
        anyhow::bail!("translation failed with errors; see diagnostics above");
    }

    // --explain: print the full argument → field translation table and exit.
    if explain_mode {
        print_explain_table(&result.jobs);
        return Ok(());
    }

    // Print the translated jobs summary.
    println!(
        "\n{} {} transcode job(s) translated from FFmpeg arguments:",
        "âś“".green(),
        result.jobs.len()
    );

    for (idx, job) in result.jobs.iter().enumerate() {
        println!("\n{} Job {}:", "─".repeat(4).dimmed(), idx + 1);
        println!("  input:  {}", job.input_path.cyan());
        println!("  output: {}", job.output_path.cyan());

        if let Some(vc) = &job.video_codec {
            println!("  video codec: {}", vc.green());
        }
        if let Some(ac) = &job.audio_codec {
            println!("  audio codec: {}", ac.green());
        }
        if let Some(vb) = &job.video_bitrate {
            println!("  video bitrate: {}", vb);
        }
        if let Some(ab) = &job.audio_bitrate {
            println!("  audio bitrate: {}", ab);
        }
        if let Some(crf) = job.crf {
            println!("  crf: {:.1}", crf);
        }
        if !job.video_filters.is_empty() {
            println!("  video filters: {} filter(s)", job.video_filters.len());
        }
        if !job.audio_filters.is_empty() {
            println!("  audio filters: {} filter(s)", job.audio_filters.len());
        }
        if let Some(seek) = &job.seek {
            println!("  seek: {}", seek);
        }
        if let Some(dur) = &job.duration {
            println!("  duration: {}", dur);
        }
        if !job.metadata.is_empty() {
            for (k, v) in &job.metadata {
                println!("  metadata: {}={}", k, v);
            }
        }
        if job.no_video {
            println!("  {}", "no video".dimmed());
        }
        if job.no_audio {
            println!("  {}", "no audio".dimmed());
        }
        if job.overwrite {
            println!("  overwrite: yes");
        }
        if !job.map.is_empty() {
            println!("  map: {} stream selector(s)", job.map.len());
        }

        if dry_run {
            println!("  {}", "[dry-run: skipping execution]".yellow().italic());
        }
    }

    if dry_run {
        println!("\n{} Dry-run mode — no files were written.", "note:".cyan());
        return Ok(());
    }

    // Execute each job.
    for (idx, job) in result.jobs.iter().enumerate() {
        eprintln!(
            "\n{} Executing job {}/{}: {} → {}",
            "oximedia-ff:".green().bold(),
            idx + 1,
            result.jobs.len(),
            job.input_path.cyan(),
            job.output_path.cyan()
        );

        execute_job(job).await.with_context(|| {
            format!(
                "job {} failed: {} → {}",
                idx + 1,
                job.input_path,
                job.output_path
            )
        })?;
    }

    Ok(())
}

// ─────────────────────────────────────────────────────────────────────────────
// Job execution
// ─────────────────────────────────────────────────────────────────────────────

/// Execute a single [`TranscodeJob`] by mapping its fields onto [`TranscodeOptions`]
/// and delegating to the native `transcode::transcode` function.
async fn execute_job(job: &TranscodeJob) -> Result<()> {
    // Overwrite guard — honour the job flag.
    if !job.overwrite && std::path::Path::new(&job.output_path).exists() {
        anyhow::bail!(
            "Output file '{}' already exists. Pass -y to overwrite.",
            job.output_path
        );
    }

    // Build filter strings for both video and audio filter chains.
    let vf_string = build_filter_string(&job.video_filters);
    let af_string = build_filter_string(&job.audio_filters);

    // Extract a scale dimension from video_filters if a Scale filter is present.
    // This populates the `scale` field of TranscodeOptions.
    let scale_from_filters = extract_scale_filter(&job.video_filters);

    // Resolve the effective video codec string.
    // A value of "copy" means stream copy — pass it through as-is; the
    // transcode module will not encode those streams.
    let video_codec = match job.video_codec.as_deref() {
        Some("copy") | None if job.no_video => None,
        Some(vc) => Some(vc.to_string()),
        None => None,
    };

    let audio_codec = match job.audio_codec.as_deref() {
        Some("copy") | None if job.no_audio => None,
        Some(ac) => Some(ac.to_string()),
        None => None,
    };

    // Convert CRF: TranscodeJob uses f64; TranscodeOptions uses u32.
    let crf = job.crf.map(|c| c.round() as u32);

    let options = TranscodeOptions {
        input: PathBuf::from(&job.input_path),
        output: PathBuf::from(&job.output_path),
        preset_name: None,
        video_codec,
        audio_codec,
        video_bitrate: job.video_bitrate.clone(),
        audio_bitrate: job.audio_bitrate.clone(),
        // Use scale extracted from -vf, falling back to None.
        scale: scale_from_filters,
        video_filter: vf_string,
        audio_filter: af_string,
        start_time: job.seek.clone(),
        duration: job.duration.clone(),
        framerate: None,
        preset: "medium".to_string(),
        two_pass: false,
        crf,
        threads: num_cpus(),
        overwrite: job.overwrite,
        resume: false,
        progress_format: ProgressFormat::Plain,
    };

    transcode::transcode(options).await
}

// ─────────────────────────────────────────────────────────────────────────────
// Filter helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Reconstruct an FFmpeg-style filter string from a slice of [`ParsedFilter`] values.
///
/// Passthrough and Unknown filters are dropped (with a warning for Unknown).
fn build_filter_string(filters: &[ParsedFilter]) -> Option<String> {
    let parts: Vec<String> = filters
        .iter()
        .filter_map(|f| match f {
            ParsedFilter::Scale { w, h } => Some(format!("scale={}:{}", w, h)),
            ParsedFilter::Fps { rate } => Some(format!("fps={}", rate)),
            ParsedFilter::HFlip => Some("hflip".to_string()),
            ParsedFilter::VFlip => Some("vflip".to_string()),
            ParsedFilter::Deinterlace => Some("yadif".to_string()),
            ParsedFilter::Rotate { angle } => Some(format!("rotate={}", angle)),
            ParsedFilter::Crop { w, h, x, y } => Some(format!("crop={}:{}:{}:{}", w, h, x, y)),
            ParsedFilter::ColorCorrect {
                brightness,
                contrast,
                saturation,
            } => Some(format!(
                "eq=brightness={}:contrast={}:saturation={}",
                brightness, contrast, saturation
            )),
            ParsedFilter::Lut3d { file } => Some(format!("lut3d=file={}", file)),
            ParsedFilter::SubtitleBurnIn { file } => Some(format!("subtitles=filename={}", file)),
            ParsedFilter::LoudNorm {
                integrated,
                true_peak,
                lra,
            } => Some(format!(
                "loudnorm=I={}:TP={}:LRA={}",
                integrated, true_peak, lra
            )),
            ParsedFilter::Volume { factor } => Some(format!("volume={}", factor)),
            ParsedFilter::Resample { sample_rate } => Some(format!("aresample={}", sample_rate)),
            ParsedFilter::Compressor { threshold, ratio } => Some(format!(
                "acompressor=threshold={}:ratio={}",
                threshold, ratio
            )),
            ParsedFilter::Passthrough => None,
            ParsedFilter::Unknown { name, args } => {
                warn!(
                    "Skipping unsupported filter '{}' (args: '{}') during execution.",
                    name, args
                );
                eprintln!(
                    "{} Skipping unsupported filter '{}' during execution.",
                    "warning:".yellow().bold(),
                    name
                );
                None
            }
        })
        .collect();

    if parts.is_empty() {
        None
    } else {
        Some(parts.join(","))
    }
}

/// Extract the first `Scale` filter from a filter list and return it as a
/// `"W:H"` string suitable for `TranscodeOptions::scale`.
///
/// `-1` dimension values are rendered as `"-1"` (keep-aspect).
fn extract_scale_filter(filters: &[ParsedFilter]) -> Option<String> {
    filters.iter().find_map(|f| {
        if let ParsedFilter::Scale { w, h } = f {
            Some(format!("{}:{}", w, h))
        } else {
            None
        }
    })
}

// ─────────────────────────────────────────────────────────────────────────────
// Platform helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Return a reasonable default thread count for the current machine.
fn num_cpus() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4)
}

// ─────────────────────────────────────────────────────────────────────────────
// Help text
// ─────────────────────────────────────────────────────────────────────────────

// ─────────────────────────────────────────────────────────────────────────────
// Explain mode
// ─────────────────────────────────────────────────────────────────────────────

/// Print a human-readable translation table: `arg → field = value`.
///
/// This is the `--explain` mode — it shows exactly what each FFmpeg argument
/// mapped to in the OxiMedia transcode model, then returns without executing.
fn print_explain_table(jobs: &[TranscodeJob]) {
    println!(
        "{} Translation table (--explain mode):",
        "oximedia-ff:".cyan().bold()
    );
    println!();

    for (idx, job) in jobs.iter().enumerate() {
        println!("{} Job {} of {}", "──".dimmed(), idx + 1, jobs.len());
        println!("  {:20} = {}", "-i".yellow(), job.input_path);
        println!("  {:20} = {}", "<output>".yellow(), job.output_path);

        if let Some(vc) = &job.video_codec {
            println!("  {:20} = {}", "-c:v".yellow(), vc);
        }
        if let Some(ac) = &job.audio_codec {
            println!("  {:20} = {}", "-c:a".yellow(), ac);
        }
        if let Some(vb) = &job.video_bitrate {
            println!("  {:20} = {}", "-b:v".yellow(), vb);
        }
        if let Some(ab) = &job.audio_bitrate {
            println!("  {:20} = {}", "-b:a".yellow(), ab);
        }
        if let Some(crf) = job.crf {
            println!("  {:20} = {:.1}", "-crf".yellow(), crf);
        }
        if !job.video_filters.is_empty() {
            println!(
                "  {:20} = {} filter(s)",
                "-vf".yellow(),
                job.video_filters.len()
            );
        }
        if !job.audio_filters.is_empty() {
            println!(
                "  {:20} = {} filter(s)",
                "-af".yellow(),
                job.audio_filters.len()
            );
        }
        if let Some(seek) = &job.seek {
            println!("  {:20} = {}", "-ss".yellow(), seek);
        }
        if let Some(dur) = &job.duration {
            println!("  {:20} = {}", "-t".yellow(), dur);
        }
        if let Some(fmt) = &job.format {
            println!("  {:20} = {}", "-f".yellow(), fmt);
        }
        if let Some(preset) = &job.preset {
            println!("  {:20} = {}", "-preset".yellow(), preset);
        }
        if let Some(tune) = &job.tune {
            println!("  {:20} = {}", "-tune".yellow(), tune);
        }
        if let Some(profile) = &job.profile {
            println!("  {:20} = {}", "-profile:v".yellow(), profile);
        }
        if let Some(pass) = job.pass {
            println!("  {:20} = {}", "-pass".yellow(), pass);
        }
        if job.overwrite {
            println!("  {:20} = yes", "-y".yellow());
        }
        if job.no_video {
            println!("  {:20} = yes", "-vn".yellow());
        }
        if job.no_audio {
            println!("  {:20} = yes", "-an".yellow());
        }
        if !job.map.is_empty() {
            println!("  {:20} = {} selector(s)", "-map".yellow(), job.map.len());
        }
        for (k, v) in &job.metadata {
            println!("  {:20} = {}={}", "-metadata".yellow(), k, v);
        }
        if !job.map_metadata.is_empty() {
            println!(
                "  {:20} = {} directive(s)",
                "-map_metadata".yellow(),
                job.map_metadata.len()
            );
        }
        if let Some(hw) = &job.hwaccel {
            println!(
                "  {:20} = {} ({})",
                "-hwaccel".yellow(),
                hw.backend,
                hw.description
            );
        }
        if !job.muxer_options.is_empty() {
            println!(
                "  {:20} = {} option(s)",
                "muxer opts".yellow(),
                job.muxer_options.len()
            );
        }
        println!();
    }

    println!(
        "{} Use --dry-run to also skip execution without the translation details.",
        "note:".cyan()
    );
}

/// Print brief usage information for the ffcompat command.
fn print_ffcompat_help() {
    println!("{}", "OxiMedia FFmpeg-compatible interface".cyan().bold());
    println!();
    println!("Usage:");
    println!("  oximedia ffcompat [FFmpeg arguments...]");
    println!("  oximedia ff [FFmpeg arguments...]");
    println!("  oximedia-ff [FFmpeg arguments...]");
    println!();
    println!("Options (OxiMedia extensions):");
    println!("  --dry-run / --plan    Print what would be done without executing.");
    println!("  --explain             Print the arg→field translation table and exit.");
    println!();
    println!("Examples:");
    println!("  oximedia ff -i input.mkv -c:v libaom-av1 -crf 28 -c:a libopus output.webm");
    println!("  oximedia ff -y -i input.mkv -vf scale=1280:720 -b:v 2M output.webm");
    println!(
        "  oximedia ff -i input.mp4 -c:v libx264 -c:a aac output.webm  # patent codecs auto-substituted"
    );
    println!();
    println!(
        "{}",
        "Note: Only patent-free codecs are supported (AV1, VP9, VP8, Opus, Vorbis, FLAC).".yellow()
    );
    println!(
        "{}",
        "      Patent-encumbered codecs (H.264, AAC, MP3, etc.) are automatically substituted."
            .yellow()
    );
}