oximedia-conform 0.2.1

Professional media conforming system for OxiMedia - EDL/XML/AAF timeline reconstruction
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
735
736
737
738
739
740
741
742
743
744
745
//! Timeline reconstruction from matched clips.

use crate::config::ConformConfig;
use crate::error::{ConformError, ConformResult};
use crate::timeline::{Timeline, TimelineClip, Track, TrackKind, Transition};
use crate::types::{ClipMatch, FrameRate, Timecode};
use tracing::{debug, info, warn};

/// Timeline reconstructor.
pub struct TimelineReconstructor {
    /// Configuration.
    config: ConformConfig,
    /// Frame rate.
    fps: FrameRate,
}

impl TimelineReconstructor {
    /// Create a new timeline reconstructor.
    #[must_use]
    pub fn new(fps: FrameRate, config: ConformConfig) -> Self {
        Self { config, fps }
    }

    /// Reconstruct timeline from matched clips.
    ///
    /// # Errors
    ///
    /// Returns an error if timeline reconstruction fails.
    pub fn reconstruct(&self, name: String, matches: &[ClipMatch]) -> ConformResult<Timeline> {
        info!("Reconstructing timeline: {}", name);

        if matches.is_empty() {
            return Err(ConformError::Other("No clips to reconstruct".to_string()));
        }

        let mut timeline = Timeline::new(name, self.fps);

        // Group clips by track
        let (video_clips, audio_clips) = self.group_clips_by_track(matches);

        // Build video tracks
        if !video_clips.is_empty() {
            let video_tracks = self.build_video_tracks(&video_clips)?;
            for track in video_tracks {
                timeline.add_video_track(track);
            }
        }

        // Build audio tracks
        if !audio_clips.is_empty() {
            let audio_tracks = self.build_audio_tracks(&audio_clips)?;
            for track in audio_tracks {
                timeline.add_audio_track(track);
            }
        }

        info!(
            "Timeline reconstructed: {} video tracks, {} audio tracks",
            timeline.video_tracks.len(),
            timeline.audio_tracks.len()
        );

        Ok(timeline)
    }

    /// Group clips by track type.
    fn group_clips_by_track(
        &self,
        matches: &[ClipMatch],
    ) -> (Vec<TimelineClip>, Vec<TimelineClip>) {
        let mut video_clips = Vec::new();
        let mut audio_clips = Vec::new();

        for clip_match in matches {
            let timeline_clip = TimelineClip::from_match(clip_match);

            match clip_match.clip.track {
                crate::types::TrackType::Video => video_clips.push(timeline_clip),
                crate::types::TrackType::Audio => audio_clips.push(timeline_clip),
                crate::types::TrackType::AudioVideo => {
                    video_clips.push(timeline_clip.clone());
                    audio_clips.push(timeline_clip);
                }
            }
        }

        (video_clips, audio_clips)
    }

    /// Build video tracks from clips.
    fn build_video_tracks(&self, clips: &[TimelineClip]) -> ConformResult<Vec<Track>> {
        let mut tracks = Vec::new();

        // Precompute sort keys once (1× to_frames per clip instead of O(log n) per comparison).
        let keys: Vec<u64> = clips
            .iter()
            .map(|c| c.timeline_in.to_frames(c.fps))
            .collect();
        // Sort indices by precomputed key (stable, preserving relative order for equal keys).
        let mut order: Vec<usize> = (0..clips.len()).collect();
        order.sort_by_key(|&i| keys[i]);

        // For now, create a single video track
        let mut track = Track::new("V1".to_string(), TrackKind::Video);
        track.name = Some("Video 1".to_string());

        for i in order {
            track.add_clip(clips[i].clone());
        }

        // Add transitions if needed
        self.add_transitions(&mut track)?;

        tracks.push(track);
        Ok(tracks)
    }

