oximedia-cli 0.1.4

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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
//! Video scopes command.
//!
//! Provides the `oximedia scopes` subcommand family for generating broadcast-quality
//! video scopes (waveform, vectorscope, histogram, parade, false color) using the
//! `oximedia-scopes` crate.

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

/// Subcommands for the `scopes` command.
#[derive(Subcommand, Debug)]
pub enum ScopesCommand {
    /// Generate waveform display
    Waveform {
        /// Input video file
        #[arg(short, long)]
        input: PathBuf,

        /// Output scope image path
        #[arg(short, long)]
        output: PathBuf,

        /// Waveform mode: luma, rgb_parade, rgb_overlay, ycbcr
        #[arg(long, default_value = "luma")]
        mode: String,

        /// Scope display width in pixels
        #[arg(long, default_value = "512")]
        width: u32,

        /// Scope display height in pixels
        #[arg(long, default_value = "512")]
        height: u32,

        /// Specific frame number (default: first frame)
        #[arg(long)]
        frame: Option<u64>,

        /// Show graticule overlay
        #[arg(long)]
        graticule: bool,
    },

    /// Generate vectorscope display
    Vectorscope {
        /// Input video file
        #[arg(short, long)]
        input: PathBuf,

        /// Output scope image path
        #[arg(short, long)]
        output: PathBuf,

        /// Display mode: circular, rectangular
        #[arg(long, default_value = "circular")]
        mode: String,

        /// Scope display size in pixels (square)
        #[arg(long, default_value = "512")]
        size: u32,

        /// Specific frame number (default: first frame)
        #[arg(long)]
        frame: Option<u64>,

        /// Show SMPTE color bar targets
        #[arg(long)]
        targets: bool,

        /// Vectorscope gain / zoom
        #[arg(long, default_value = "1.0")]
        gain: f64,
    },

    /// Generate histogram
    Histogram {
        /// Input video file
        #[arg(short, long)]
        input: PathBuf,

        /// Output scope image path
        #[arg(short, long)]
        output: PathBuf,

        /// Histogram mode: rgb, luma, overlay, stacked, logarithmic
        #[arg(long, default_value = "rgb")]
        mode: String,

        /// Scope display width in pixels
        #[arg(long, default_value = "512")]
        width: u32,

        /// Scope display height in pixels
        #[arg(long, default_value = "256")]
        height: u32,

        /// Specific frame number (default: first frame)
        #[arg(long)]
        frame: Option<u64>,
    },

    /// Generate RGB or YCbCr parade display
    Parade {
        /// Input video file
        #[arg(short, long)]
        input: PathBuf,

        /// Output scope image path
        #[arg(short, long)]
        output: PathBuf,

        /// Parade mode: rgb, ycbcr
        #[arg(long, default_value = "rgb")]
        mode: String,

        /// Scope display width in pixels
        #[arg(long, default_value = "768")]
        width: u32,

        /// Scope display height in pixels
        #[arg(long, default_value = "256")]
        height: u32,

        /// Specific frame number (default: first frame)
        #[arg(long)]
        frame: Option<u64>,
    },

    /// Generate false color exposure display
    FalseColor {
        /// Input video file
        #[arg(short, long)]
        input: PathBuf,

        /// Output scope image path
        #[arg(short, long)]
        output: PathBuf,

        /// Specific frame number (default: first frame)
        #[arg(long)]
        frame: Option<u64>,

        /// Show color scale legend alongside the image
        #[arg(long)]
        scale: bool,
    },

    /// Analyze a frame with one or more scope types
    Analyze {
        /// Input video file
        #[arg(short, long)]
        input: PathBuf,

        /// Frame number to analyze (default: first frame)
        #[arg(long)]
        frame: Option<u64>,

        /// Scope type(s) to generate
        #[arg(long, default_value = "all",
              value_parser = ["waveform", "vectorscope", "histogram", "all"])]
        scope: String,

        /// Output directory for scope images
        #[arg(short, long)]
        output: PathBuf,
    },

    /// Check video compliance against a broadcast color standard
    Compliance {
        /// Input video file
        #[arg(short, long)]
        input: PathBuf,

        /// Broadcast standard to check against
        #[arg(long, default_value = "rec709",
              value_parser = ["rec709", "rec2020"])]
        standard: String,
    },

    /// Print per-frame statistics for a video file
    Stats {
        /// Input video file
        #[arg(short, long)]
        input: PathBuf,

        /// Number of frames to sample (0 = auto)
        #[arg(long, default_value = "0")]
        frames: u64,
    },
}

