oximedia-scene 0.1.8

Scene understanding and AI-powered video analysis 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
#![allow(dead_code)]
//! Action beat detection and analysis for video scenes.
//!
//! An *action beat* is a discrete unit of dramatic or physical action within a
//! scene — a punch, a door opening, a character reaction, a camera cut timed
//! to music.  This module quantifies beats by analysing motion energy, audio
//! transients, and cut timing, making it useful for:
//!
//! - Pacing analysis (beats per minute of a scene)
//! - Highlight detection in sports / action footage
//! - Edit-point suggestion aligned with dramatic beats
//! - Synchronisation of cuts to music beats

use std::fmt;

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Category of an action beat.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BeatCategory {
    /// High-motion physical action (fight, chase, explosion).
    PhysicalAction,
    /// Dialogue emphasis or dramatic reaction.
    DramaticReaction,
    /// Camera movement beat (whip pan, zoom, crane).
    CameraMove,
    /// Edit cut synchronised to audio.
    RhythmicCut,
    /// Audio transient (loud hit, crash, music accent).
    AudioTransient,
    /// Generic / unclassified beat.
    Generic,
}

impl fmt::Display for BeatCategory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PhysicalAction => write!(f, "PhysicalAction"),
            Self::DramaticReaction => write!(f, "DramaticReaction"),
            Self::CameraMove => write!(f, "CameraMove"),
            Self::RhythmicCut => write!(f, "RhythmicCut"),
            Self::AudioTransient => write!(f, "AudioTransient"),
            Self::Generic => write!(f, "Generic"),
        }
    }
}

/// A detected action beat.
#[derive(Debug, Clone)]
pub struct ActionBeat {
    /// Timestamp in seconds.
    pub timestamp: f64,
    /// Duration of the beat in seconds.
    pub duration: f64,
    /// Intensity / energy of the beat (0..1).
    pub intensity: f64,
    /// Category of the beat.
    pub category: BeatCategory,
    /// Confidence of the detection (0..1).
    pub confidence: f64,
}

/// Aggregate statistics about beats in a segment.
#[derive(Debug, Clone)]
pub struct BeatStats {
    /// Total number of beats.
    pub count: usize,
    /// Average beats per minute.
    pub bpm: f64,
    /// Average beat intensity.
    pub avg_intensity: f64,
    /// Maximum beat intensity.
    pub max_intensity: f64,
    /// Standard deviation of inter-beat intervals.
    pub interval_std_dev: f64,
    /// Dominant beat category.
    pub dominant_category: BeatCategory,
}

/// Configuration for the beat detector.
#[derive(Debug, Clone)]
pub struct BeatDetectorConfig {
    /// Minimum motion energy to register a beat.
    pub motion_threshold: f64,
    /// Minimum audio energy to register a transient.
    pub audio_threshold: f64,
    /// Minimum time between consecutive beats (seconds).
    pub min_interval: f64,
    /// Look-ahead window (seconds) for peak picking.
    pub window_size: f64,
    /// Whether to merge nearby beats.
    pub merge_nearby: bool,
    /// Merge distance in seconds.
    pub merge_distance: f64,
}

/// A time-stamped energy sample used as detector input.
#[derive(Debug, Clone, Copy)]
pub struct EnergySample {
    /// Timestamp in seconds.
    pub time: f64,
    /// Motion energy (0..1).
    pub motion: f64,
    /// Audio energy (0..1).
    pub audio: f64,
}

/// Pacing profile derived from beat analysis.
#[derive(Debug, Clone)]
pub struct PacingProfile {
    /// Time segments and their BPM values.
    pub segments: Vec<PacingSegment>,
    /// Overall average BPM.
    pub overall_bpm: f64,
    /// Pacing trend over the scene (-1 = decelerating, 0 = steady, 1 = accelerating).
    pub trend: f64,
}

/// A single pacing segment.
#[derive(Debug, Clone)]
pub struct PacingSegment {
    /// Start time in seconds.
    pub start: f64,
    /// End time in seconds.
    pub end: f64,
    /// Beats per minute in this segment.
    pub bpm: f64,
}

// ---------------------------------------------------------------------------
// Implementations
// ---------------------------------------------------------------------------