    /// Build audio tracks from clips.
    fn build_audio_tracks(&self, clips: &[TimelineClip]) -> ConformResult<Vec<Track>> {
        let mut tracks = Vec::new();

        // Precompute sort keys once (1× to_frames per clip instead of O(log n) per comparison).
        let keys: Vec<u64> = clips
            .iter()
            .map(|c| c.timeline_in.to_frames(c.fps))
            .collect();
        // Sort indices by precomputed key (stable, preserving relative order for equal keys).
        let mut order: Vec<usize> = (0..clips.len()).collect();
        order.sort_by_key(|&i| keys[i]);

        // For now, create a single audio track
        let mut track = Track::new("A1".to_string(), TrackKind::Audio);
        track.name = Some("Audio 1".to_string());

        for i in order {
            track.add_clip(clips[i].clone());
        }

        tracks.push(track);
        Ok(tracks)
    }

    /// Add transitions between clips.
    fn add_transitions(&self, track: &mut Track) -> ConformResult<()> {
        if track.clips.len() < 2 {
            return Ok(());
        }

        for i in 0..track.clips.len() - 1 {
            let current = &track.clips[i];
            let next = &track.clips[i + 1];

            // Check for gap or overlap
            let current_out = current.timeline_out.to_frames(current.fps);
            let next_in = next.timeline_in.to_frames(next.fps);

            if current_out == next_in {
                // Perfect cut
                let transition = Transition::cut(current.timeline_out);
                track.add_transition(transition);
            } else if current_out > next_in {
                // Overlap - create dissolve
                let overlap_frames = (current_out - next_in) as u32;
                let transition = Transition::dissolve(next.timeline_in, overlap_frames);
                track.add_transition(transition);
                debug!("Added dissolve transition: {} frames", overlap_frames);
            } else {
                // Gap - warn
                let gap_frames = next_in - current_out;
                warn!("Gap detected: {} frames between clips", gap_frames);
                let transition = Transition::cut(current.timeline_out);
                track.add_transition(transition);
            }
        }

        Ok(())
    }

    /// Validate timeline consistency.
    pub fn validate_timeline(&self, timeline: &Timeline) -> ConformResult<()> {
        for (i, track) in timeline.video_tracks.iter().enumerate() {
            self.validate_track(track, i)?;
        }

        for (i, track) in timeline.audio_tracks.iter().enumerate() {
            self.validate_track(track, i)?;
        }

        Ok(())
    }

    /// Validate a single track.
    fn validate_track(&self, track: &Track, index: usize) -> ConformResult<()> {
        if track.clips.is_empty() {
            warn!("Track {} is empty", index);
            return Ok(());
        }

        // Check for overlapping clips
        for i in 0..track.clips.len() - 1 {
            let current = &track.clips[i];
            let next = &track.clips[i + 1];

            let current_out = current.timeline_out.to_frames(current.fps);
            let next_in = next.timeline_in.to_frames(next.fps);

            if current_out > next_in && self.config.strict_validation {
                return Err(ConformError::Validation(format!(
                    "Overlapping clips in track {}: clip {} ends at {}, clip {} starts at {}",
                    index,
                    i,
                    current.timeline_out,
                    i + 1,
                    next.timeline_in
                )));
            }
        }

        Ok(())
    }

    /// Split timeline into segments.
    pub fn split_into_segments(
        &self,
        timeline: &Timeline,
        segment_duration: f64,
    ) -> ConformResult<Vec<Timeline>> {
        let total_duration = timeline.duration_seconds();
        let num_segments = (total_duration / segment_duration).ceil() as usize;

        let mut segments = Vec::new();

        for i in 0..num_segments {
            let start_time = i as f64 * segment_duration;
            let end_time = ((i + 1) as f64 * segment_duration).min(total_duration);

            let segment = self.extract_segment(
                timeline,
                start_time,
                end_time,
                format!("{}_seg{}", timeline.name, i + 1),
            )?;

            segments.push(segment);
        }

        Ok(segments)
    }

