oximedia-cv 0.1.3

Computer vision 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
//! Temporal fingerprinting for video content.
//!
//! This module provides temporal analysis and fingerprinting for video sequences:
//!
//! - **Keyframe extraction**: Identifies representative frames from video
//! - **Shot boundary detection**: Detects scene changes and cuts
//! - **Temporal signatures**: Creates time-based feature vectors
//! - **Frame sampling**: Intelligent frame selection strategies
//! - **Segment hashing**: Hashes video segments for partial matching

use crate::error::{CvError, CvResult};
use rayon::prelude::*;

/// Frame sampling strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SamplingStrategy {
    /// Uniform sampling at fixed intervals.
    Uniform,
    /// Adaptive sampling based on content changes.
    Adaptive,
    /// Scene-based sampling (one frame per scene).
    SceneBased,
    /// Keyframe-only sampling.
    KeyframeOnly,
}

/// Shot boundary detection result.
#[derive(Debug, Clone)]
pub struct ShotBoundary {
    /// Frame index where shot starts.
    pub start_frame: usize,
    /// Frame index where shot ends.
    pub end_frame: usize,
    /// Confidence score (0.0-1.0).
    pub confidence: f64,
    /// Type of transition (cut, fade, dissolve).
    pub transition_type: TransitionType,
}

/// Type of shot transition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransitionType {
    /// Hard cut (instant change).
    Cut,
    /// Fade to/from black.
    Fade,
    /// Dissolve/crossfade between scenes.
    Dissolve,
}

/// Keyframe with metadata.
#[derive(Debug, Clone)]
pub struct Keyframe {
    /// Frame index in original video.
    pub frame_index: usize,
    /// Frame image data (width, height, RGB).
    pub image: (u32, u32, Vec<u8>),
    /// Importance score (0.0-1.0).
    pub importance: f64,
}

/// Extracts keyframes from video frames.
///
/// # Arguments
///
/// * `frames` - Slice of video frames (width, height, RGB data)
/// * `min_interval` - Minimum frames between keyframes
/// * `max_keyframes` - Maximum number of keyframes to extract
/// * `scene_threshold` - Scene change threshold (0.0-1.0)
///
/// # Errors
///
/// Returns an error if extraction fails.
pub fn extract_keyframes(
    frames: &[(u32, u32, Vec<u8>)],
    min_interval: usize,
    max_keyframes: usize,
    scene_threshold: f64,
) -> CvResult<Vec<(u32, u32, Vec<u8>)>> {
    if frames.is_empty() {
        return Err(CvError::invalid_parameter("frames", "empty"));
    }

    if min_interval == 0 {
        return Err(CvError::invalid_parameter("min_interval", "0"));
    }

    // Detect scene boundaries
    let boundaries = detect_shot_boundaries(frames, scene_threshold)?;

    // Select keyframes based on scene boundaries and importance
    let mut keyframes = Vec::new();
    let mut last_keyframe_idx = 0;

    // Add first frame
    keyframes.push(frames[0].clone());

    // Add one keyframe per scene
    for boundary in &boundaries {
        let scene_start = boundary.start_frame;
        let scene_end = boundary.end_frame;

        if scene_start < last_keyframe_idx + min_interval {
            continue;
        }

        // Find most representative frame in scene (middle frame)
        let mid_frame = (scene_start + scene_end) / 2;
        if mid_frame < frames.len() && mid_frame >= last_keyframe_idx + min_interval {
            keyframes.push(frames[mid_frame].clone());
            last_keyframe_idx = mid_frame;
        }

        if keyframes.len() >= max_keyframes {
            break;
        }
    }

    // If we don't have enough keyframes, add uniform samples
    if keyframes.len() < max_keyframes {
        let interval = frames.len() / max_keyframes.max(1);
        let mut idx = interval;
        while idx < frames.len() && keyframes.len() < max_keyframes {
            if idx >= last_keyframe_idx + min_interval {
                keyframes.push(frames[idx].clone());
                last_keyframe_idx = idx;
            }
            idx += interval;
        }
    }

    Ok(keyframes)
}