impl Default for BeatDetectorConfig {
    fn default() -> Self {
        Self {
            motion_threshold: 0.25,
            audio_threshold: 0.3,
            min_interval: 0.15,
            window_size: 0.5,
            merge_nearby: true,
            merge_distance: 0.1,
        }
    }
}

/// Detect action beats from energy samples.
pub fn detect_beats(samples: &[EnergySample], config: &BeatDetectorConfig) -> Vec<ActionBeat> {
    if samples.is_empty() {
        return Vec::new();
    }

    let mut beats: Vec<ActionBeat> = Vec::new();

    for (i, s) in samples.iter().enumerate() {
        let combined = s.motion * 0.6 + s.audio * 0.4;
        let is_peak = combined > config.motion_threshold.min(config.audio_threshold);

        // Simple local-maximum check
        if is_peak {
            let prev_ok = if i > 0 {
                let pc = samples[i - 1].motion * 0.6 + samples[i - 1].audio * 0.4;
                combined >= pc
            } else {
                true
            };
            let next_ok = if i + 1 < samples.len() {
                let nc = samples[i + 1].motion * 0.6 + samples[i + 1].audio * 0.4;
                combined >= nc
            } else {
                true
            };
            if prev_ok && next_ok {
                // Enforce minimum interval
                let too_close = beats
                    .last()
                    .is_some_and(|b: &ActionBeat| s.time - b.timestamp < config.min_interval);
                if !too_close {
                    let category = classify_beat(s);
                    beats.push(ActionBeat {
                        timestamp: s.time,
                        duration: config.window_size,
                        intensity: combined.min(1.0),
                        category,
                        confidence: combined.min(1.0),
                    });
                }
            }
        }
    }

    if config.merge_nearby {
        merge_beats(&mut beats, config.merge_distance);
    }

    beats
}

/// Classify a beat based on motion vs audio dominance.
fn classify_beat(sample: &EnergySample) -> BeatCategory {
    if sample.motion > 0.7 {
        BeatCategory::PhysicalAction
    } else if sample.audio > 0.7 {
        BeatCategory::AudioTransient
    } else if sample.motion > 0.4 && sample.audio > 0.4 {
        BeatCategory::RhythmicCut
    } else if sample.motion > sample.audio {
        BeatCategory::CameraMove
    } else {
        BeatCategory::Generic
    }
}

/// Merge beats that are closer than `distance` seconds.
fn merge_beats(beats: &mut Vec<ActionBeat>, distance: f64) {
    if beats.len() < 2 {
        return;
    }
    let mut merged = vec![beats[0].clone()];
    for b in beats.iter().skip(1) {
        if let Some(last) = merged.last_mut() {
            if b.timestamp - last.timestamp < distance {
                last.intensity = last.intensity.max(b.intensity);
                last.duration = b.timestamp - last.timestamp + b.duration;
                continue;
            }
        }
        merged.push(b.clone());
    }
    *beats = merged;
}

/// Compute aggregate beat statistics.
#[allow(clippy::cast_precision_loss)]
pub fn compute_beat_stats(beats: &[ActionBeat], duration_secs: f64) -> BeatStats {
    if beats.is_empty() || duration_secs <= 0.0 {
        return BeatStats {
            count: 0,
            bpm: 0.0,
            avg_intensity: 0.0,
            max_intensity: 0.0,
            interval_std_dev: 0.0,
            dominant_category: BeatCategory::Generic,
        };
    }

    let count = beats.len();
    let bpm = count as f64 / duration_secs * 60.0;
    let avg_intensity = beats.iter().map(|b| b.intensity).sum::<f64>() / count as f64;
    let max_intensity = beats.iter().map(|b| b.intensity).fold(0.0f64, f64::max);

    // Inter-beat interval statistics
    let intervals: Vec<f64> = beats
        .windows(2)
        .map(|w| w[1].timestamp - w[0].timestamp)
        .collect();
    let interval_std_dev = if intervals.len() > 1 {
        let mean_iv = intervals.iter().sum::<f64>() / intervals.len() as f64;
        let var =
            intervals.iter().map(|v| (v - mean_iv).powi(2)).sum::<f64>() / intervals.len() as f64;
        var.sqrt()
    } else {
        0.0
    };

    // Dominant category by count
    let mut counts = [0usize; 6];
    for b in beats {
        let idx = match b.category {
            BeatCategory::PhysicalAction => 0,
            BeatCategory::DramaticReaction => 1,
            BeatCategory::CameraMove => 2,
            BeatCategory::RhythmicCut => 3,
            BeatCategory::AudioTransient => 4,
            BeatCategory::Generic => 5,
        };
        counts[idx] += 1;
    }
    let dominant_idx = counts
        .iter()
        .enumerate()
        .max_by_key(|(_, &c)| c)
        .map_or(5, |(i, _)| i);
    let dominant_category = match dominant_idx {
        0 => BeatCategory::PhysicalAction,
        1 => BeatCategory::DramaticReaction,
        2 => BeatCategory::CameraMove,
        3 => BeatCategory::RhythmicCut,
        4 => BeatCategory::AudioTransient,
        _ => BeatCategory::Generic,
    };

    BeatStats {
        count,
        bpm,
        avg_intensity,
        max_intensity,
        interval_std_dev,
        dominant_category,
    }
}

