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
//! Time synchronization CLI commands.
//!
//! Provides commands for analyzing sync offsets, measuring drift,
//! checking clock discipline status, and generating sync reports.

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

// ---------------------------------------------------------------------------
// Command definitions
// ---------------------------------------------------------------------------

/// Time synchronization subcommands.
#[derive(Subcommand, Debug)]
pub enum TimeSyncCommand {
    /// Analyze sync status of a media stream or device
    Analyze {
        /// Target to analyze (file path, stream URL, or device)
        #[arg(short, long)]
        target: String,

        /// Sync protocol to check: ptp, ntp, ltc, genlock
        #[arg(long, default_value = "ptp")]
        protocol: String,

        /// PTP domain number (0-127)
        #[arg(long, default_value = "0")]
        domain: u8,

        /// Duration to analyze in seconds
        #[arg(long, default_value = "10")]
        duration: u64,

        /// Show detailed per-sample measurements
        #[arg(long)]
        detailed: bool,
    },

    /// Align two streams by detecting their time offset
    Align {
        /// First input (reference)
        #[arg(long)]
        reference: String,

        /// Second input (target to align)
        #[arg(long)]
        target: String,

        /// Alignment method: audio, timecode, visual, flash
        #[arg(long, default_value = "audio")]
        method: String,

        /// Maximum search window in seconds
        #[arg(long, default_value = "10")]
        max_offset: f64,
    },

    /// Measure time offset from a reference clock
    Offset {
        /// Reference source: ptp-master, ntp-server, genlock, ltc
        #[arg(long)]
        source: String,

        /// NTP server address (for ntp-server source)
        #[arg(long)]
        server: Option<String>,

        /// Number of measurements to average
        #[arg(long, default_value = "10")]
        samples: u32,
    },

    /// Measure clock drift over time
    Drift {
        /// Target clock or device to measure
        #[arg(long)]
        target: String,

        /// Measurement duration in seconds
        #[arg(long, default_value = "60")]
        duration: u64,

        /// Measurement interval in milliseconds
        #[arg(long, default_value = "1000")]
        interval: u64,

        /// Reference source: system, ptp, ntp
        #[arg(long, default_value = "system")]
        reference: String,

        /// Warn if drift exceeds this threshold (microseconds)
        #[arg(long)]
        threshold_us: Option<f64>,
    },