/// Detects shot boundaries in video frames.
///
/// # Arguments
///
/// * `frames` - Slice of video frames
/// * `threshold` - Scene change threshold (0.0-1.0)
///
/// # Errors
///
/// Returns an error if detection fails.
pub fn detect_shot_boundaries(
    frames: &[(u32, u32, Vec<u8>)],
    threshold: f64,
) -> CvResult<Vec<ShotBoundary>> {
    if frames.len() < 2 {
        return Ok(Vec::new());
    }

    let mut boundaries = Vec::new();
    let mut scene_start = 0;

    // Compute frame differences
    let differences = compute_frame_differences(frames)?;

    for (i, &diff) in differences.iter().enumerate() {
        if diff > threshold {
            // Detected a scene change
            if i > scene_start {
                boundaries.push(ShotBoundary {
                    start_frame: scene_start,
                    end_frame: i,
                    confidence: diff.min(1.0),
                    transition_type: classify_transition(diff),
                });
            }
            scene_start = i + 1;
        }
    }

    // Add final scene
    if scene_start < frames.len() {
        boundaries.push(ShotBoundary {
            start_frame: scene_start,
            end_frame: frames.len() - 1,
            confidence: 1.0,
            transition_type: TransitionType::Cut,
        });
    }

    Ok(boundaries)
}

/// Computes differences between consecutive frames.
fn compute_frame_differences(frames: &[(u32, u32, Vec<u8>)]) -> CvResult<Vec<f64>> {
    let mut differences = Vec::with_capacity(frames.len() - 1);

    for i in 0..frames.len() - 1 {
        let (w1, h1, data1) = &frames[i];
        let (w2, h2, data2) = &frames[i + 1];

        if w1 != w2 || h1 != h2 {
            return Err(CvError::invalid_parameter(
                "frames",
                "inconsistent dimensions",
            ));
        }

        let diff = compute_frame_difference(data1, data2);
        differences.push(diff);
    }

    Ok(differences)
}

/// Computes difference between two frames.
fn compute_frame_difference(frame1: &[u8], frame2: &[u8]) -> f64 {
    if frame1.len() != frame2.len() {
        return 1.0; // Maximum difference
    }

    let mut sum = 0.0;
    let n = frame1.len() / 3; // Number of pixels

    for i in 0..n {
        let r1 = f64::from(frame1[i * 3]);
        let g1 = f64::from(frame1[i * 3 + 1]);
        let b1 = f64::from(frame1[i * 3 + 2]);

        let r2 = f64::from(frame2[i * 3]);
        let g2 = f64::from(frame2[i * 3 + 1]);
        let b2 = f64::from(frame2[i * 3 + 2]);

        let dr = (r1 - r2).abs();
        let dg = (g1 - g2).abs();
        let db = (b1 - b2).abs();

        sum += dr + dg + db;
    }

    // Normalize to [0, 1]
    sum / (n as f64 * 3.0 * 255.0)
}

/// Classifies transition type based on difference magnitude.
fn classify_transition(diff: f64) -> TransitionType {
    if diff > 0.7 {
        TransitionType::Cut
    } else if diff > 0.4 {
        TransitionType::Dissolve
    } else {
        TransitionType::Fade
    }
}

/// Computes temporal signature for video.
///
/// Creates a time-based feature vector capturing temporal patterns.
///
/// # Arguments
///
/// * `frames` - Slice of video frames
/// * `interval` - Sampling interval in frames
///
/// # Errors
///
/// Returns an error if computation fails.
pub fn compute_temporal_signature(
    frames: &[(u32, u32, Vec<u8>)],
    interval: usize,
) -> CvResult<Vec<f32>> {
    if frames.is_empty() {
        return Err(CvError::invalid_parameter("frames", "empty"));
    }

    if interval == 0 {
        return Err(CvError::invalid_parameter("interval", "0"));
    }

    let mut signature = Vec::new();

    // Sample frames at regular intervals
    let mut idx = 0;
    while idx < frames.len() {
        let features = extract_temporal_features(&frames[idx])?;
        signature.extend_from_slice(&features);

        idx += interval;
    }

    Ok(signature)
}

/// Extracts temporal features from a single frame.
fn extract_temporal_features(frame: &(u32, u32, Vec<u8>)) -> CvResult<Vec<f32>> {
    let (width, height, data) = frame;

    if *width == 0 || *height == 0 {
        return Err(CvError::invalid_dimensions(*width, *height));
    }

    let mut features = Vec::with_capacity(8);

    // Average brightness
    let brightness = compute_average_brightness(data);
    features.push(brightness);

    // Color moments (RGB)
    let (r_mean, g_mean, b_mean) = compute_color_moments(data);
    features.push(r_mean);
    features.push(g_mean);
    features.push(b_mean);

    // Edge density
    let edge_density = compute_edge_density(data, *width, *height);
    features.push(edge_density);

    // Spatial complexity
    let complexity = compute_spatial_complexity(data, *width, *height);
    features.push(complexity);

    // Color variance
    let variance = compute_color_variance(data);
    features.push(variance);

    // Contrast
    let contrast = compute_contrast(data);
    features.push(contrast);

    Ok(features)
}

