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
//! Audio loudness metering, normalization, spectrum analysis, and beat detection.
//!
//! Provides audio-related commands using `oximedia-metering`, `oximedia-normalize`,
//! and `oximedia-audio-analysis` crates.

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

/// Audio command subcommands.
#[derive(Subcommand, Debug)]
pub enum AudioCommand {
    /// Measure audio loudness (ITU-R BS.1770-4)
    Loudness {
        /// Input audio/video file
        #[arg(short, long)]
        input: PathBuf,

        /// Loudness standard: ebu-r128, atsc-a85, spotify, youtube, apple-music, netflix
        #[arg(long, default_value = "ebu-r128")]
        standard: String,

        /// Sample rate override (Hz)
        #[arg(long)]
        sample_rate: Option<f64>,

        /// Number of channels override
        #[arg(long)]
        channels: Option<usize>,

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

    /// Normalize audio loudness to a target standard
    Normalize {
        /// Input audio/video file
        #[arg(short, long)]
        input: PathBuf,

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

        /// Target loudness in LUFS (overrides standard default)
        #[arg(long)]
        target: Option<f64>,

        /// Loudness standard: ebu-r128, atsc-a85, spotify, youtube, apple-music
        #[arg(long, default_value = "spotify")]
        standard: String,

        /// Enable true peak limiter
        #[arg(long)]
        limiter: bool,

        /// Enable dynamic range compression
        #[arg(long)]
        drc: bool,
    },

    /// Analyze audio frequency spectrum
    Spectrum {
        /// Input audio/video file
        #[arg(short, long)]
        input: PathBuf,

        /// FFT size (power of 2)
        #[arg(long, default_value = "2048")]
        fft_size: usize,

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

    /// Detect beats and tempo in audio
    Beats {
        /// Input audio/video file
        #[arg(short, long)]
        input: PathBuf,

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

/// Handle audio command dispatch.
pub async fn handle_audio_command(command: AudioCommand, json_output: bool) -> Result<()> {
    match command {
        AudioCommand::Loudness {
            input,
            standard,
            sample_rate,
            channels,
            output_format,
        } => {
            measure_loudness(
                &input,
                &standard,
                sample_rate,
                channels,
                if json_output { "json" } else { &output_format },
            )
            .await
        }
        AudioCommand::Normalize {
            input,
            output,
            target,
            standard,
            limiter,
            drc,
        } => normalize_audio(&input, &output, target, &standard, limiter, drc).await,
        AudioCommand::Spectrum {
            input,
            fft_size,
            output_format,
        } => {
            analyze_spectrum(
                &input,
                fft_size,
                if json_output { "json" } else { &output_format },
            )
            .await
        }
        AudioCommand::Beats {
            input,
            output_format,
        } => detect_beats(&input, if json_output { "json" } else { &output_format }).await,
    }
}

/// Parse a standard name string into `oximedia_metering::Standard`.
fn parse_standard(name: &str) -> Result<oximedia_metering::Standard> {
    match name.trim().to_lowercase().as_str() {
        "ebu-r128" | "ebu_r128" | "ebur128" | "r128" => Ok(oximedia_metering::Standard::EbuR128),
        "atsc-a85" | "atsc_a85" | "atsca85" | "a85" => Ok(oximedia_metering::Standard::AtscA85),
        "spotify" => Ok(oximedia_metering::Standard::Spotify),
        "youtube" => Ok(oximedia_metering::Standard::YouTube),
        "apple-music" | "apple_music" | "applemusic" => {
            Ok(oximedia_metering::Standard::AppleMusic)
        }
        "netflix" => Ok(oximedia_metering::Standard::Netflix),
        "amazon" | "amazon-prime" | "prime" => Ok(oximedia_metering::Standard::AmazonPrime),
        other => Err(anyhow::anyhow!(
            "Unknown standard '{}'. Available: ebu-r128, atsc-a85, spotify, youtube, apple-music, netflix, amazon-prime",
            other
        )),
    }
}

/// Measure audio loudness.
async fn measure_loudness(
    input: &PathBuf,
    standard_name: &str,
    sample_rate: Option<f64>,
    channels: Option<usize>,
    output_format: &str,
) -> Result<()> {
    if !input.exists() {
        return Err(anyhow::anyhow!("Input file not found: {}", input.display()));
    }

    let standard = parse_standard(standard_name)?;
    let sr = sample_rate.unwrap_or(48000.0);
    let ch = channels.unwrap_or(2);

    let config = oximedia_metering::MeterConfig::new(standard, sr, ch);
    let _meter = oximedia_metering::LoudnessMeter::new(config)
        .map_err(|e| anyhow::anyhow!("Failed to create loudness meter: {}", e))?;

    match output_format {
        "json" => {
            let result = serde_json::json!({
                "input": input.display().to_string(),
                "standard": standard.name(),
                "target_lufs": standard.target_lufs(),
                "max_true_peak_dbtp": standard.max_true_peak_dbtp(),
                "tolerance_lu": standard.tolerance_lu(),
                "sample_rate": sr,
                "channels": ch,
                "status": "pending_audio_decoding",
                "metrics": {
                    "integrated_lufs": null,
                    "momentary_lufs": null,
                    "short_term_lufs": null,
                    "loudness_range": null,
                    "true_peak_dbtp": null,
                },
                "compliance": null,
                "message": "Loudness meter initialized; awaiting audio decoding pipeline integration",
            });
            let json_str =
                serde_json::to_string_pretty(&result).context("Failed to serialize result")?;
            println!("{}", json_str);
        }
        _ => {
            println!("{}", "Audio Loudness Metering".green().bold());
            println!("{}", "=".repeat(60));
            println!("{:20} {}", "Input:", input.display());
            println!("{:20} {}", "Standard:", standard.name());
            println!("{:20} {:.1} LUFS", "Target:", standard.target_lufs());
            println!(
                "{:20} {:.1} dBTP",
                "Max True Peak:",
                standard.max_true_peak_dbtp()
            );
            println!("{:20} {:.1} LU", "Tolerance:", standard.tolerance_lu());
            println!("{:20} {} Hz", "Sample rate:", sr);
            println!("{:20} {}", "Channels:", ch);
            println!();

            println!("{}", "Measurements".cyan().bold());
            println!("{}", "-".repeat(60));
            println!("  Integrated LUFS:  (pending audio decoding)");
            println!("  Momentary LUFS:   (pending audio decoding)");
            println!("  Short-term LUFS:  (pending audio decoding)");
            println!("  Loudness Range:   (pending audio decoding)");
            println!("  True Peak:        (pending audio decoding)");
            println!();

            println!(
                "{}",
                "Note: Audio decoding pipeline not yet integrated.".yellow()
            );
            println!(
                "{}",
                "Loudness meter is ready; audio decoding will enable end-to-end metering.".dimmed()
            );
        }
    }

    Ok(())
}

/// Normalize audio loudness.
async fn normalize_audio(
    input: &PathBuf,
    output: &PathBuf,
    target: Option<f64>,
    standard_name: &str,
    limiter: bool,
    drc: bool,
) -> Result<()> {
    if !input.exists() {
        return Err(anyhow::anyhow!("Input file not found: {}", input.display()));
    }

    let standard = if let Some(target_lufs) = target {
        oximedia_metering::Standard::Custom {
            target_lufs,
            max_peak_dbtp: -1.0,
            tolerance_lu: 1.0,
        }
    } else {
        parse_standard(standard_name)?
    };

    let mut config = oximedia_normalize::NormalizerConfig::new(standard, 48000.0, 2);
    config.enable_limiter = limiter;
    config.enable_drc = drc;

    let _normalizer = oximedia_normalize::Normalizer::new(config)
        .map_err(|e| anyhow::anyhow!("Failed to create normalizer: {}", e))?;

    println!("{}", "Audio Normalization".green().bold());
    println!("{}", "=".repeat(60));
    println!("{:20} {}", "Input:", input.display());
    println!("{:20} {}", "Output:", output.display());
    println!("{:20} {:.1} LUFS", "Target:", standard.target_lufs());
    println!(
        "{:20} {}",
        "Limiter:",
        if limiter { "enabled" } else { "disabled" }
    );
    println!("{:20} {}", "DRC:", if drc { "enabled" } else { "disabled" });
    println!();

    println!(
        "{}",
        "Note: Audio decoding/encoding pipeline not yet integrated.".yellow()
    );
    println!(
        "{}",
        "Normalizer is ready; audio pipeline will enable end-to-end processing.".dimmed()
    );

    Ok(())
}

/// Analyze audio frequency spectrum.
async fn analyze_spectrum(input: &PathBuf, fft_size: usize, output_format: &str) -> Result<()> {
    if !input.exists() {
        return Err(anyhow::anyhow!("Input file not found: {}", input.display()));
    }

    // Validate FFT size is a power of 2
    if fft_size == 0 || (fft_size & (fft_size - 1)) != 0 {
        return Err(anyhow::anyhow!(
            "FFT size must be a power of 2, got {}",
            fft_size
        ));
    }

    let config = oximedia_audio_analysis::AnalysisConfig {
        fft_size,
        ..oximedia_audio_analysis::AnalysisConfig::default()
    };
    let _analyzer = oximedia_audio_analysis::AudioAnalyzer::new(config);

    match output_format {
        "json" => {
            let result = serde_json::json!({
                "input": input.display().to_string(),
                "fft_size": fft_size,
                "frequency_resolution": 48000.0 / fft_size as f64,
                "status": "pending_audio_decoding",
                "spectral_features": {
                    "centroid": null,
                    "flatness": null,
                    "rolloff": null,
                    "bandwidth": null,
                },
                "message": "Audio analyzer initialized; awaiting audio decoding pipeline integration",
            });
            let json_str =
                serde_json::to_string_pretty(&result).context("Failed to serialize result")?;
            println!("{}", json_str);
        }
        _ => {
            println!("{}", "Spectrum Analysis".green().bold());
            println!("{}", "=".repeat(60));
            println!("{:20} {}", "Input:", input.display());
            println!("{:20} {}", "FFT size:", fft_size);
            println!(
                "{:20} {:.2} Hz",
                "Freq resolution:",
                48000.0 / fft_size as f64
            );
            println!();

            println!("{}", "Spectral Features".cyan().bold());
            println!("{}", "-".repeat(60));
            println!("  Centroid:   (pending audio decoding)");
            println!("  Flatness:   (pending audio decoding)");
            println!("  Rolloff:    (pending audio decoding)");
            println!("  Bandwidth:  (pending audio decoding)");
            println!();

            println!(
                "{}",
                "Note: Audio decoding pipeline not yet integrated.".yellow()
            );
        }
    }

    Ok(())
}

/// Detect beats and tempo in audio.
async fn detect_beats(input: &PathBuf, output_format: &str) -> Result<()> {
    if !input.exists() {
        return Err(anyhow::anyhow!("Input file not found: {}", input.display()));
    }

    let config = oximedia_audio_analysis::AnalysisConfig::default();
    let _analyzer = oximedia_audio_analysis::AudioAnalyzer::new(config);

    match output_format {
        "json" => {
            let result = serde_json::json!({
                "input": input.display().to_string(),
                "status": "pending_audio_decoding",
                "tempo": {
                    "bpm": null,
                    "confidence": null,
                },
                "beats": [],
                "message": "Beat detector initialized; awaiting audio decoding pipeline integration",
            });
            let json_str =
                serde_json::to_string_pretty(&result).context("Failed to serialize result")?;
            println!("{}", json_str);
        }
        _ => {
            println!("{}", "Beat Detection".green().bold());
            println!("{}", "=".repeat(60));
            println!("{:20} {}", "Input:", input.display());
            println!();

            println!("{}", "Tempo Analysis".cyan().bold());
            println!("{}", "-".repeat(60));
            println!("  BPM:        (pending audio decoding)");
            println!("  Confidence: (pending audio decoding)");
            println!("  Beats:      (pending audio decoding)");
            println!();

            println!(
                "{}",
                "Note: Audio decoding pipeline not yet integrated.".yellow()
            );
        }
    }

    Ok(())
}