/// Entry point for `oximedia scopes <subcommand>`.
pub async fn handle_scopes_command(command: ScopesCommand, json_output: bool) -> Result<()> {
    match command {
        ScopesCommand::Waveform {
            input,
            output,
            mode,
            width,
            height,
            frame,
            graticule,
        } => {
            run_waveform(
                &input,
                &output,
                &mode,
                width,
                height,
                frame,
                graticule,
                json_output,
            )
            .await
        }
        ScopesCommand::Vectorscope {
            input,
            output,
            mode,
            size,
            frame,
            targets,
            gain,
        } => {
            run_vectorscope(
                &input,
                &output,
                &mode,
                size,
                frame,
                targets,
                gain,
                json_output,
            )
            .await
        }
        ScopesCommand::Histogram {
            input,
            output,
            mode,
            width,
            height,
            frame,
        } => run_histogram(&input, &output, &mode, width, height, frame, json_output).await,
        ScopesCommand::Parade {
            input,
            output,
            mode,
            width,
            height,
            frame,
        } => run_parade(&input, &output, &mode, width, height, frame, json_output).await,
        ScopesCommand::FalseColor {
            input,
            output,
            frame,
            scale,
        } => run_false_color(&input, &output, frame, scale, json_output).await,

        ScopesCommand::Analyze {
            input,
            frame,
            scope,
            output,
        } => run_analyze(&input, frame, &scope, &output, json_output).await,

        ScopesCommand::Compliance { input, standard } => {
            run_compliance(&input, &standard, json_output).await
        }

        ScopesCommand::Stats { input, frames } => run_stats(&input, frames, json_output).await,
    }
}

// ---------------------------------------------------------------------------
// Frame extraction helper
// ---------------------------------------------------------------------------

/// Extract a single frame as RGB24 data from a video file.
///
/// For now this creates a placeholder gradient frame when the full demux/decode
/// pipeline is not yet wired, while still exercising the scopes engine.  When
/// OxiMedia I/O integration is complete, this function should open the container,
/// seek to `_frame_num`, decode, and return raw RGB24 bytes plus dimensions.
fn extract_frame_rgb(input: &std::path::Path, _frame_num: u64) -> Result<(Vec<u8>, u32, u32)> {
    // Verify the input path exists so the user gets a clear error early.
    if !input.exists() {
        bail!("Input file not found: {}", input.display());
    }

    // Placeholder: create a 256x256 colour-ramp frame that gives interesting
    // scope output (diagonal gradient with varying R/G/B channels).
    let w: u32 = 256;
    let h: u32 = 256;
    let mut data = vec![0u8; (w * h * 3) as usize];
    for y in 0..h {
        for x in 0..w {
            let idx = ((y * w + x) * 3) as usize;
            data[idx] = (x & 0xFF) as u8; // R
            data[idx + 1] = (y & 0xFF) as u8; // G
            data[idx + 2] = (((x + y) / 2) & 0xFF) as u8; // B
        }
    }

    Ok((data, w, h))
}

// ---------------------------------------------------------------------------
// Write scope RGBA data to output path (raw RGBA or described via JSON)
// ---------------------------------------------------------------------------

fn write_scope_output(
    output: &std::path::Path,
    scope: &oximedia_scopes::ScopeData,
    json_output: bool,
    scope_label: &str,
) -> Result<()> {
    if json_output {
        let obj = serde_json::json!({
            "scope": scope_label,
            "width": scope.width,
            "height": scope.height,
            "format": "RGBA",
            "bytes": scope.data.len(),
            "output": output.to_string_lossy(),
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&obj).context("JSON serialisation")?
        );
        return Ok(());
    }

    // Write raw RGBA file (consumer can load as width*height*4 RGBA bytes)
    std::fs::write(output, &scope.data)
        .with_context(|| format!("Failed to write scope image to {}", output.display()))?;

    println!("{}", format!("{scope_label} Scope").green().bold());
    println!("  Output:     {}", output.display());
    println!("  Dimensions: {}x{}", scope.width, scope.height);
    println!("  Format:     RGBA ({} bytes)", scope.data.len());

    Ok(())
}