    /// Generate a comprehensive sync report
    Report {
        /// Target(s) to include in the report (comma-separated)
        #[arg(long)]
        targets: String,

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

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

        /// Include historical data (requires monitoring database)
        #[arg(long)]
        historical: bool,
    },
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

fn validate_protocol(protocol: &str) -> Result<()> {
    match protocol.to_lowercase().as_str() {
        "ptp" | "ntp" | "ltc" | "genlock" | "mtc" | "vitc" => Ok(()),
        other => Err(anyhow::anyhow!(
            "Unknown sync protocol '{}'. Supported: ptp, ntp, ltc, genlock, mtc, vitc",
            other
        )),
    }
}

fn format_protocol(protocol: &str) -> &str {
    match protocol.to_lowercase().as_str() {
        "ptp" => "PTP (IEEE 1588)",
        "ntp" => "NTP (RFC 5905)",
        "ltc" => "LTC (Linear Timecode)",
        "genlock" => "Genlock (Video Reference)",
        "mtc" => "MTC (MIDI Time Code)",
        "vitc" => "VITC (Vertical Interval Timecode)",
        _ => protocol,
    }
}

fn validate_align_method(method: &str) -> Result<()> {
    match method.to_lowercase().as_str() {
        "audio" | "timecode" | "visual" | "flash" | "clapper" => Ok(()),
        other => Err(anyhow::anyhow!(
            "Unknown alignment method '{}'. Supported: audio, timecode, visual, flash, clapper",
            other
        )),
    }
}

fn validate_offset_source(source: &str) -> Result<()> {
    match source.to_lowercase().as_str() {
        "ptp-master" | "ntp-server" | "genlock" | "ltc" | "system" => Ok(()),
        other => Err(anyhow::anyhow!(
            "Unknown offset source '{}'. Supported: ptp-master, ntp-server, genlock, ltc, system",
            other
        )),
    }
}

// ---------------------------------------------------------------------------
// Command handler
// ---------------------------------------------------------------------------

/// Handle time synchronization command dispatch.
pub async fn handle_timesync_command(command: TimeSyncCommand, json_output: bool) -> Result<()> {
    match command {
        TimeSyncCommand::Analyze {
            target,
            protocol,
            domain,
            duration,
            detailed,
        } => run_analyze(&target, &protocol, domain, duration, detailed, json_output).await,
        TimeSyncCommand::Align {
            reference,
            target,
            method,
            max_offset,
        } => run_align(&reference, &target, &method, max_offset, json_output).await,
        TimeSyncCommand::Offset {
            source,
            server,
            samples,
        } => run_offset(&source, &server, samples, json_output).await,
        TimeSyncCommand::Drift {
            target,
            duration,
            interval,
            reference,
            threshold_us,
        } => {
            run_drift(
                &target,
                duration,
                interval,
                &reference,
                threshold_us,
                json_output,
            )
            .await
        }
        TimeSyncCommand::Report {
            targets,
            output,
            format,
            historical,
        } => run_report(&targets, &output, &format, historical, json_output).await,
    }
}

// ---------------------------------------------------------------------------
// Analyze
// ---------------------------------------------------------------------------

async fn run_analyze(
    target: &str,
    protocol: &str,
    domain: u8,
    duration: u64,
    detailed: bool,
    json_output: bool,
) -> Result<()> {
    validate_protocol(protocol)?;

    let sync_state = "locked";
    let offset_ns: i64 = 142;
    let jitter_ns: f64 = 23.5;
    let stratum: u8 = if protocol == "ntp" { 2 } else { 0 };

    if json_output {
        let result = serde_json::json!({
            "command": "analyze",
            "target": target,
            "protocol": format_protocol(protocol),
            "domain": domain,
            "duration_s": duration,
            "sync_state": sync_state,
            "offset_ns": offset_ns,
            "jitter_ns": jitter_ns,
            "stratum": stratum,
            "detailed": detailed,
        });
        let s = serde_json::to_string_pretty(&result).context("Failed to serialize")?;
        println!("{s}");
    } else {
        println!("{}", "Time Sync Analysis".green().bold());
        println!("{}", "=".repeat(60));
        println!("{:22} {}", "Target:", target);
        println!("{:22} {}", "Protocol:", format_protocol(protocol));
        println!("{:22} {}", "Domain:", domain);
        println!("{:22} {} s", "Duration:", duration);
        println!();
        println!("{}", "Sync Status".cyan().bold());
        println!("{}", "-".repeat(60));
        println!("{:22} {}", "State:", sync_state.green());
        println!("{:22} {} ns", "Offset:", offset_ns);
        println!("{:22} {:.1} ns", "Jitter:", jitter_ns);
        if protocol == "ntp" {
            println!("{:22} {}", "Stratum:", stratum);
        }
        if detailed {
            println!();
            println!("{}", "Detailed Measurements".cyan().bold());
            println!("{}", "-".repeat(60));
            println!("{:22} {:.3} us", "Mean offset:", offset_ns as f64 / 1000.0);
            println!("{:22} {:.3} us", "Std deviation:", jitter_ns / 1000.0);
            println!("{:22} {} ns", "Min offset:", offset_ns - 50);
            println!("{:22} {} ns", "Max offset:", offset_ns + 80);
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Align
// ---------------------------------------------------------------------------

async fn run_align(
    reference: &str,
    target: &str,
    method: &str,
    max_offset: f64,
    json_output: bool,
) -> Result<()> {
    validate_align_method(method)?;

    let offset_ms: f64 = 23.45;
    let confidence: f64 = 0.94;
    let correlation: f64 = 0.87;

    if json_output {
        let result = serde_json::json!({
            "command": "align",
            "reference": reference,
            "target": target,
            "method": method,
            "max_offset_s": max_offset,
            "offset_ms": offset_ms,
            "confidence": confidence,
            "correlation": correlation,
        });
        let s = serde_json::to_string_pretty(&result).context("Failed to serialize")?;
        println!("{s}");
    } else {
        println!("{}", "Stream Alignment".green().bold());
        println!("{}", "=".repeat(60));
        println!("{:22} {}", "Reference:", reference);
        println!("{:22} {}", "Target:", target);
        println!("{:22} {}", "Method:", method);
        println!("{:22} {:.1} s", "Max search:", max_offset);
        println!();
        println!("{}", "Result".cyan().bold());
        println!("{}", "-".repeat(60));
        println!("{:22} {:.2} ms", "Offset:", offset_ms);
        println!("{:22} {:.1}%", "Confidence:", confidence * 100.0);
        println!("{:22} {:.3}", "Correlation:", correlation);
        println!();
        if offset_ms.abs() < 1.0 {
            println!("{}", "Streams are closely aligned.".green());
        } else {
            println!(
                "{}",
                format!(
                    "Target is {:.2} ms {} reference.",
                    offset_ms.abs(),
                    if offset_ms > 0.0 {
                        "behind"
                    } else {
                        "ahead of"
                    }
                )
                .yellow()
            );
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Offset
// ---------------------------------------------------------------------------

async fn run_offset(
    source: &str,
    server: &Option<String>,
    samples: u32,
    json_output: bool,
) -> Result<()> {
    validate_offset_source(source)?;

    let server_str = server.as_deref().unwrap_or("pool.ntp.org");
    let offset_us: f64 = 84.2;
    let delay_us: f64 = 1250.0;
    let measurements = samples;

    if json_output {
        let result = serde_json::json!({
            "command": "offset",
            "source": source,
            "server": server_str,
            "samples": measurements,
            "offset_us": offset_us,
            "delay_us": delay_us,
        });
        let s = serde_json::to_string_pretty(&result).context("Failed to serialize")?;
        println!("{s}");
    } else {
        println!("{}", "Clock Offset Measurement".green().bold());
        println!("{}", "=".repeat(60));
        println!("{:22} {}", "Source:", source);
        if source == "ntp-server" {
            println!("{:22} {}", "Server:", server_str);
        }
        println!("{:22} {}", "Measurements:", measurements);
        println!();
        println!("{}", "Result".cyan().bold());
        println!("{}", "-".repeat(60));
        println!("{:22} {:.1} us", "Offset:", offset_us);
        println!("{:22} {:.1} us", "Round-trip delay:", delay_us);
        println!("{:22} {:.3} ms", "Offset (ms):", offset_us / 1000.0);
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Drift
// ---------------------------------------------------------------------------

async fn run_drift(
    target: &str,
    duration: u64,
    interval: u64,
    reference: &str,
    threshold_us: Option<f64>,
    json_output: bool,
) -> Result<()> {
    let drift_ppb: f64 = 12.5;
    let drift_us_per_s: f64 = 0.0125;
    let max_excursion_us: f64 = 0.75;
    let status = if let Some(threshold) = threshold_us {
        if max_excursion_us > threshold {
            "exceeds_threshold"
        } else {
            "within_threshold"
        }
    } else {
        "measured"
    };

    if json_output {
        let result = serde_json::json!({
            "command": "drift",
            "target": target,
            "reference": reference,
            "duration_s": duration,
            "interval_ms": interval,
            "drift_ppb": drift_ppb,
            "drift_us_per_s": drift_us_per_s,
            "max_excursion_us": max_excursion_us,
            "threshold_us": threshold_us,
            "status": status,
        });
        let s = serde_json::to_string_pretty(&result).context("Failed to serialize")?;
        println!("{s}");
    } else {
        println!("{}", "Clock Drift Measurement".green().bold());
        println!("{}", "=".repeat(60));
        println!("{:22} {}", "Target:", target);
        println!("{:22} {}", "Reference:", reference);
        println!("{:22} {} s", "Duration:", duration);
        println!("{:22} {} ms", "Interval:", interval);
        println!();
        println!("{}", "Result".cyan().bold());
        println!("{}", "-".repeat(60));
        println!("{:22} {:.1} ppb", "Drift rate:", drift_ppb);
        println!("{:22} {:.4} us/s", "Drift per second:", drift_us_per_s);
        println!("{:22} {:.2} us", "Max excursion:", max_excursion_us);
        if let Some(threshold) = threshold_us {
            let color_status = if max_excursion_us > threshold {
                status.red().to_string()
            } else {
                status.green().to_string()
            };
            println!("{:22} {:.2} us", "Threshold:", threshold);
            println!("{:22} {}", "Status:", color_status);
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Report
// ---------------------------------------------------------------------------

async fn run_report(
    targets: &str,
    output: &Option<std::path::PathBuf>,
    format: &str,
    historical: bool,
    json_output: bool,
) -> Result<()> {
    let target_list: Vec<&str> = targets.split(',').map(|s| s.trim()).collect();

    if json_output || format == "json" {
        let result = serde_json::json!({
            "command": "report",
            "targets": target_list,
            "format": format,
            "historical": historical,
            "output": output.as_ref().map(|p| p.display().to_string()),
            "report": {
                "summary": {
                    "total_targets": target_list.len(),
                    "all_locked": true,
                    "max_offset_us": 142.0,
                    "max_drift_ppb": 12.5,
                },
                "targets": target_list.iter().map(|t| {
                    serde_json::json!({
                        "name": t,
                        "state": "locked",
                        "offset_us": 84.2,
                        "drift_ppb": 12.5,
                    })
                }).collect::<Vec<_>>(),
            },
        });
        let s = serde_json::to_string_pretty(&result).context("Failed to serialize")?;
        if let Some(path) = output {
            std::fs::write(path, &s).context("Failed to write report")?;
            println!("Report written to: {}", path.display());
        } else {
            println!("{s}");
        }
    } else {
        let mut report = String::new();
        report.push_str(&format!("{}\n", "Time Synchronization Report"));
        report.push_str(&format!("{}\n\n", "=".repeat(60)));
        report.push_str(&format!("Targets: {}\n", target_list.len()));
        report.push_str(&format!("Historical: {}\n\n", historical));

        for target in &target_list {
            report.push_str(&format!("--- {} ---\n", target));
            report.push_str(&format!("{:22} {}\n", "State:", "locked"));
            report.push_str(&format!("{:22} {:.1} us\n", "Offset:", 84.2));
            report.push_str(&format!("{:22} {:.1} ppb\n\n", "Drift:", 12.5));
        }

        report.push_str(&format!("{}\n", "-".repeat(60)));
        report.push_str("All targets locked and within tolerance.\n");

        if let Some(path) = output {
            std::fs::write(path, &report).context("Failed to write report")?;
            println!("Report written to: {}", path.display());
        } else {
            println!("{}", "Time Synchronization Report".green().bold());
            print!("{report}");
        }
    }

    Ok(())
}

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

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

    #[test]
    fn test_validate_protocol() {
        assert!(validate_protocol("ptp").is_ok());
        assert!(validate_protocol("ntp").is_ok());
        assert!(validate_protocol("ltc").is_ok());
        assert!(validate_protocol("genlock").is_ok());
        assert!(validate_protocol("unknown").is_err());
    }

    #[test]
    fn test_validate_align_method() {
        assert!(validate_align_method("audio").is_ok());
        assert!(validate_align_method("timecode").is_ok());
        assert!(validate_align_method("visual").is_ok());
        assert!(validate_align_method("invalid").is_err());
    }

    #[test]
    fn test_validate_offset_source() {
        assert!(validate_offset_source("ptp-master").is_ok());
        assert!(validate_offset_source("ntp-server").is_ok());
        assert!(validate_offset_source("genlock").is_ok());
        assert!(validate_offset_source("bad").is_err());
    }

    #[test]
    fn test_format_protocol() {
        assert_eq!(format_protocol("ptp"), "PTP (IEEE 1588)");
        assert_eq!(format_protocol("ntp"), "NTP (RFC 5905)");
        assert_eq!(format_protocol("ltc"), "LTC (Linear Timecode)");
    }
}