    /// Extract a segment from the timeline.
    fn extract_segment(
        &self,
        timeline: &Timeline,
        start_time: f64,
        end_time: f64,
        name: String,
    ) -> ConformResult<Timeline> {
        let mut segment = Timeline::new(name, timeline.fps);

        let start_tc = crate::utils::seconds_to_timecode(start_time, timeline.fps);
        let end_tc = crate::utils::seconds_to_timecode(end_time, timeline.fps);

        // Extract video tracks
        for track in &timeline.video_tracks {
            let segment_track = self.extract_track_segment(track, start_tc, end_tc)?;
            if !segment_track.clips.is_empty() {
                segment.add_video_track(segment_track);
            }
        }

        // Extract audio tracks
        for track in &timeline.audio_tracks {
            let segment_track = self.extract_track_segment(track, start_tc, end_tc)?;
            if !segment_track.clips.is_empty() {
                segment.add_audio_track(segment_track);
            }
        }

        Ok(segment)
    }

    /// Extract a segment from a track.
    fn extract_track_segment(
        &self,
        track: &Track,
        start_tc: Timecode,
        end_tc: Timecode,
    ) -> ConformResult<Track> {
        let mut segment_track = Track::new(track.id.clone(), track.kind);
        segment_track.name = track.name.clone();

        let start_frames = start_tc.to_frames(self.fps);
        let end_frames = end_tc.to_frames(self.fps);

        for clip in &track.clips {
            let clip_in = clip.timeline_in.to_frames(clip.fps);
            let clip_out = clip.timeline_out.to_frames(clip.fps);

            // Check if clip overlaps with segment
            if clip_out > start_frames && clip_in < end_frames {
                // Clip overlaps - add it (potentially trimmed)
                let mut segment_clip = clip.clone();

                // Trim if needed
                if clip_in < start_frames {
                    let trim_frames = start_frames - clip_in;
                    segment_clip.source_in = Timecode::from_frames(
                        segment_clip.source_in.to_frames(clip.fps) + trim_frames,
                        clip.fps,
                    );
                    segment_clip.timeline_in = start_tc;
                }

                if clip_out > end_frames {
                    let trim_frames = clip_out - end_frames;
                    segment_clip.source_out = Timecode::from_frames(
                        segment_clip.source_out.to_frames(clip.fps) - trim_frames,
                        clip.fps,
                    );
                    segment_clip.timeline_out = end_tc;
                }

                segment_track.add_clip(segment_clip);
            }
        }

        Ok(segment_track)
    }

    /// Merge multiple timelines into one.
    pub fn merge_timelines(&self, timelines: &[Timeline], name: String) -> ConformResult<Timeline> {
        if timelines.is_empty() {
            return Err(ConformError::Other("No timelines to merge".to_string()));
        }

        let fps = timelines[0].fps;
        let mut merged = Timeline::new(name, fps);

        // Merge video tracks
        let max_video_tracks = timelines
            .iter()
            .map(|t| t.video_tracks.len())
            .max()
            .unwrap_or(0);
        for track_idx in 0..max_video_tracks {
            let mut merged_track = Track::new(format!("V{}", track_idx + 1), TrackKind::Video);
            merged_track.name = Some(format!("Video {}", track_idx + 1));

            let mut current_offset = Timecode::new(0, 0, 0, 0);

            for timeline in timelines {
                if let Some(track) = timeline.video_tracks.get(track_idx) {
                    for clip in &track.clips {
                        let mut offset_clip = clip.clone();
                        let offset_frames = current_offset.to_frames(fps);

                        offset_clip.timeline_in = Timecode::from_frames(
                            clip.timeline_in.to_frames(fps) + offset_frames,
                            fps,
                        );
                        offset_clip.timeline_out = Timecode::from_frames(
                            clip.timeline_out.to_frames(fps) + offset_frames,
                            fps,
                        );

                        merged_track.add_clip(offset_clip);
                    }
                }

                // Update offset for next timeline
                let timeline_duration_frames = timeline.duration_frames();
                current_offset = Timecode::from_frames(
                    current_offset.to_frames(fps) + timeline_duration_frames,
                    fps,
                );
            }

            if !merged_track.clips.is_empty() {
                merged.add_video_track(merged_track);
            }
        }

        // Merge audio tracks (similar logic)
        let max_audio_tracks = timelines
            .iter()
            .map(|t| t.audio_tracks.len())
            .max()
            .unwrap_or(0);
        for track_idx in 0..max_audio_tracks {
            let mut merged_track = Track::new(format!("A{}", track_idx + 1), TrackKind::Audio);
            merged_track.name = Some(format!("Audio {}", track_idx + 1));

            let mut current_offset = Timecode::new(0, 0, 0, 0);

            for timeline in timelines {
                if let Some(track) = timeline.audio_tracks.get(track_idx) {
                    for clip in &track.clips {
                        let mut offset_clip = clip.clone();
                        let offset_frames = current_offset.to_frames(fps);

                        offset_clip.timeline_in = Timecode::from_frames(
                            clip.timeline_in.to_frames(fps) + offset_frames,
                            fps,
                        );
                        offset_clip.timeline_out = Timecode::from_frames(
                            clip.timeline_out.to_frames(fps) + offset_frames,
                            fps,
                        );

                        merged_track.add_clip(offset_clip);
                    }
                }

                let timeline_duration_frames = timeline.duration_frames();
                current_offset = Timecode::from_frames(
                    current_offset.to_frames(fps) + timeline_duration_frames,
                    fps,
                );
            }

            if !merged_track.clips.is_empty() {
                merged.add_audio_track(merged_track);
            }
        }

        Ok(merged)
    }

