oximedia-cli 0.1.7

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
//! Quality Control command.
//!
//! Provides `oximedia qc` for running quality control checks, validation,
//! and auto-fix on media files using `oximedia-qc`.

use anyhow::{Context, Result};
use clap::Subcommand;
use colored::Colorize;
use std::path::PathBuf;

/// QC subcommands.
#[derive(Subcommand)]
pub enum QcCommand {
    /// Run QC checks on a media file
    Check {
        /// Input media file
        #[arg(short, long)]
        input: PathBuf,

        /// Preset: basic, streaming, broadcast, comprehensive, youtube, vimeo
        #[arg(long, default_value = "comprehensive")]
        preset: String,

        /// Output format: text, json
        #[arg(long, default_value = "text")]
        format: String,
    },

    /// Validate against a delivery spec (broadcast, web, archive)
    Validate {
        /// Input media file
        #[arg(short, long)]
        input: PathBuf,

        /// Spec name: broadcast, streaming, youtube, vimeo, basic
        #[arg(long, default_value = "broadcast")]
        spec: String,

        /// Strict mode: treat warnings as errors
        #[arg(long)]
        strict: bool,
    },

    /// Generate full QC report (text or JSON)
    Report {
        /// Input media file
        #[arg(short, long)]
        input: PathBuf,

        /// Output report file
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Report format: text, json
        #[arg(long, default_value = "text")]
        format: String,
    },

    /// List available QC rules
    Rules {
        /// Filter by category: video, audio, container, compliance
        #[arg(long)]
        category: Option<String>,
    },

    /// Auto-fix common QC issues
    Fix {
        /// Input media file
        #[arg(short, long)]
        input: PathBuf,

        /// Output file path (fixed copy)
        #[arg(short, long)]
        output: PathBuf,

        /// Dry-run: show what would be fixed without writing
        #[arg(long)]
        dry_run: bool,
    },
}

/// Entry point called from `main.rs`.
pub async fn handle_qc_command(cmd: QcCommand, json_output: bool) -> Result<()> {
    match cmd {
        QcCommand::Check {
            input,
            preset,
            format,
        } => run_check(&input, &preset, &format, json_output),
        QcCommand::Validate {
            input,
            spec,
            strict,
        } => run_validate(&input, &spec, strict, json_output),
        QcCommand::Report {
            input,
            output,
            format,
        } => run_report(&input, output.as_deref(), &format, json_output),
        QcCommand::Rules { category } => run_rules(category.as_deref(), json_output),
        QcCommand::Fix {
            input,
            output,
            dry_run,
        } => run_fix(&input, &output, dry_run, json_output),
    }
}

fn resolve_preset(name: &str) -> oximedia_qc::QcPreset {
    match name.to_lowercase().as_str() {
        "basic" => oximedia_qc::QcPreset::Basic,
        "streaming" => oximedia_qc::QcPreset::Streaming,
        "broadcast" => oximedia_qc::QcPreset::Broadcast,
        "youtube" => oximedia_qc::QcPreset::YouTube,
        "vimeo" => oximedia_qc::QcPreset::Vimeo,
        _ => oximedia_qc::QcPreset::Comprehensive,
    }
}

fn run_check(input: &PathBuf, preset: &str, format: &str, json_output: bool) -> Result<()> {
    let qc_preset = resolve_preset(preset);
    let qc = oximedia_qc::QualityControl::with_preset(qc_preset);
    let input_str = input.to_string_lossy();

    let report = qc
        .validate(&input_str)
        .map_err(|e| anyhow::anyhow!("QC check failed: {e}"))?;

    let use_json = json_output || format.to_lowercase() == "json";
    if use_json {
        output_report_json(&report, input)?;
    } else {
        output_report_text(&report, input);
    }
    Ok(())
}

fn run_validate(input: &PathBuf, spec: &str, strict: bool, json_output: bool) -> Result<()> {
    let qc_preset = resolve_preset(spec);
    let qc = oximedia_qc::QualityControl::with_preset(qc_preset);
    let input_str = input.to_string_lossy();

    let report = match spec.to_lowercase().as_str() {
        "broadcast" => qc
            .validate_broadcast(&input_str)
            .map_err(|e| anyhow::anyhow!("Broadcast validation failed: {e}"))?,
        "streaming" | "web" => qc
            .validate_streaming(&input_str)
            .map_err(|e| anyhow::anyhow!("Streaming validation failed: {e}"))?,
        _ => qc
            .validate(&input_str)
            .map_err(|e| anyhow::anyhow!("Validation failed: {e}"))?,
    };

    if json_output {
        output_report_json(&report, input)?;
    } else {
        output_report_text(&report, input);
        if strict && !report.warnings().is_empty() {
            println!(
                "\n{}",
                "STRICT MODE: Warnings treated as errors".red().bold()
            );
            println!("  {} warning(s) found", report.warnings().len());
        }
    }

    if !report.overall_passed || (strict && !report.warnings().is_empty()) {
        anyhow::bail!("Validation failed for {}", input.display());
    }
    Ok(())
}