/// Computes average brightness of frame.
fn compute_average_brightness(data: &[u8]) -> f32 {
    let sum: u32 = data.iter().map(|&x| u32::from(x)).sum();
    sum as f32 / data.len() as f32 / 255.0
}

/// Computes color moments (mean values).
fn compute_color_moments(data: &[u8]) -> (f32, f32, f32) {
    let n = data.len() / 3;
    let mut r_sum = 0u32;
    let mut g_sum = 0u32;
    let mut b_sum = 0u32;

    for i in 0..n {
        r_sum += u32::from(data[i * 3]);
        g_sum += u32::from(data[i * 3 + 1]);
        b_sum += u32::from(data[i * 3 + 2]);
    }

    let r_mean = r_sum as f32 / n as f32 / 255.0;
    let g_mean = g_sum as f32 / n as f32 / 255.0;
    let b_mean = b_sum as f32 / n as f32 / 255.0;

    (r_mean, g_mean, b_mean)
}

/// Computes edge density using simple gradient.
fn compute_edge_density(data: &[u8], width: u32, height: u32) -> f32 {
    let mut edge_count = 0u32;
    let threshold = 30u8;

    for y in 0..height - 1 {
        for x in 0..width - 1 {
            let idx = ((y * width + x) * 3) as usize;
            let right_idx = ((y * width + x + 1) * 3) as usize;
            let down_idx = (((y + 1) * width + x) * 3) as usize;

            // Horizontal gradient
            let h_grad = data[idx].abs_diff(data[right_idx]);
            // Vertical gradient
            let v_grad = data[idx].abs_diff(data[down_idx]);

            if h_grad > threshold || v_grad > threshold {
                edge_count += 1;
            }
        }
    }

    edge_count as f32 / ((width - 1) * (height - 1)) as f32
}

/// Computes spatial complexity (variance of gradients).
fn compute_spatial_complexity(data: &[u8], width: u32, height: u32) -> f32 {
    let mut gradients = Vec::new();

    for y in 0..height - 1 {
        for x in 0..width - 1 {
            let idx = ((y * width + x) * 3) as usize;
            let right_idx = ((y * width + x + 1) * 3) as usize;

            let grad = data[idx].abs_diff(data[right_idx]);
            gradients.push(f32::from(grad));
        }
    }

    if gradients.is_empty() {
        return 0.0;
    }

    let mean: f32 = gradients.iter().sum::<f32>() / gradients.len() as f32;
    let variance: f32 =
        gradients.iter().map(|&x| (x - mean).powi(2)).sum::<f32>() / gradients.len() as f32;

    variance.sqrt() / 255.0
}

/// Computes color variance.
fn compute_color_variance(data: &[u8]) -> f32 {
    let n = data.len();
    if n == 0 {
        return 0.0;
    }

    let mean: f32 = data.iter().map(|&x| f32::from(x)).sum::<f32>() / n as f32;
    let variance: f32 = data
        .iter()
        .map(|&x| (f32::from(x) - mean).powi(2))
        .sum::<f32>()
        / n as f32;

    variance.sqrt() / 255.0
}

/// Computes contrast (difference between max and min).
fn compute_contrast(data: &[u8]) -> f32 {
    if data.is_empty() {
        return 0.0;
    }

    // data is non-empty (checked above), so min() and max() always return Some.
    let min_val = data.iter().copied().min().unwrap_or(0);
    let max_val = data.iter().copied().max().unwrap_or(0);

    f32::from(max_val - min_val) / 255.0
}