// ---------------------------------------------------------------------------
// Waveform
// ---------------------------------------------------------------------------

async fn run_waveform(
    input: &std::path::Path,
    output: &std::path::Path,
    mode: &str,
    width: u32,
    height: u32,
    frame_num: Option<u64>,
    graticule: bool,
    json_output: bool,
) -> Result<()> {
    use oximedia_scopes::{
        HistogramMode, ScopeConfig, ScopeType, VectorscopeMode, VideoScopes, WaveformMode,
    };

    let scope_type = match mode.to_lowercase().as_str() {
        "luma" => ScopeType::WaveformLuma,
        "rgb_parade" | "rgb-parade" => ScopeType::WaveformRgbParade,
        "rgb_overlay" | "rgb-overlay" => ScopeType::WaveformRgbOverlay,
        "ycbcr" => ScopeType::WaveformYcbcr,
        other => bail!(
            "Unknown waveform mode '{}'. Use: luma, rgb_parade, rgb_overlay, ycbcr",
            other
        ),
    };

    let config = ScopeConfig {
        width,
        height,
        show_graticule: graticule,
        show_labels: graticule,
        anti_alias: true,
        waveform_mode: WaveformMode::Overlay,
        vectorscope_mode: VectorscopeMode::Circular,
        histogram_mode: HistogramMode::Overlay,
        vectorscope_gain: 1.0,
        highlight_gamut: false,
        gamut_colorspace: oximedia_scopes::GamutColorspace::Rec709,
    };

    let (frame_data, fw, fh) = extract_frame_rgb(input, frame_num.unwrap_or(0))?;
    let scopes = VideoScopes::new(config);
    let scope_data = scopes
        .analyze(&frame_data, fw, fh, scope_type)
        .map_err(|e| anyhow::anyhow!("Waveform analysis failed: {e}"))?;

    write_scope_output(output, &scope_data, json_output, "Waveform")
}

// ---------------------------------------------------------------------------
// Vectorscope
// ---------------------------------------------------------------------------

#[allow(clippy::too_many_arguments)]
async fn run_vectorscope(
    input: &std::path::Path,
    output: &std::path::Path,
    mode: &str,
    size: u32,
    frame_num: Option<u64>,
    targets: bool,
    gain: f64,
    json_output: bool,
) -> Result<()> {
    use oximedia_scopes::{
        HistogramMode, ScopeConfig, ScopeType, VectorscopeMode, VideoScopes, WaveformMode,
    };

    let vectorscope_mode = match mode.to_lowercase().as_str() {
        "circular" => VectorscopeMode::Circular,
        "rectangular" => VectorscopeMode::Rectangular,
        other => bail!(
            "Unknown vectorscope mode '{}'. Use: circular, rectangular",
            other
        ),
    };

    let config = ScopeConfig {
        width: size,
        height: size,
        show_graticule: targets,
        show_labels: targets,
        anti_alias: true,
        waveform_mode: WaveformMode::Overlay,
        vectorscope_mode,
        histogram_mode: HistogramMode::Overlay,
        vectorscope_gain: gain as f32,
        highlight_gamut: false,
        gamut_colorspace: oximedia_scopes::GamutColorspace::Rec709,
    };

    let (frame_data, fw, fh) = extract_frame_rgb(input, frame_num.unwrap_or(0))?;
    let scopes = VideoScopes::new(config);
    let scope_data = scopes
        .analyze(&frame_data, fw, fh, ScopeType::Vectorscope)
        .map_err(|e| anyhow::anyhow!("Vectorscope analysis failed: {e}"))?;

    write_scope_output(output, &scope_data, json_output, "Vectorscope")
}

// ---------------------------------------------------------------------------
// Histogram
// ---------------------------------------------------------------------------