/// Compute a pacing profile by windowing the beats.
#[allow(clippy::cast_precision_loss)]
pub fn compute_pacing(
    beats: &[ActionBeat],
    total_duration: f64,
    window_secs: f64,
) -> PacingProfile {
    if beats.is_empty() || total_duration <= 0.0 || window_secs <= 0.0 {
        return PacingProfile {
            segments: Vec::new(),
            overall_bpm: 0.0,
            trend: 0.0,
        };
    }

    let n_windows = (total_duration / window_secs).ceil() as usize;
    let mut segments = Vec::with_capacity(n_windows);

    for w in 0..n_windows {
        let start = w as f64 * window_secs;
        let end = (start + window_secs).min(total_duration);
        let count = beats
            .iter()
            .filter(|b| b.timestamp >= start && b.timestamp < end)
            .count();
        let dur = end - start;
        let bpm = if dur > 0.0 {
            count as f64 / dur * 60.0
        } else {
            0.0
        };
        segments.push(PacingSegment { start, end, bpm });
    }

    let overall_bpm = beats.len() as f64 / total_duration * 60.0;

    // Trend: simple linear regression slope of BPM over segment index
    let trend = if segments.len() >= 2 {
        let n = segments.len() as f64;
        let sum_x: f64 = (0..segments.len()).map(|i| i as f64).sum();
        let sum_y: f64 = segments.iter().map(|s| s.bpm).sum();
        let sum_xy: f64 = segments
            .iter()
            .enumerate()
            .map(|(i, s)| i as f64 * s.bpm)
            .sum();
        let sum_xx: f64 = (0..segments.len()).map(|i| (i as f64).powi(2)).sum();
        let denom = n * sum_xx - sum_x * sum_x;
        if denom.abs() > 1e-12 {
            let slope = (n * sum_xy - sum_x * sum_y) / denom;
            slope.clamp(-1.0, 1.0)
        } else {
            0.0
        }
    } else {
        0.0
    };

    PacingProfile {
        segments,
        overall_bpm,
        trend,
    }
}

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

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

    fn sample(time: f64, motion: f64, audio: f64) -> EnergySample {
        EnergySample {
            time,
            motion,
            audio,
        }
    }

    #[test]
    fn test_detect_beats_empty() {
        let beats = detect_beats(&[], &BeatDetectorConfig::default());
        assert!(beats.is_empty());
    }

    #[test]
    fn test_detect_beats_single_peak() {
        let samples = vec![
            sample(0.0, 0.0, 0.0),
            sample(0.5, 0.8, 0.6),
            sample(1.0, 0.0, 0.0),
        ];
        let beats = detect_beats(&samples, &BeatDetectorConfig::default());
        assert_eq!(beats.len(), 1);
        assert!((beats[0].timestamp - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_detect_beats_multiple() {
        let samples = vec![
            sample(0.0, 0.0, 0.0),
            sample(1.0, 0.9, 0.5),
            sample(2.0, 0.1, 0.1),
            sample(3.0, 0.5, 0.8),
            sample(4.0, 0.0, 0.0),
        ];
        let beats = detect_beats(&samples, &BeatDetectorConfig::default());
        assert!(beats.len() >= 2);
    }

    #[test]
    fn test_detect_beats_min_interval() {
        let samples = vec![
            sample(0.0, 0.5, 0.5),
            sample(0.05, 0.6, 0.6),
            sample(0.1, 0.5, 0.5),
        ];
        let cfg = BeatDetectorConfig {
            min_interval: 0.2,
            ..BeatDetectorConfig::default()
        };
        let beats = detect_beats(&samples, &cfg);
        assert!(beats.len() <= 1);
    }

    #[test]
    fn test_classify_physical_action() {
        let s = sample(0.0, 0.9, 0.1);
        assert_eq!(classify_beat(&s), BeatCategory::PhysicalAction);
    }

    #[test]
    fn test_classify_audio_transient() {
        let s = sample(0.0, 0.1, 0.9);
        assert_eq!(classify_beat(&s), BeatCategory::AudioTransient);
    }

    #[test]
    fn test_classify_rhythmic_cut() {
        let s = sample(0.0, 0.5, 0.5);
        assert_eq!(classify_beat(&s), BeatCategory::RhythmicCut);
    }

    #[test]
    fn test_compute_beat_stats_empty() {
        let stats = compute_beat_stats(&[], 10.0);
        assert_eq!(stats.count, 0);
        assert_eq!(stats.bpm, 0.0);
    }

    #[test]
    fn test_compute_beat_stats_values() {
        let beats = vec![
            ActionBeat {
                timestamp: 1.0,
                duration: 0.1,
                intensity: 0.8,
                category: BeatCategory::PhysicalAction,
                confidence: 0.9,
            },
            ActionBeat {
                timestamp: 3.0,
                duration: 0.1,
                intensity: 0.6,
                category: BeatCategory::PhysicalAction,
                confidence: 0.7,
            },
            ActionBeat {
                timestamp: 5.0,
                duration: 0.1,
                intensity: 0.9,
                category: BeatCategory::AudioTransient,
                confidence: 0.8,
            },
        ];
        let stats = compute_beat_stats(&beats, 6.0);
        assert_eq!(stats.count, 3);
        assert!((stats.bpm - 30.0).abs() < 1e-9);
        assert!((stats.max_intensity - 0.9).abs() < 1e-9);
        assert_eq!(stats.dominant_category, BeatCategory::PhysicalAction);
    }

    #[test]
    fn test_pacing_profile_empty() {
        let p = compute_pacing(&[], 10.0, 5.0);
        assert!(p.segments.is_empty());
        assert_eq!(p.overall_bpm, 0.0);
    }

    #[test]
    fn test_pacing_profile_segments() {
        let beats = vec![
            ActionBeat {
                timestamp: 1.0,
                duration: 0.1,
                intensity: 0.5,
                category: BeatCategory::Generic,
                confidence: 0.5,
            },
            ActionBeat {
                timestamp: 2.0,
                duration: 0.1,
                intensity: 0.5,
                category: BeatCategory::Generic,
                confidence: 0.5,
            },
            ActionBeat {
                timestamp: 7.0,
                duration: 0.1,
                intensity: 0.5,
                category: BeatCategory::Generic,
                confidence: 0.5,
            },
        ];
        let p = compute_pacing(&beats, 10.0, 5.0);
        assert_eq!(p.segments.len(), 2);
    }

    #[test]
    fn test_beat_category_display() {
        assert_eq!(
            format!("{}", BeatCategory::PhysicalAction),
            "PhysicalAction"
        );
        assert_eq!(
            format!("{}", BeatCategory::AudioTransient),
            "AudioTransient"
        );
    }

    #[test]
    fn test_merge_beats() {
        let mut beats = vec![
            ActionBeat {
                timestamp: 1.0,
                duration: 0.1,
                intensity: 0.5,
                category: BeatCategory::Generic,
                confidence: 0.5,
            },
            ActionBeat {
                timestamp: 1.05,
                duration: 0.1,
                intensity: 0.7,
                category: BeatCategory::Generic,
                confidence: 0.5,
            },
            ActionBeat {
                timestamp: 5.0,
                duration: 0.1,
                intensity: 0.3,
                category: BeatCategory::Generic,
                confidence: 0.5,
            },
        ];
        merge_beats(&mut beats, 0.1);
        assert_eq!(beats.len(), 2);
        assert!((beats[0].intensity - 0.7).abs() < 1e-9);
    }
}