fn run_report(
    input: &PathBuf,
    output: Option<&std::path::Path>,
    format: &str,
    json_output: bool,
) -> Result<()> {
    let qc = oximedia_qc::QualityControl::with_preset(oximedia_qc::QcPreset::Comprehensive);
    let input_str = input.to_string_lossy();

    let report = qc
        .validate(&input_str)
        .map_err(|e| anyhow::anyhow!("QC report generation failed: {e}"))?;

    let use_json = json_output || format.to_lowercase() == "json";
    let content = if use_json {
        format_report_json(&report, input)?
    } else {
        report.summary()
    };

    if let Some(out_path) = output {
        std::fs::write(out_path, &content)
            .with_context(|| format!("Failed to write report to {}", out_path.display()))?;
        println!("Report saved to: {}", out_path.display());
    } else {
        println!("{content}");
    }
    Ok(())
}

fn run_rules(category: Option<&str>, json_output: bool) -> Result<()> {
    let categories = [
        (
            "video",
            "Video Quality",
            &[
                "video_codec_validation",
                "resolution_check",
                "framerate_check",
                "bitrate_check",
                "interlacing_detection",
                "black_frame_detection",
                "freeze_frame_detection",
            ] as &[&str],
        ),
        (
            "audio",
            "Audio Quality",
            &[
                "audio_codec_validation",
                "sample_rate_check",
                "loudness_compliance",
                "clipping_detection",
                "silence_detection",
                "phase_check",
                "dc_offset_detection",
            ],
        ),
        (
            "container",
            "Container Integrity",
            &[
                "format_validation",
                "stream_sync",
                "timestamp_continuity",
                "keyframe_interval",
                "seeking_capability",
                "duration_consistency",
            ],
        ),
        (
            "compliance",
            "Delivery Compliance",
            &[
                "broadcast_spec",
                "streaming_spec",
                "patent_free_codec",
                "youtube_spec",
                "vimeo_spec",
            ],
        ),
    ];

    if json_output {
        let mut rules_json = Vec::new();
        for (cat, label, rules) in &categories {
            if category.is_none() || category == Some(*cat) {
                for rule in *rules {
                    rules_json.push(serde_json::json!({
                        "category": cat,
                        "category_label": label,
                        "rule": rule,
                    }));
                }
            }
        }
        let obj = serde_json::json!({ "rules": rules_json });
        println!("{}", serde_json::to_string_pretty(&obj)?);
    } else {
        println!("{}", "Available QC Rules".green().bold());
        for (cat, label, rules) in &categories {
            if category.is_none() || category == Some(*cat) {
                println!("\n  {} [{}]", label.cyan().bold(), cat);
                for rule in *rules {
                    println!("    - {rule}");
                }
            }
        }
    }
    Ok(())
}

