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
//! Meter rendering and visualization.
//!
//! Provides data structures and utilities for rendering meters visually.
use crate::{MeteringError, MeteringResult};
/// Color in RGB format.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Color {
/// Red component (0-255).
pub r: u8,
/// Green component (0-255).
pub g: u8,
/// Blue component (0-255).
pub b: u8,
}
impl Color {
/// Create a new color.
pub const fn new(r: u8, g: u8, b: u8) -> Self {
Self { r, g, b }
}
/// Create a color from hex string (e.g., "#FF0000" for red).
pub fn from_hex(hex: &str) -> MeteringResult<Self> {
let hex = hex.trim_start_matches('#');
if hex.len() != 6 {
return Err(MeteringError::InvalidConfig(
"Hex color must be 6 characters".to_string(),
));
}
let r = u8::from_str_radix(&hex[0..2], 16)
.map_err(|_| MeteringError::InvalidConfig("Invalid hex color".to_string()))?;
let g = u8::from_str_radix(&hex[2..4], 16)
.map_err(|_| MeteringError::InvalidConfig("Invalid hex color".to_string()))?;
let b = u8::from_str_radix(&hex[4..6], 16)
.map_err(|_| MeteringError::InvalidConfig("Invalid hex color".to_string()))?;
Ok(Self { r, g, b })
}
/// Interpolate between two colors.
///
/// # Arguments
///
/// * `other` - The other color
/// * `t` - Interpolation factor (0.0 to 1.0)
pub fn lerp(&self, other: &Self, t: f64) -> Self {
let t = t.clamp(0.0, 1.0);
Self {
r: (f64::from(self.r) + (f64::from(other.r) - f64::from(self.r)) * t) as u8,
g: (f64::from(self.g) + (f64::from(other.g) - f64::from(self.g)) * t) as u8,
b: (f64::from(self.b) + (f64::from(other.b) - f64::from(self.b)) * t) as u8,
}
}
}
/// Common meter colors.
pub mod colors {
use super::Color;
/// Green (safe zone).
pub const GREEN: Color = Color::new(0, 255, 0);
/// Yellow (warning zone).
pub const YELLOW: Color = Color::new(255, 255, 0);
/// Red (danger zone).
pub const RED: Color = Color::new(255, 0, 0);
/// Dark green (lower range).
pub const DARK_GREEN: Color = Color::new(0, 128, 0);
/// Orange (intermediate warning).
pub const ORANGE: Color = Color::new(255, 165, 0);
/// Black (background).
pub const BLACK: Color = Color::new(0, 0, 0);
/// White (foreground/text).
pub const WHITE: Color = Color::new(255, 255, 255);
/// Dark gray (scale markings).
pub const DARK_GRAY: Color = Color::new(64, 64, 64);
/// Light gray (grid).
pub const LIGHT_GRAY: Color = Color::new(192, 192, 192);
}
/// Meter orientation.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Orientation {
/// Horizontal meter (left to right).
Horizontal,
/// Vertical meter (bottom to top).
Vertical,
}
/// Meter scale type.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ScaleType {
/// Linear scale.
Linear,
/// Logarithmic scale (dB).
Logarithmic,
}
/// Color gradient for meter display.
#[derive(Clone, Debug)]
pub struct ColorGradient {
stops: Vec<(f64, Color)>,
}
impl ColorGradient {
/// Create a new color gradient.
///
/// # Arguments
///
/// * `stops` - List of (position, color) tuples where position is 0.0 to 1.0
pub fn new(stops: Vec<(f64, Color)>) -> Self {
Self { stops }
}
/// Create a standard traffic light gradient (green -> yellow -> red).
pub fn traffic_light() -> Self {
Self::new(vec![
(0.0, colors::DARK_GREEN),
(0.6, colors::GREEN),
(0.8, colors::YELLOW),
(0.95, colors::ORANGE),
(1.0, colors::RED),
])
}
/// Create a standard PPM gradient.
pub fn ppm() -> Self {
Self::new(vec![
(0.0, colors::DARK_GREEN),
(0.7, colors::GREEN),
(0.9, colors::YELLOW),
(1.0, colors::RED),
])
}
/// Get the color at a specific position.
///
/// # Arguments
///
/// * `position` - Position in gradient (0.0 to 1.0)
pub fn color_at(&self, position: f64) -> Color {
let position = position.clamp(0.0, 1.0);
// Find the two stops to interpolate between
for i in 0..self.stops.len() - 1 {
let (pos1, color1) = self.stops[i];
let (pos2, color2) = self.stops[i + 1];
if position >= pos1 && position <= pos2 {
let range = pos2 - pos1;
let t = if range > 0.0 {
(position - pos1) / range
} else {
0.0
};
return color1.lerp(&color2, t);
}
}
// Return last color if position is beyond all stops
self.stops.last().map_or(colors::BLACK, |(_, c)| *c)
}
}
/// Bar meter renderer configuration.
#[derive(Clone, Debug)]
pub struct BarMeterConfig {
/// Meter orientation.
pub orientation: Orientation,
/// Meter width in pixels.
pub width: usize,
/// Meter height in pixels.
pub height: usize,
/// Minimum value (e.g., -60.0 dBFS).
pub min_value: f64,
/// Maximum value (e.g., 0.0 dBFS).
pub max_value: f64,
/// Scale type.
pub scale_type: ScaleType,
/// Color gradient.
pub gradient: ColorGradient,
/// Show peak hold indicator.
pub show_peak_hold: bool,
/// Show scale markings.
pub show_scale: bool,
}
impl Default for BarMeterConfig {
fn default() -> Self {
Self {
orientation: Orientation::Vertical,
width: 30,
height: 200,
min_value: -60.0,
max_value: 0.0,
scale_type: ScaleType::Logarithmic,
gradient: ColorGradient::traffic_light(),
show_peak_hold: true,
show_scale: true,
}
}
}
/// Bar meter render data.
#[derive(Clone, Debug)]
pub struct BarMeterData {
/// Current level (0.0 to 1.0 normalized).
pub level: f64,
/// Peak hold level (0.0 to 1.0 normalized).
pub peak_hold: f64,
/// Whether the meter is clipping.
pub is_clipping: bool,
}
impl BarMeterData {
/// Create bar meter data from dBFS values.
///
/// # Arguments
///
/// * `level_dbfs` - Current level in dBFS
/// * `peak_hold_dbfs` - Peak hold level in dBFS
/// * `min_dbfs` - Minimum dBFS for normalization
/// * `max_dbfs` - Maximum dBFS for normalization
pub fn from_dbfs(level_dbfs: f64, peak_hold_dbfs: f64, min_dbfs: f64, max_dbfs: f64) -> Self {
let normalize = |db: f64| {
if db.is_infinite() && db.is_sign_negative() {
0.0
} else {
((db - min_dbfs) / (max_dbfs - min_dbfs)).clamp(0.0, 1.0)
}
};
Self {
level: normalize(level_dbfs),
peak_hold: normalize(peak_hold_dbfs),
is_clipping: level_dbfs >= max_dbfs,
}
}
}
/// Scale marking on a meter.
#[derive(Clone, Debug)]
pub struct ScaleMark {
/// Position (0.0 to 1.0).
pub position: f64,
/// Label text.
pub label: String,
/// Whether this is a major marking.
pub is_major: bool,
}
/// Generate scale markings for a dBFS meter.
pub fn generate_db_scale(min_db: f64, max_db: f64) -> Vec<ScaleMark> {
let mut marks = Vec::new();
let range = max_db - min_db;
// Major markings every 10 dB
let mut db = (min_db / 10.0).ceil() * 10.0;
while db <= max_db {
let position = (db - min_db) / range;
marks.push(ScaleMark {
position,
label: format!("{db:.0}"),
is_major: true,
});
db += 10.0;
}
// Minor markings every 5 dB
let mut db = (min_db / 5.0).ceil() * 5.0;
while db <= max_db {
let position = (db - min_db) / range;
// Skip if this is already a major marking
if !marks.iter().any(|m| (m.position - position).abs() < 0.01) {
marks.push(ScaleMark {
position,
label: String::new(),
is_major: false,
});
}
db += 5.0;
}
marks
}
/// One column of a waveform display (oscilloscope-style per-pixel envelope).
#[derive(Debug, Clone)]
pub struct WaveformColumn {
/// Minimum sample value in this column's time window.
pub min: f32,
/// Maximum sample value in this column's time window.
pub max: f32,
/// Root-mean-square level in this column's time window.
pub rms: f32,
}
/// Per-pixel waveform envelope data suitable for oscilloscope display.
#[derive(Debug, Clone)]
pub struct WaveformData {
/// Ordered list of per-column envelope data, one entry per display pixel column.
pub columns: Vec<WaveformColumn>,
}
impl WaveformData {
/// Generate waveform display data from interleaved audio samples.
///
/// `samples` — mono or interleaved audio (use channel 0 for simplicity)
/// `width` — number of display columns (pixels wide)
pub fn generate(samples: &[f32], width: usize) -> Self {
if samples.is_empty() || width == 0 {
return Self { columns: vec![] };
}
let mut columns = Vec::with_capacity(width);
for col in 0..width {
let start = col * samples.len() / width;
let end = ((col + 1) * samples.len() / width)
.max(start + 1)
.min(samples.len());
let segment = &samples[start..end];
let mut min = f32::INFINITY;
let mut max = f32::NEG_INFINITY;
let mut sum_sq = 0.0f32;
for &s in segment {
if s < min {
min = s;
}
if s > max {
max = s;
}
sum_sq += s * s;
}
let rms = (sum_sq / segment.len() as f32).sqrt();
columns.push(WaveformColumn { min, max, rms });
}
Self { columns }
}
}
/// One bin in a vectorscope display grid.
#[derive(Debug, Clone, Default)]
pub struct VectorscopeBin {
/// Accumulated hit count for this (x, y) position.
pub count: u32,
}
/// Vectorscope data for chroma/phase display.
#[derive(Debug, Clone)]
pub struct VectorscopeData {
/// 2D grid of bins, row-major: bins[y * width + x].
pub bins: Vec<VectorscopeBin>,
/// Horizontal dimension of the bin grid in pixels.
pub width: usize,
/// Vertical dimension of the bin grid in pixels.
pub height: usize,
}
/// Polar reference point for the 75% color bar graticule.
#[derive(Debug, Clone)]
pub struct GraticulePoint {
/// Normalized X coordinate in [-1, 1].
pub x: f32,
/// Normalized Y coordinate in [-1, 1].
pub y: f32,
/// Short human-readable label for this color bar reference (e.g. "Y", "C", "G").
pub label: &'static str,
}
impl VectorscopeData {
/// Generate vectorscope data from (Cb, Cr) chroma pairs in [-0.5, 0.5].
///
/// Cb maps to X axis, Cr maps to Y axis.
/// Values outside [-0.5, 0.5] are clamped to the grid boundary.
pub fn generate(cb_cr_pairs: &[(f32, f32)], width: usize, height: usize) -> Self {
let bins = vec![VectorscopeBin::default(); width * height];
let mut data = Self {
bins,
width,
height,
};
for &(cb, cr) in cb_cr_pairs {
// Map [-0.5, 0.5] → [0, width/height)
let nx = ((cb + 0.5).clamp(0.0, 1.0) * (width - 1) as f32) as usize;
let ny = ((cr + 0.5).clamp(0.0, 1.0) * (height - 1) as f32) as usize;
let idx = ny * width + nx;
if idx < data.bins.len() {
data.bins[idx].count = data.bins[idx].count.saturating_add(1);
}
}
data
}
/// Returns the 8 standard 75% color-bar reference points in (Cb, Cr) space.
pub fn graticule_75pct_bar() -> Vec<GraticulePoint> {
// Standard 75% color-bar CbCr values (BT.601/BT.709 approximate)
vec![
GraticulePoint {
x: -0.169,
y: 0.500,
label: "Y",
}, // Yellow
GraticulePoint {
x: -0.338,
y: -0.169,
label: "C",
}, // Cyan
GraticulePoint {
x: -0.169,
y: -0.338,
label: "G",
}, // Green
GraticulePoint {
x: 0.169,
y: 0.169,
label: "M",
}, // Magenta
GraticulePoint {
x: 0.500,
y: 0.169,
label: "R",
}, // Red
GraticulePoint {
x: 0.338,
y: -0.169,
label: "B",
}, // Blue
GraticulePoint {
x: 0.0,
y: 0.0,
label: "W",
}, // White (origin)
GraticulePoint {
x: 0.0,
y: 0.0,
label: "K",
}, // Black (origin)
]
}
}
/// Circular meter configuration for radial displays.
#[derive(Clone, Debug)]
pub struct CircularMeterConfig {
/// Center X coordinate.
pub center_x: usize,
/// Center Y coordinate.
pub center_y: usize,
/// Radius in pixels.
pub radius: usize,
/// Start angle in degrees (0 = right, 90 = top).
pub start_angle: f64,
/// End angle in degrees.
pub end_angle: f64,
/// Color gradient.
pub gradient: ColorGradient,
}
impl Default for CircularMeterConfig {
fn default() -> Self {
Self {
center_x: 100,
center_y: 100,
radius: 80,
start_angle: 135.0, // Lower left
end_angle: 45.0, // Lower right
gradient: ColorGradient::traffic_light(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_color_creation() {
let color = Color::new(255, 128, 64);
assert_eq!(color.r, 255);
assert_eq!(color.g, 128);
assert_eq!(color.b, 64);
}
#[test]
fn test_color_from_hex() {
let color = Color::from_hex("#FF8040").expect("color should be valid");
assert_eq!(color.r, 255);
assert_eq!(color.g, 128);
assert_eq!(color.b, 64);
}
#[test]
fn test_color_lerp() {
let c1 = Color::new(0, 0, 0);
let c2 = Color::new(255, 255, 255);
let mid = c1.lerp(&c2, 0.5);
assert!(mid.r > 120 && mid.r < 135);
assert!(mid.g > 120 && mid.g < 135);
assert!(mid.b > 120 && mid.b < 135);
}
#[test]
fn test_gradient() {
let gradient = ColorGradient::traffic_light();
let color_low = gradient.color_at(0.0);
let color_high = gradient.color_at(1.0);
// Low should be greenish, high should be reddish
assert!(color_low.g > color_low.r);
assert!(color_high.r > color_high.g);
}
#[test]
fn test_bar_meter_data_from_dbfs() {
let data = BarMeterData::from_dbfs(-10.0, -5.0, -60.0, 0.0);
assert!(data.level > 0.8); // -10 dB is high on -60 to 0 scale
assert!(data.peak_hold > 0.9); // -5 dB is very high
}
#[test]
fn test_bar_meter_data_clipping() {
let data = BarMeterData::from_dbfs(0.5, 0.5, -60.0, 0.0);
assert!(data.is_clipping);
}
#[test]
fn test_generate_db_scale() {
let marks = generate_db_scale(-60.0, 0.0);
assert!(!marks.is_empty());
// Should have markings at 0, -10, -20, etc.
let has_zero = marks.iter().any(|m| m.label == "0");
let has_minus_10 = marks.iter().any(|m| m.label == "-10");
assert!(has_zero);
assert!(has_minus_10);
}
#[test]
fn test_default_configs() {
let bar_config = BarMeterConfig::default();
assert_eq!(bar_config.min_value, -60.0);
assert_eq!(bar_config.max_value, 0.0);
let circular_config = CircularMeterConfig::default();
assert_eq!(circular_config.radius, 80);
}
#[test]
fn test_waveform_column_bounds_samples() {
let samples: Vec<f32> = (0..100).map(|i| (i as f32 / 50.0) - 1.0).collect();
let data = WaveformData::generate(&samples, 10);
assert_eq!(data.columns.len(), 10);
for col in &data.columns {
// Every sample in the segment must lie within [min, max]
assert!(col.min <= col.max);
assert!(col.rms >= 0.0 && col.rms <= 1.0 + 1e-6);
}
}
#[test]
fn test_waveform_column_count() {
let samples = vec![0.0f32; 100];
let data = WaveformData::generate(&samples, 16);
assert_eq!(data.columns.len(), 16);
}
#[test]
fn test_waveform_empty_returns_empty() {
let data = WaveformData::generate(&[], 10);
assert!(data.columns.is_empty());
let data2 = WaveformData::generate(&[0.1, 0.2], 0);
assert!(data2.columns.is_empty());
}
#[test]
fn test_vectorscope_correct_quadrant() {
// (Cb=0.25, Cr=0.25) → right-top quadrant (x > width/2, y > height/2)
let pairs = vec![(0.25f32, 0.25f32)];
let data = VectorscopeData::generate(&pairs, 32, 32);
// Find the bin with count > 0
let hit = data
.bins
.iter()
.position(|b| b.count > 0)
.expect("expected a hit bin");
let hx = hit % 32;
let hy = hit / 32;
assert!(hx > 16, "x should be in right half for Cb=0.25");
assert!(hy > 16, "y should be in top half for Cr=0.25");
}
#[test]
fn test_vectorscope_bin_accumulation() {
let pairs = vec![(0.0f32, 0.0f32); 5]; // 5 identical pairs → bin count = 5
let data = VectorscopeData::generate(&pairs, 16, 16);
let total: u32 = data.bins.iter().map(|b| b.count).sum();
assert_eq!(total, 5);
}
#[test]
fn test_graticule_has_8_points() {
let graticule = VectorscopeData::graticule_75pct_bar();
assert_eq!(graticule.len(), 8);
// All points should be in [-0.5, 0.5]
for p in &graticule {
assert!(p.x.abs() <= 0.55, "x={} out of range", p.x);
assert!(p.y.abs() <= 0.55, "y={} out of range", p.y);
}
}
}