    /// Optimize timeline by removing gaps and overlaps.
    pub fn optimize_timeline(&self, timeline: &mut Timeline) -> ConformResult<()> {
        for track in &mut timeline.video_tracks {
            self.optimize_track(track)?;
        }

        for track in &mut timeline.audio_tracks {
            self.optimize_track(track)?;
        }

        Ok(())
    }

    /// Optimize a single track.
    fn optimize_track(&self, track: &mut Track) -> ConformResult<()> {
        if track.clips.is_empty() {
            return Ok(());
        }

        track.sort_clips();

        // Remove gaps by shifting clips
        let mut current_time = Timecode::new(0, 0, 0, 0);

        for clip in &mut track.clips {
            let clip_duration_frames = clip.duration_frames();

            clip.timeline_in = current_time;
            clip.timeline_out = Timecode::from_frames(
                current_time.to_frames(clip.fps) + clip_duration_frames,
                clip.fps,
            );

            current_time = clip.timeline_out;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{ClipReference, MatchMethod, MediaFile, TrackType};
    use std::collections::HashMap;
    use std::path::PathBuf;

    fn create_test_match(id: &str, record_in: Timecode, record_out: Timecode) -> ClipMatch {
        let clip = ClipReference {
            id: id.to_string(),
            source_file: Some(format!("{id}.mov")),
            source_in: Timecode::new(1, 0, 0, 0),
            source_out: Timecode::new(1, 0, 10, 0),
            record_in,
            record_out,
            track: TrackType::Video,
            fps: FrameRate::Fps25,
            metadata: HashMap::new(),
        };

        ClipMatch {
            clip,
            media: MediaFile::new(PathBuf::from(format!("/test/{id}.mov"))),
            score: 1.0,
            method: MatchMethod::ExactFilename,
            details: String::new(),
        }
    }

    #[test]
    fn test_reconstructor_creation() {
        let reconstructor = TimelineReconstructor::new(FrameRate::Fps25, ConformConfig::default());
        assert_eq!(reconstructor.fps.as_f64(), 25.0);
    }

    #[test]
    fn test_reconstruct_simple_timeline() {
        let reconstructor = TimelineReconstructor::new(FrameRate::Fps25, ConformConfig::default());

        let matches = vec![
            create_test_match(
                "clip1",
                Timecode::new(1, 0, 0, 0),
                Timecode::new(1, 0, 10, 0),
            ),
            create_test_match(
                "clip2",
                Timecode::new(1, 0, 10, 0),
                Timecode::new(1, 0, 20, 0),
            ),
        ];

        let timeline = reconstructor
            .reconstruct("Test Timeline".to_string(), &matches)
            .expect("test expectation failed");

        assert_eq!(timeline.name, "Test Timeline");
        assert_eq!(timeline.video_tracks.len(), 1);
        assert_eq!(timeline.video_tracks[0].clips.len(), 2);
    }

    #[test]
    fn test_validate_timeline() {
        let reconstructor = TimelineReconstructor::new(FrameRate::Fps25, ConformConfig::default());

        let matches = vec![create_test_match(
            "clip1",
            Timecode::new(1, 0, 0, 0),
            Timecode::new(1, 0, 10, 0),
        )];

        let timeline = reconstructor
            .reconstruct("Test".to_string(), &matches)
            .expect("test expectation failed");

        assert!(reconstructor.validate_timeline(&timeline).is_ok());
    }

    /// Build a `TimelineClip` directly from raw fields without going through `ClipMatch`.
    fn make_clip(id: &str, h: u8, m: u8, s: u8, f: u8) -> TimelineClip {
        use std::path::PathBuf;
        TimelineClip {
            id: id.to_string(),
            source_path: PathBuf::from(format!("/test/{id}.mov")),
            source_in: Timecode::new(0, 0, 0, 0),
            source_out: Timecode::new(0, 0, 1, 0),
            timeline_in: Timecode::new(h, m, s, f),
            timeline_out: Timecode::new(h, m, s + 1, f),
            fps: FrameRate::Fps25,
            name: Some(id.to_string()),
            match_score: 1.0,
        }
    }

    #[test]
    fn test_reconstruction_sorts_1000_clips_correctly() {
        use crate::config::ConformConfig;

        // Build 1000 clips with pseudo-random timeline_in values by cycling through
        // different second/frame values in a non-monotone order.
        let fps = FrameRate::Fps25;
        let reconstructor = TimelineReconstructor::new(fps, ConformConfig::default());

        let n: u32 = 1000;
        // Create clips whose frame index (when sorted) should be 0..n.
        // We map index i to a shuffled position via a simple bit-reversal permutation so
        // the input order is far from sorted.
        let clips: Vec<TimelineClip> = (0..n)
            .map(|i| {
                // bit-reversal of i among 10-bit integers for pseudo-random ordering
                let shuffled = {
                    let mut v: u32 = 0;
                    let mut x = i;
                    for _ in 0..10 {
                        v = (v << 1) | (x & 1);
                        x >>= 1;
                    }
                    v
                };
                // Convert frame index `shuffled` to HH:MM:SS:FF at 25 fps
                let total_frames = shuffled;
                let frame_f = (total_frames % 25) as u8;
                let total_sec = total_frames / 25;
                let sec_s = (total_sec % 60) as u8;
                let total_min = total_sec / 60;
                let min_m = (total_min % 60) as u8;
                let hour_h = (total_min / 60) as u8;
                make_clip(&format!("clip{i}"), hour_h, min_m, sec_s, frame_f)
            })
            .collect();

        let video_tracks = reconstructor
            .build_video_tracks(&clips)
            .expect("build_video_tracks should succeed");

        assert_eq!(video_tracks.len(), 1);
        let track = &video_tracks[0];
        assert_eq!(track.clips.len(), n as usize);

        // Verify ascending order of timeline_in
        for window in track.clips.windows(2) {
            let a = window[0].timeline_in.to_frames(fps);
            let b = window[1].timeline_in.to_frames(fps);
            assert!(
                a <= b,
                "clips out of order: frame {a} followed by frame {b}"
            );
        }
    }

    #[test]
    fn test_reconstruction_sorted_output_matches_reference() {
        use crate::config::ConformConfig;

        let fps = FrameRate::Fps25;
        let reconstructor = TimelineReconstructor::new(fps, ConformConfig::default());

        // 10 clips in a non-sorted order (seconds: 9,0,5,3,7,1,8,4,6,2)
        let order = [9u8, 0, 5, 3, 7, 1, 8, 4, 6, 2];
        let clips: Vec<TimelineClip> = order
            .iter()
            .map(|&s| make_clip(&format!("clip{s}"), 0, 0, s, 0))
            .collect();

        let video_tracks = reconstructor
            .build_video_tracks(&clips)
            .expect("build_video_tracks should succeed");

        // Build reference by sorting with sort_by_key (the old approach)
        let mut reference = clips.clone();
        reference.sort_by_key(|c| c.timeline_in.to_frames(c.fps));

        let result_clips = &video_tracks[0].clips;
        assert_eq!(result_clips.len(), reference.len());

        for (got, expected) in result_clips.iter().zip(reference.iter()) {
            assert_eq!(
                got.timeline_in.to_frames(fps),
                expected.timeline_in.to_frames(fps),
                "timeline_in mismatch: got {}, expected {}",
                got.timeline_in,
                expected.timeline_in,
            );
            assert_eq!(
                got.id, expected.id,
                "clip id mismatch: got {}, expected {}",
                got.id, expected.id,
            );
        }
    }

    #[test]
    fn test_reconstruction_stable_sort_duplicate_timestamps() {
        use crate::config::ConformConfig;

        let fps = FrameRate::Fps25;
        let reconstructor = TimelineReconstructor::new(fps, ConformConfig::default());

        // Build clips where clips 0..4 share timeline_in = 0s and clips 5..9 share timeline_in = 1s.
        // The stable sort must preserve the original relative order within each group.
        let clips: Vec<TimelineClip> = (0..10usize)
            .map(|i| {
                let s = if i < 5 { 0u8 } else { 1u8 };
                make_clip(&format!("clip{i}"), 0, 0, s, 0)
            })
            .collect();

        let video_tracks = reconstructor
            .build_video_tracks(&clips)
            .expect("build_video_tracks should succeed");

        let result_clips = &video_tracks[0].clips;
        assert_eq!(result_clips.len(), 10);

        // First 5 should be clip0..clip4 in that order (same key → stable order)
        for (pos, expected_id) in ["clip0", "clip1", "clip2", "clip3", "clip4"]
            .iter()
            .enumerate()
        {
            assert_eq!(
                result_clips[pos].id, *expected_id,
                "stable sort violated at position {pos}: got {}, expected {expected_id}",
                result_clips[pos].id,
            );
        }
        // Next 5 should be clip5..clip9 in that order
        for (pos, expected_id) in ["clip5", "clip6", "clip7", "clip8", "clip9"]
            .iter()
            .enumerate()
        {
            assert_eq!(
                result_clips[5 + pos].id,
                *expected_id,
                "stable sort violated at position {}: got {}, expected {expected_id}",
                5 + pos,
                result_clips[5 + pos].id,
            );
        }
    }

    #[test]
    fn test_reconstruction_1000_clips_fast() {
        use crate::config::ConformConfig;
        use std::time::Instant;

        let fps = FrameRate::Fps25;
        let reconstructor = TimelineReconstructor::new(fps, ConformConfig::default());

        let clips: Vec<TimelineClip> = (0u32..1000)
            .rev() // worst-case reverse order
            .map(|i| {
                let total_sec = i;
                let sec_s = (total_sec % 60) as u8;
                let total_min = total_sec / 60;
                let min_m = (total_min % 60) as u8;
                let hour_h = (total_min / 60) as u8;
                make_clip(&format!("clip{i}"), hour_h, min_m, sec_s, 0)
            })
            .collect();

        let start = Instant::now();
        let video_tracks = reconstructor
            .build_video_tracks(&clips)
            .expect("build_video_tracks should succeed");
        let elapsed = start.elapsed();

        // Sanity: correct output
        assert_eq!(video_tracks[0].clips.len(), 1000);

        // Performance bound: well under 100 ms even on slow CI
        assert!(
            elapsed.as_millis() < 100,
            "build_video_tracks for 1000 clips took {}ms, expected < 100ms",
            elapsed.as_millis()
        );
    }
}