async fn run_histogram(
    input: &std::path::Path,
    output: &std::path::Path,
    mode: &str,
    width: u32,
    height: u32,
    frame_num: Option<u64>,
    json_output: bool,
) -> Result<()> {
    use oximedia_scopes::{
        HistogramMode, ScopeConfig, ScopeType, VectorscopeMode, VideoScopes, WaveformMode,
    };

    let (scope_type, histogram_mode) = match mode.to_lowercase().as_str() {
        "rgb" => (ScopeType::HistogramRgb, HistogramMode::Overlay),
        "luma" => (ScopeType::HistogramLuma, HistogramMode::Overlay),
        "overlay" => (ScopeType::HistogramRgb, HistogramMode::Overlay),
        "stacked" => (ScopeType::HistogramRgb, HistogramMode::Stacked),
        "logarithmic" | "log" => (ScopeType::HistogramRgb, HistogramMode::Logarithmic),
        other => bail!(
            "Unknown histogram mode '{}'. Use: rgb, luma, overlay, stacked, logarithmic",
            other
        ),
    };

    let config = ScopeConfig {
        width,
        height,
        show_graticule: true,
        show_labels: true,
        anti_alias: true,
        waveform_mode: WaveformMode::Overlay,
        vectorscope_mode: VectorscopeMode::Circular,
        histogram_mode,
        vectorscope_gain: 1.0,
        highlight_gamut: false,
        gamut_colorspace: oximedia_scopes::GamutColorspace::Rec709,
    };

    let (frame_data, fw, fh) = extract_frame_rgb(input, frame_num.unwrap_or(0))?;
    let scopes = VideoScopes::new(config);
    let scope_data = scopes
        .analyze(&frame_data, fw, fh, scope_type)
        .map_err(|e| anyhow::anyhow!("Histogram analysis failed: {e}"))?;

    write_scope_output(output, &scope_data, json_output, "Histogram")
}

// ---------------------------------------------------------------------------
// Parade
// ---------------------------------------------------------------------------

async fn run_parade(
    input: &std::path::Path,
    output: &std::path::Path,
    mode: &str,
    width: u32,
    height: u32,
    frame_num: Option<u64>,
    json_output: bool,
) -> Result<()> {
    use oximedia_scopes::{
        HistogramMode, ScopeConfig, ScopeType, VectorscopeMode, VideoScopes, WaveformMode,
    };

    let scope_type = match mode.to_lowercase().as_str() {
        "rgb" => ScopeType::ParadeRgb,
        "ycbcr" => ScopeType::ParadeYcbcr,
        other => bail!("Unknown parade mode '{}'. Use: rgb, ycbcr", other),
    };

    let config = ScopeConfig {
        width,
        height,
        show_graticule: true,
        show_labels: true,
        anti_alias: true,
        waveform_mode: WaveformMode::Overlay,
        vectorscope_mode: VectorscopeMode::Circular,
        histogram_mode: HistogramMode::Overlay,
        vectorscope_gain: 1.0,
        highlight_gamut: false,
        gamut_colorspace: oximedia_scopes::GamutColorspace::Rec709,
    };

    let (frame_data, fw, fh) = extract_frame_rgb(input, frame_num.unwrap_or(0))?;
    let scopes = VideoScopes::new(config);
    let scope_data = scopes
        .analyze(&frame_data, fw, fh, scope_type)
        .map_err(|e| anyhow::anyhow!("Parade analysis failed: {e}"))?;

    write_scope_output(output, &scope_data, json_output, "Parade")
}

// ---------------------------------------------------------------------------
// False Color
// ---------------------------------------------------------------------------