/// Samples frames using specified strategy.
///
/// # Errors
///
/// Returns an error if sampling fails.
pub fn sample_frames(
    frames: &[(u32, u32, Vec<u8>)],
    strategy: SamplingStrategy,
    count: usize,
    scene_threshold: f64,
) -> CvResult<Vec<(u32, u32, Vec<u8>)>> {
    if frames.is_empty() {
        return Err(CvError::invalid_parameter("frames", "empty"));
    }

    if count == 0 {
        return Err(CvError::invalid_parameter("count", "0"));
    }

    match strategy {
        SamplingStrategy::Uniform => sample_uniform(frames, count),
        SamplingStrategy::Adaptive => sample_adaptive(frames, count),
        SamplingStrategy::SceneBased => sample_scene_based(frames, count, scene_threshold),
        SamplingStrategy::KeyframeOnly => {
            let min_interval = frames.len() / count.max(1);
            extract_keyframes(frames, min_interval, count, scene_threshold)
        }
    }
}

/// Samples frames uniformly.
fn sample_uniform(
    frames: &[(u32, u32, Vec<u8>)],
    count: usize,
) -> CvResult<Vec<(u32, u32, Vec<u8>)>> {
    let interval = frames.len() / count.max(1);
    let mut samples = Vec::new();

    let mut idx = 0;
    while idx < frames.len() && samples.len() < count {
        samples.push(frames[idx].clone());
        idx += interval;
    }

    Ok(samples)
}

/// Samples frames adaptively based on content changes.
fn sample_adaptive(
    frames: &[(u32, u32, Vec<u8>)],
    count: usize,
) -> CvResult<Vec<(u32, u32, Vec<u8>)>> {
    if frames.len() <= count {
        return Ok(frames.to_vec());
    }

    // Compute frame differences
    let differences = compute_frame_differences(frames)?;

    // Find frames with highest differences (most interesting)
    let mut indexed_diffs: Vec<(usize, f64)> = differences
        .iter()
        .enumerate()
        .map(|(i, &d)| (i, d))
        .collect();

    indexed_diffs.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

    // Select top 'count' frames
    let mut selected_indices: Vec<usize> =
        indexed_diffs.iter().take(count).map(|(i, _)| *i).collect();

    selected_indices.sort_unstable();

    let samples = selected_indices
        .iter()
        .map(|&i| frames[i].clone())
        .collect();

    Ok(samples)
}

/// Samples frames based on scene boundaries.
fn sample_scene_based(
    frames: &[(u32, u32, Vec<u8>)],
    count: usize,
    scene_threshold: f64,
) -> CvResult<Vec<(u32, u32, Vec<u8>)>> {
    let boundaries = detect_shot_boundaries(frames, scene_threshold)?;

    if boundaries.is_empty() {
        return sample_uniform(frames, count);
    }

    let mut samples = Vec::new();
    let scenes_per_sample = (boundaries.len() as f64 / count as f64).ceil() as usize;

    for (i, boundary) in boundaries.iter().enumerate() {
        if i % scenes_per_sample == 0 && samples.len() < count {
            let mid = (boundary.start_frame + boundary.end_frame) / 2;
            if mid < frames.len() {
                samples.push(frames[mid].clone());
            }
        }
    }

    Ok(samples)
}

/// Computes temporal correlation between two videos.
///
/// Returns a correlation score in [0.0, 1.0].
#[must_use]
pub fn compute_temporal_correlation(sig1: &[f32], sig2: &[f32]) -> f64 {
    if sig1.is_empty() || sig2.is_empty() {
        return 0.0;
    }

    // Use shorter signature for comparison
    let len = sig1.len().min(sig2.len());

    let mut sum = 0.0;
    let mut count = 0;

    for i in 0..len {
        let diff = (sig1[i] - sig2[i]).abs();
        sum += f64::from(1.0 - diff.min(1.0));
        count += 1;
    }

    if count == 0 {
        0.0
    } else {
        sum / count as f64
    }
}