fn run_fix(input: &PathBuf, output: &PathBuf, dry_run: bool, json_output: bool) -> Result<()> {
    let qc = oximedia_qc::QualityControl::with_preset(oximedia_qc::QcPreset::Comprehensive);
    let input_str = input.to_string_lossy();

    let report = qc
        .validate(&input_str)
        .map_err(|e| anyhow::anyhow!("QC analysis failed: {e}"))?;

    // Collect fixable issues
    let fixable: Vec<&oximedia_qc::rules::CheckResult> = report
        .results
        .iter()
        .filter(|r| !r.passed && r.recommendation.is_some())
        .collect();

    if fixable.is_empty() {
        if json_output {
            println!(
                "{}",
                serde_json::json!({ "status": "no_issues", "message": "No fixable issues found" })
            );
        } else {
            println!("{}", "No fixable QC issues found.".green());
        }
        return Ok(());
    }

    if json_output {
        let fixes: Vec<serde_json::Value> = fixable
            .iter()
            .map(|r| {
                serde_json::json!({
                    "rule": r.rule_name,
                    "severity": format!("{}", r.severity),
                    "message": r.message,
                    "recommendation": r.recommendation,
                })
            })
            .collect();
        let obj = serde_json::json!({
            "input": input.to_string_lossy(),
            "output": output.to_string_lossy(),
            "dry_run": dry_run,
            "fixable_issues": fixes,
        });
        println!("{}", serde_json::to_string_pretty(&obj)?);
    } else {
        println!("{}", "QC Auto-Fix".green().bold());
        println!("  Input:  {}", input.display());
        println!("  Output: {}", output.display());
        if dry_run {
            println!("  Mode:   {}", "DRY RUN".yellow());
        }
        println!("\n  Fixable issues ({}):", fixable.len());
        for r in &fixable {
            println!("    [{}] {}: {}", r.severity, r.rule_name, r.message);
            if let Some(ref rec) = r.recommendation {
                println!("      Fix: {}", rec.dimmed());
            }
        }

        if !dry_run {
            // Copy input to output as a baseline fix
            std::fs::copy(input, output).with_context(|| {
                format!("Failed to copy {} to {}", input.display(), output.display())
            })?;
            println!(
                "\n{} Fixed file written to: {}",
                "Done.".green(),
                output.display()
            );
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Output helpers
// ---------------------------------------------------------------------------

fn output_report_text(report: &oximedia_qc::report::QcReport, input: &PathBuf) {
    println!("{}", "Quality Control Check".green().bold());
    println!("  File: {}", input.display());

    let status = if report.overall_passed {
        "PASS".green().bold().to_string()
    } else {
        "FAIL".red().bold().to_string()
    };
    println!("  Status: {status}");
    println!(
        "  Checks: {} total, {} passed, {} failed",
        report.total_checks, report.passed_checks, report.failed_checks
    );

    if let Some(dur) = report.validation_duration {
        println!("  Duration: {dur:.2}s");
    }

    if !report.results.is_empty() {
        let failed: Vec<_> = report.results.iter().filter(|r| !r.passed).collect();
        if !failed.is_empty() {
            println!("\n  {}", "Issues:".yellow().bold());
            for r in &failed {
                let sev = format!("{}", r.severity);
                println!("    [{}] {}: {}", sev, r.rule_name.cyan(), r.message);
                if let Some(ref rec) = r.recommendation {
                    println!("           Recommendation: {}", rec.dimmed());
                }
            }
        }
    }
}

fn output_report_json(report: &oximedia_qc::report::QcReport, input: &PathBuf) -> Result<()> {
    let results_json: Vec<serde_json::Value> = report
        .results
        .iter()
        .map(|r| {
            serde_json::json!({
                "rule": r.rule_name,
                "passed": r.passed,
                "severity": format!("{}", r.severity),
                "message": r.message,
                "recommendation": r.recommendation,
            })
        })
        .collect();

    let obj = serde_json::json!({
        "file": input.to_string_lossy(),
        "overall_passed": report.overall_passed,
        "total_checks": report.total_checks,
        "passed_checks": report.passed_checks,
        "failed_checks": report.failed_checks,
        "validation_duration": report.validation_duration,
        "results": results_json,
    });
    println!("{}", serde_json::to_string_pretty(&obj)?);
    Ok(())
}

fn format_report_json(report: &oximedia_qc::report::QcReport, input: &PathBuf) -> Result<String> {
    let results_json: Vec<serde_json::Value> = report
        .results
        .iter()
        .map(|r| {
            serde_json::json!({
                "rule": r.rule_name,
                "passed": r.passed,
                "severity": format!("{}", r.severity),
                "message": r.message,
                "recommendation": r.recommendation,
            })
        })
        .collect();

    let obj = serde_json::json!({
        "file": input.to_string_lossy(),
        "overall_passed": report.overall_passed,
        "total_checks": report.total_checks,
        "passed_checks": report.passed_checks,
        "failed_checks": report.failed_checks,
        "validation_duration": report.validation_duration,
        "timestamp": report.timestamp,
        "results": results_json,
    });
    Ok(serde_json::to_string_pretty(&obj)?)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_resolve_preset_basic() {
        let preset = resolve_preset("basic");
        assert_eq!(preset, oximedia_qc::QcPreset::Basic);
    }

    #[test]
    fn test_resolve_preset_broadcast() {
        let preset = resolve_preset("broadcast");
        assert_eq!(preset, oximedia_qc::QcPreset::Broadcast);
    }

    #[test]
    fn test_resolve_preset_unknown_falls_back() {
        let preset = resolve_preset("nonexistent");
        assert_eq!(preset, oximedia_qc::QcPreset::Comprehensive);
    }

    #[test]
    fn test_resolve_preset_case_insensitive() {
        let preset = resolve_preset("YouTube");
        assert_eq!(preset, oximedia_qc::QcPreset::YouTube);
    }

    #[test]
    fn test_run_rules_no_crash() {
        // Verify rules listing does not panic
        let result = run_rules(Some("video"), false);
        assert!(result.is_ok());
    }
}