async fn run_false_color(
    input: &std::path::Path,
    output: &std::path::Path,
    frame_num: Option<u64>,
    show_scale: bool,
    json_output: bool,
) -> Result<()> {
    use oximedia_scopes::{ScopeConfig, ScopeType, VideoScopes};

    let config = ScopeConfig::default();
    let (frame_data, fw, fh) = extract_frame_rgb(input, frame_num.unwrap_or(0))?;

    let scopes = VideoScopes::new(config);
    let scope_data = scopes
        .analyze(&frame_data, fw, fh, ScopeType::FalseColor)
        .map_err(|e| anyhow::anyhow!("False color analysis failed: {e}"))?;

    if json_output {
        let stats = oximedia_scopes::false_color::compute_false_color_stats(&frame_data, fw, fh);
        let zone_map: serde_json::Map<String, serde_json::Value> = stats
            .zone_distribution
            .iter()
            .map(|(name, pct)| {
                (
                    name.clone(),
                    serde_json::Value::Number(
                        serde_json::Number::from_f64(f64::from(*pct))
                            .unwrap_or_else(|| serde_json::Number::from(0)),
                    ),
                )
            })
            .collect();

        let obj = serde_json::json!({
            "scope": "FalseColor",
            "width": scope_data.width,
            "height": scope_data.height,
            "format": "RGBA",
            "bytes": scope_data.data.len(),
            "output": output.to_string_lossy(),
            "show_scale": show_scale,
            "stats": {
                "highlight_clip_pct": stats.highlight_clip_percent,
                "shadow_clip_pct": stats.shadow_clip_percent,
                "good_exposure_pct": stats.good_exposure_percent,
                "zone_distribution": zone_map,
            },
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&obj).context("JSON serialisation")?
        );
        return Ok(());
    }

    // If scale legend requested, append it beneath the false color image
    let final_data = if show_scale {
        let legend_height = 20u32;
        let scale = oximedia_scopes::false_color::FalseColorScale::default();
        let legend =
            oximedia_scopes::false_color::generate_false_color_legend(fw, legend_height, &scale);
        let mut combined = scope_data.data.clone();
        combined.extend_from_slice(&legend);
        combined
    } else {
        scope_data.data.clone()
    };

    std::fs::write(output, &final_data)
        .with_context(|| format!("Failed to write false color image to {}", output.display()))?;

    let stats = oximedia_scopes::false_color::compute_false_color_stats(&frame_data, fw, fh);

    println!("{}", "False Color Scope".green().bold());
    println!("  Output:         {}", output.display());
    println!(
        "  Dimensions:     {}x{}",
        scope_data.width, scope_data.height
    );
    println!("  Format:         RGBA ({} bytes)", final_data.len());
    println!("  Good exposure:  {:.1}%", stats.good_exposure_percent);
    println!("  Shadow clip:    {:.1}%", stats.shadow_clip_percent);
    println!("  Highlight clip: {:.1}%", stats.highlight_clip_percent);
    if show_scale {
        println!("  Legend:          appended ({}px tall)", 20);
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Analyze (multi-scope)
// ---------------------------------------------------------------------------

async fn run_analyze(
    input: &std::path::Path,
    frame_num: Option<u64>,
    scope: &str,
    output_dir: &std::path::Path,
    json_output: bool,
) -> Result<()> {
    use oximedia_scopes::{
        HistogramMode, ScopeConfig, ScopeType, VectorscopeMode, VideoScopes, WaveformMode,
    };

    if !input.exists() {
        bail!("Input file not found: {}", input.display());
    }

    std::fs::create_dir_all(output_dir)
        .with_context(|| format!("Cannot create output directory: {}", output_dir.display()))?;

    let frame = frame_num.unwrap_or(0);
    let (frame_data, fw, fh) = extract_frame_rgb(input, frame)?;

    let config = ScopeConfig {
        width: 512,
        height: 512,
        show_graticule: true,
        show_labels: true,
        anti_alias: true,
        waveform_mode: WaveformMode::Overlay,
        vectorscope_mode: VectorscopeMode::Circular,
        histogram_mode: HistogramMode::Overlay,
        vectorscope_gain: 1.0,
        highlight_gamut: false,
        gamut_colorspace: oximedia_scopes::GamutColorspace::Rec709,
    };

    let scope_types: &[(&str, ScopeType)] = match scope {
        "waveform" => &[("waveform", ScopeType::WaveformLuma)],
        "vectorscope" => &[("vectorscope", ScopeType::Vectorscope)],
        "histogram" => &[("histogram", ScopeType::HistogramRgb)],
        _ => &[
            ("waveform", ScopeType::WaveformLuma),
            ("vectorscope", ScopeType::Vectorscope),
            ("histogram", ScopeType::HistogramRgb),
        ],
    };

    let scopes = VideoScopes::new(config);
    let mut generated = Vec::new();

    for (name, scope_type) in scope_types {
        let scope_data = scopes
            .analyze(&frame_data, fw, fh, *scope_type)
            .map_err(|e| anyhow::anyhow!("Scope analysis failed for {name}: {e}"))?;
        let out_path = output_dir.join(format!("{name}.rgba"));
        std::fs::write(&out_path, &scope_data.data)
            .with_context(|| format!("Cannot write {}", out_path.display()))?;
        generated.push((
            name.to_string(),
            out_path,
            scope_data.width,
            scope_data.height,
        ));
    }

    if json_output {
        let files: Vec<serde_json::Value> = generated
            .iter()
            .map(|(n, p, w, h)| {
                serde_json::json!({
                    "scope": n,
                    "path": p.display().to_string(),
                    "width": w,
                    "height": h,
                })
            })
            .collect();
        let obj = serde_json::json!({
            "command": "scopes analyze",
            "input": input.display().to_string(),
            "frame": frame,
            "scope_filter": scope,
            "output_dir": output_dir.display().to_string(),
            "generated": files,
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&obj).context("JSON serialization")?
        );
        return Ok(());
    }

    println!("{}", "Scopes Analysis".green().bold());
    println!("{}", "=".repeat(60));
    println!("{:20} {}", "Input:", input.display());
    println!("{:20} {}", "Frame:", frame);
    println!("{:20} {}", "Output dir:", output_dir.display());
    println!();
    for (name, path, w, h) in &generated {
        println!("  {} {}x{} → {}", name.cyan(), w, h, path.display());
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Compliance
// ---------------------------------------------------------------------------

async fn run_compliance(input: &std::path::Path, standard: &str, json_output: bool) -> Result<()> {
    use oximedia_scopes::{GamutColorspace, ScopeConfig, ScopeType, VideoScopes};

    if !input.exists() {
        bail!("Input file not found: {}", input.display());
    }

    let gamut = match standard {
        "rec2020" => GamutColorspace::Rec2020,
        _ => GamutColorspace::Rec709,
    };

    let config = ScopeConfig {
        highlight_gamut: true,
        gamut_colorspace: gamut,
        ..ScopeConfig::default()
    };

    let (frame_data, fw, fh) = extract_frame_rgb(input, 0)?;
    let scopes = VideoScopes::new(config);
    let scope_data = scopes
        .analyze(&frame_data, fw, fh, ScopeType::Vectorscope)
        .map_err(|e| anyhow::anyhow!("Compliance analysis failed: {e}"))?;

    // Heuristic: estimate out-of-gamut pixels from scope output brightness
    let total_pixels = (scope_data.width * scope_data.height) as usize;
    let bright_pixels = scope_data
        .data
        .chunks(4)
        .filter(|px| px[0] > 200 || px[1] > 200 || px[2] > 200)
        .count();
    let pct_in_gamut = if total_pixels > 0 {
        100.0 - (bright_pixels as f64 / total_pixels as f64) * 100.0
    } else {
        100.0
    };
    let compliant = pct_in_gamut >= 95.0;

    if json_output {
        let obj = serde_json::json!({
            "command": "scopes compliance",
            "input": input.display().to_string(),
            "standard": standard,
            "pct_in_gamut": pct_in_gamut,
            "compliant": compliant,
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&obj).context("JSON serialization")?
        );
        return Ok(());
    }

    println!("{}", "Scopes Compliance".green().bold());
    println!("{}", "=".repeat(60));
    println!("{:20} {}", "Input:", input.display());
    println!("{:20} {}", "Standard:", standard.to_uppercase());
    println!("{:20} {:.1}%", "In-gamut est.:", pct_in_gamut);
    let status = if compliant {
        "PASS".green().bold().to_string()
    } else {
        "FAIL".red().bold().to_string()
    };
    println!("{:20} {}", "Result:", status);

    Ok(())
}

// ---------------------------------------------------------------------------
// Stats
// ---------------------------------------------------------------------------

async fn run_stats(
    input: &std::path::Path,
    frames_to_sample: u64,
    json_output: bool,
) -> Result<()> {
    use oximedia_scopes::{ScopeConfig, ScopeType, VideoScopes};

    if !input.exists() {
        bail!("Input file not found: {}", input.display());
    }

    // Sample up to 3 frames (or as requested) — real impl decodes multiple frames
    let count = if frames_to_sample == 0 {
        3
    } else {
        frames_to_sample.min(10)
    };
    let config = ScopeConfig::default();
    let scopes = VideoScopes::new(config);

    let mut min_luma = f64::MAX;
    let mut max_luma = f64::MIN;
    let mut sum_luma = 0.0_f64;

    for i in 0..count {
        let (frame_data, fw, fh) = extract_frame_rgb(input, i)?;
        let scope_data = scopes
            .analyze(&frame_data, fw, fh, ScopeType::HistogramLuma)
            .map_err(|e| anyhow::anyhow!("Stats analysis failed on frame {i}: {e}"))?;

        // Compute mean luminance from histogram data
        let luma_mean = scope_data.data.iter().map(|&b| b as f64).sum::<f64>()
            / (scope_data.data.len().max(1) as f64);
        if luma_mean < min_luma {
            min_luma = luma_mean;
        }
        if luma_mean > max_luma {
            max_luma = luma_mean;
        }
        sum_luma += luma_mean;
    }

    let avg_luma = sum_luma / count as f64;

    if json_output {
        let obj = serde_json::json!({
            "command": "scopes stats",
            "input": input.display().to_string(),
            "frames_sampled": count,
            "luma": {
                "min": min_luma,
                "max": max_luma,
                "avg": avg_luma,
            },
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&obj).context("JSON serialization")?
        );
        return Ok(());
    }

    println!("{}", "Scopes Statistics".green().bold());
    println!("{}", "=".repeat(60));
    println!("{:20} {}", "Input:", input.display());
    println!("{:20} {}", "Frames sampled:", count);
    println!();
    println!("{}", "Luminance".cyan().bold());
    println!("{}", "-".repeat(60));
    println!("{:20} {:.1}", "Min:", min_luma);
    println!("{:20} {:.1}", "Max:", max_luma);
    println!("{:20} {:.1}", "Average:", avg_luma);

    Ok(())
}

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

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

    fn temp_input() -> PathBuf {
        let dir = std::env::temp_dir();
        let path = dir.join("oximedia_scopes_test_input.bin");
        if let Ok(mut f) = std::fs::File::create(&path) {
            let _ = f.write_all(b"dummy");
        }
        path
    }

    #[tokio::test]
    async fn test_waveform_luma() {
        let input = temp_input();
        let output = std::env::temp_dir().join("test_waveform.rgba");
        let result = run_waveform(&input, &output, "luma", 64, 64, None, false, false).await;
        assert!(result.is_ok());
        assert!(output.exists());
        let _ = std::fs::remove_file(&output);
    }

    #[tokio::test]
    async fn test_waveform_rgb_parade() {
        let input = temp_input();
        let output = std::env::temp_dir().join("test_wf_rgbparade.rgba");
        let result = run_waveform(&input, &output, "rgb_parade", 64, 64, None, true, false).await;
        assert!(result.is_ok());
        let _ = std::fs::remove_file(&output);
    }

    #[tokio::test]
    async fn test_vectorscope_circular() {
        let input = temp_input();
        let output = std::env::temp_dir().join("test_vectorscope.rgba");
        let result = run_vectorscope(&input, &output, "circular", 64, None, true, 1.0, false).await;
        assert!(result.is_ok());
        let _ = std::fs::remove_file(&output);
    }

    #[tokio::test]
    async fn test_histogram_rgb() {
        let input = temp_input();
        let output = std::env::temp_dir().join("test_histogram.rgba");
        let result = run_histogram(&input, &output, "rgb", 64, 64, None, false).await;
        assert!(result.is_ok());
        let _ = std::fs::remove_file(&output);
    }

    #[tokio::test]
    async fn test_parade_rgb() {
        let input = temp_input();
        let output = std::env::temp_dir().join("test_parade.rgba");
        let result = run_parade(&input, &output, "rgb", 96, 64, None, false).await;
        assert!(result.is_ok());
        let _ = std::fs::remove_file(&output);
    }

    #[tokio::test]
    async fn test_false_color() {
        let input = temp_input();
        let output = std::env::temp_dir().join("test_false_color.rgba");
        let result = run_false_color(&input, &output, None, false, false).await;
        assert!(result.is_ok());
        let _ = std::fs::remove_file(&output);
    }

    #[tokio::test]
    async fn test_false_color_with_scale() {
        let input = temp_input();
        let output = std::env::temp_dir().join("test_false_color_scale.rgba");
        let result = run_false_color(&input, &output, None, true, false).await;
        assert!(result.is_ok());
        let _ = std::fs::remove_file(&output);
    }

    #[tokio::test]
    async fn test_json_output() {
        let input = temp_input();
        let output = std::env::temp_dir().join("test_wf_json.rgba");
        let result = run_waveform(&input, &output, "luma", 64, 64, None, false, true).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_bad_waveform_mode() {
        let input = temp_input();
        let output = std::env::temp_dir().join("test_bad_wf.rgba");
        let result = run_waveform(&input, &output, "invalid", 64, 64, None, false, false).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_bad_vectorscope_mode() {
        let input = temp_input();
        let output = std::env::temp_dir().join("test_bad_vs.rgba");
        let result = run_vectorscope(&input, &output, "invalid", 64, None, false, 1.0, false).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_missing_input() {
        let output = std::env::temp_dir().join("test_missing.rgba");
        let result = run_waveform(
            std::path::Path::new("/nonexistent/video.mkv"),
            &output,
            "luma",
            64,
            64,
            None,
            false,
            false,
        )
        .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_analyze_all_scopes() {
        let input = temp_input();
        let out_dir = std::env::temp_dir().join("oximedia_scopes_analyze_test");
        let result = run_analyze(&input, None, "all", &out_dir, false).await;
        assert!(result.is_ok(), "unexpected error: {result:?}");
        let _ = std::fs::remove_dir_all(&out_dir);
    }

    #[tokio::test]
    async fn test_analyze_waveform_json() {
        let input = temp_input();
        let out_dir = std::env::temp_dir().join("oximedia_scopes_analyze_wf_test");
        let result = run_analyze(&input, None, "waveform", &out_dir, true).await;
        assert!(result.is_ok(), "unexpected error: {result:?}");
        let _ = std::fs::remove_dir_all(&out_dir);
    }

    #[tokio::test]
    async fn test_analyze_missing_input() {
        let out_dir = std::env::temp_dir().join("oximedia_scopes_analyze_missing");
        let result = run_analyze(
            std::path::Path::new("/nonexistent/input.mkv"),
            None,
            "all",
            &out_dir,
            false,
        )
        .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_compliance_rec709() {
        let input = temp_input();
        let result = run_compliance(&input, "rec709", false).await;
        assert!(result.is_ok(), "unexpected error: {result:?}");
    }

    #[tokio::test]
    async fn test_compliance_rec2020_json() {
        let input = temp_input();
        let result = run_compliance(&input, "rec2020", true).await;
        assert!(result.is_ok(), "unexpected error: {result:?}");
    }

    #[tokio::test]
    async fn test_compliance_missing_input() {
        let result = run_compliance(
            std::path::Path::new("/nonexistent/video.mkv"),
            "rec709",
            false,
        )
        .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_stats_text() {
        let input = temp_input();
        let result = run_stats(&input, 0, false).await;
        assert!(result.is_ok(), "unexpected error: {result:?}");
    }

    #[tokio::test]
    async fn test_stats_json() {
        let input = temp_input();
        let result = run_stats(&input, 2, true).await;
        assert!(result.is_ok(), "unexpected error: {result:?}");
    }

    #[tokio::test]
    async fn test_stats_missing_input() {
        let result = run_stats(std::path::Path::new("/nonexistent/video.mkv"), 0, false).await;
        assert!(result.is_err());
    }
}