/// Hashes a video segment.
///
/// # Errors
///
/// Returns an error if hashing fails.
pub fn hash_segment(frames: &[(u32, u32, Vec<u8>)], start: usize, end: usize) -> CvResult<Vec<u8>> {
    if start >= end || end > frames.len() {
        return Err(CvError::invalid_parameter(
            "range",
            format!("[{start}, {end})"),
        ));
    }

    let segment = &frames[start..end];
    let signature = compute_temporal_signature(segment, 1)?;

    // Convert f32 signature to bytes
    let mut bytes = Vec::new();
    for &val in &signature {
        bytes.push((val * 255.0) as u8);
    }

    Ok(bytes)
}

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

    fn create_test_frame(width: u32, height: u32, brightness: u8) -> (u32, u32, Vec<u8>) {
        let data = vec![brightness; (width * height * 3) as usize];
        (width, height, data)
    }

    fn create_test_frames(count: usize) -> Vec<(u32, u32, Vec<u8>)> {
        (0..count)
            .map(|i| create_test_frame(64, 64, (i * 10) as u8))
            .collect()
    }

    #[test]
    fn test_extract_keyframes() {
        let frames = create_test_frames(100);
        let keyframes =
            extract_keyframes(&frames, 10, 5, 0.3).expect("extract_keyframes should succeed");
        assert!(!keyframes.is_empty());
        assert!(keyframes.len() <= 5);
    }

    #[test]
    fn test_detect_shot_boundaries() {
        let mut frames = create_test_frames(50);
        // Create a scene change at frame 25
        for i in 25..50 {
            frames[i] = create_test_frame(64, 64, 200);
        }

        let boundaries =
            detect_shot_boundaries(&frames, 0.3).expect("detect_shot_boundaries should succeed");
        assert!(!boundaries.is_empty());
    }

    #[test]
    fn test_compute_temporal_signature() {
        let frames = create_test_frames(10);
        let signature = compute_temporal_signature(&frames, 2)
            .expect("compute_temporal_signature should succeed");
        assert!(!signature.is_empty());
    }

    #[test]
    fn test_temporal_features() {
        let frame = create_test_frame(64, 64, 128);
        let features =
            extract_temporal_features(&frame).expect("extract_temporal_features should succeed");
        assert_eq!(features.len(), 8);
    }

    #[test]
    fn test_frame_difference() {
        let frame1 = vec![100u8; 300];
        let frame2 = vec![100u8; 300];
        let diff = compute_frame_difference(&frame1, &frame2);
        assert_eq!(diff, 0.0);

        let frame3 = vec![200u8; 300];
        let diff2 = compute_frame_difference(&frame1, &frame3);
        assert!(diff2 > 0.0);
    }

    #[test]
    fn test_sample_uniform() {
        let frames = create_test_frames(100);
        let samples = sample_uniform(&frames, 10).expect("sample_uniform should succeed");
        assert_eq!(samples.len(), 10);
    }

    #[test]
    fn test_sample_adaptive() {
        let frames = create_test_frames(100);
        let samples = sample_adaptive(&frames, 10).expect("sample_adaptive should succeed");
        assert_eq!(samples.len(), 10);
    }

    #[test]
    fn test_sample_scene_based() {
        let frames = create_test_frames(100);
        let samples =
            sample_scene_based(&frames, 10, 0.3).expect("sample_scene_based should succeed");
        assert!(!samples.is_empty());
    }

    #[test]
    fn test_temporal_correlation() {
        let sig1 = vec![0.1, 0.2, 0.3, 0.4];
        let sig2 = vec![0.1, 0.2, 0.3, 0.4];
        let corr = compute_temporal_correlation(&sig1, &sig2);
        assert!((corr - 1.0).abs() < 0.01);

        let sig3 = vec![0.9, 0.8, 0.7, 0.6];
        let corr2 = compute_temporal_correlation(&sig1, &sig3);
        assert!(corr2 < 1.0);
    }

    #[test]
    fn test_hash_segment() {
        let frames = create_test_frames(10);
        let hash = hash_segment(&frames, 0, 5).expect("hash_segment should succeed");
        assert!(!hash.is_empty());
    }

    #[test]
    fn test_brightness() {
        let data = vec![128u8; 300];
        let brightness = compute_average_brightness(&data);
        assert!((brightness - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_color_moments() {
        let data = vec![100u8, 150u8, 200u8];
        let (r, g, b) = compute_color_moments(&data);
        assert!(r > 0.0 && r < 1.0);
        assert!(g > 0.0 && g < 1.0);
        assert!(b > 0.0 && b < 1.0);
    }

    #[test]
    fn test_transition_classification() {
        assert_eq!(classify_transition(0.8), TransitionType::Cut);
        assert_eq!(classify_transition(0.5), TransitionType::Dissolve);
        assert_eq!(classify_transition(0.2), TransitionType::Fade);
    }

    #[test]
    fn test_empty_frames() {
        let frames: Vec<(u32, u32, Vec<u8>)> = Vec::new();
        assert!(extract_keyframes(&frames, 10, 5, 0.3).is_err());
    }

    #[test]
    fn test_invalid_interval() {
        let frames = create_test_frames(10);
        assert!(extract_keyframes(&frames, 0, 5, 0.3).is_err());
    }
}