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
//! Conform session management.

use crate::config::ConformConfig;
use crate::error::{ConformError, ConformResult};
use crate::exporters::report::{AmbiguousMatch, MatchReport};
use crate::exporters::{project::ProjectExporter, sequence::SequenceExporter, Exporter};
use crate::importers::{edl::EdlImporter, TimelineImporter};
use crate::matching::strategies::MatchStrategy;
use crate::media::{catalog::MediaCatalog, scanner::MediaScanner, ScanProgress};
use crate::qc::{checker::QualityChecker, validator::Validator};
use crate::timeline::{Timeline, TimelineClip, Track, TrackKind};
use crate::types::{ClipMatch, ClipReference, OutputFormat};
use parking_lot::RwLock;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tracing::{debug, info, warn};
use uuid::Uuid;

/// Conform session status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionStatus {
    /// Session created but not started.
    Created,
    /// Scanning source media.
    Scanning,
    /// Matching clips.
    Matching,
    /// Conforming.
    Conforming,
    /// Exporting.
    Exporting,
    /// Completed successfully.
    Completed,
    /// Failed.
    Failed,
}

/// A conform session that manages the entire conforming workflow.
pub struct ConformSession {
    /// Unique session ID.
    id: Uuid,
    /// Session name.
    name: String,
    /// EDL or timeline path.
    timeline_path: PathBuf,
    /// Source media paths to scan.
    source_paths: Vec<PathBuf>,
    /// Output path for conformed sequence.
    output_path: PathBuf,
    /// Configuration.
    config: ConformConfig,
    /// Media catalog.
    catalog: MediaCatalog,
    /// Clips to match.
    clips: Vec<ClipReference>,
    /// Match results.
    matches: Arc<RwLock<Vec<ClipMatch>>>,
    /// Missing clips.
    missing: Arc<RwLock<Vec<ClipReference>>>,
    /// Ambiguous matches.
    ambiguous: Arc<RwLock<Vec<AmbiguousMatch>>>,
    /// Session status.
    status: Arc<RwLock<SessionStatus>>,
}

impl ConformSession {
    /// Create a new conform session.
    ///
    /// # Errors
    ///
    /// Returns an error if the session cannot be created.
    pub fn new<P: AsRef<Path>>(
        name: String,
        timeline_path: P,
        source_paths: Vec<PathBuf>,
        output_path: PathBuf,
        config: ConformConfig,
    ) -> ConformResult<Self> {
        let id = Uuid::new_v4();
        let catalog = MediaCatalog::in_memory()?;

        Ok(Self {
            id,
            name,
            timeline_path: timeline_path.as_ref().to_path_buf(),
            source_paths,
            output_path,
            config,
            catalog,
            clips: Vec::new(),
            matches: Arc::new(RwLock::new(Vec::new())),
            missing: Arc::new(RwLock::new(Vec::new())),
            ambiguous: Arc::new(RwLock::new(Vec::new())),
            status: Arc::new(RwLock::new(SessionStatus::Created)),
        })
    }

    /// Create a new conform session with a database.
    ///
    /// # Errors
    ///
    /// Returns an error if the session cannot be created.
    pub fn with_database<P: AsRef<Path>>(
        name: String,
        timeline_path: P,
        source_paths: Vec<PathBuf>,
        output_path: PathBuf,
        config: ConformConfig,
        db_path: P,
    ) -> ConformResult<Self> {
        let id = Uuid::new_v4();
        let catalog = MediaCatalog::new(db_path)?;

        Ok(Self {
            id,
            name,
            timeline_path: timeline_path.as_ref().to_path_buf(),
            source_paths,
            output_path,
            config,
            catalog,
            clips: Vec::new(),
            matches: Arc::new(RwLock::new(Vec::new())),
            missing: Arc::new(RwLock::new(Vec::new())),
            ambiguous: Arc::new(RwLock::new(Vec::new())),
            status: Arc::new(RwLock::new(SessionStatus::Created)),
        })
    }

    /// Get the session ID.
    #[must_use]
    pub fn id(&self) -> Uuid {
        self.id
    }

    /// Get the session name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the current status.
    #[must_use]
    pub fn status(&self) -> SessionStatus {
        *self.status.read()
    }

    /// Set the status.
    fn set_status(&self, status: SessionStatus) {
        *self.status.write() = status;
    }

    /// Load clips from the timeline file.
    ///
    /// # Errors
    ///
    /// Returns an error if the timeline cannot be loaded.
    pub async fn load_timeline(&mut self) -> ConformResult<()> {
        info!("Loading timeline from {}", self.timeline_path.display());

        // Detect format and import
        let clips = if self.timeline_path.extension().and_then(|e| e.to_str()) == Some("edl") {
            let importer = EdlImporter::new();
            importer.import(&self.timeline_path)?
        } else {
            return Err(ConformError::UnsupportedFormat(
                "Only EDL files are currently supported".to_string(),
            ));
        };

        info!("Loaded {} clips from timeline", clips.len());
        self.clips = clips;
        Ok(())
    }

    /// Scan source media directories.
    ///
    /// # Errors
    ///
    /// Returns an error if scanning fails.
    pub async fn scan_sources(&mut self) -> ConformResult<ScanProgress> {
        self.set_status(SessionStatus::Scanning);
        info!("Scanning {} source paths", self.source_paths.len());

        let mut scanner = MediaScanner::new();
        scanner.generate_checksums(self.config.verify_checksums);

        let progress = Arc::new(ScanProgress::new());
        let mut all_media = Vec::new();

        for source_path in &self.source_paths {
            info!("Scanning {}", source_path.display());
            let media = scanner.scan(source_path, Some(progress.clone()))?;
            all_media.extend(media);
        }

        info!("Found {} media files", all_media.len());
        self.catalog.add_many(all_media)?;

        Ok((*progress).clone())
    }

    /// Match clips to media files.
    ///
    /// # Errors
    ///
    /// Returns an error if matching fails.
    pub async fn match_clips(&mut self) -> ConformResult<MatchReport> {
        self.set_status(SessionStatus::Matching);
        info!("Matching {} clips", self.clips.len());

        let strategy = MatchStrategy::new(self.config.clone());
        let all_media = self.catalog.get_all()?;

        let mut matched = Vec::new();
        let mut missing = Vec::new();
        let mut ambiguous = Vec::new();

        for clip in &self.clips {
            let clip_matches = strategy.match_clip(clip, &all_media);

            if clip_matches.is_empty() {
                warn!("No match found for clip: {}", clip.id);
                missing.push(clip.clone());
            } else if clip_matches.len() == 1 {
                debug!(
                    "Found match for clip {}: score {:.2}",
                    clip.id, clip_matches[0].score
                );
                matched.push(clip_matches[0].clone());
            } else {
                // Multiple matches - check if ambiguous
                if strategy.is_ambiguous(&clip_matches, 0.05) {
                    warn!(
                        "Ambiguous matches for clip {}: {} candidates",
                        clip.id,
                        clip_matches.len()
                    );
                    ambiguous.push(AmbiguousMatch {
                        clip: clip.clone(),
                        candidates: clip_matches,
                    });
                } else {
                    // Use best match
                    debug!(
                        "Using best match for clip {}: score {:.2}",
                        clip.id, clip_matches[0].score
                    );
                    matched.push(clip_matches[0].clone());
                }
            }
        }

        info!(
            "Matching complete: {} matched, {} missing, {} ambiguous",
            matched.len(),
            missing.len(),
            ambiguous.len()
        );

        *self.matches.write() = matched.clone();
        *self.missing.write() = missing.clone();
        *self.ambiguous.write() = ambiguous.clone();

        Ok(MatchReport::new(matched, missing, ambiguous))
    }

    /// Validate matches.
    ///
    /// # Errors
    ///
    /// Returns an error if validation fails.
    pub fn validate(&self) -> ConformResult<()> {
        info!("Validating matches");

        let validator = Validator::new(self.config.clone());
        let matches = self.matches.read();
        let report = validator.validate_all(&matches);

        if !report.is_valid {
            if self.config.strict_validation {
                return Err(ConformError::Validation(format!(
                    "Validation failed with {} errors",
                    report.errors.len()
                )));
            }
            warn!(
                "Validation found {} errors and {} warnings",
                report.errors.len(),
                report.warnings.len()
            );
        }

        let checker = QualityChecker::new();
        checker.check_format_consistency(&matches)?;
        checker.check_timecode_continuity(&matches)?;

        info!("Validation complete");
        Ok(())
    }

    /// Perform conforming.
    ///
    /// # Errors
    ///
    /// Returns an error if conforming fails.
    pub async fn conform(&mut self) -> ConformResult<Timeline> {
        self.set_status(SessionStatus::Conforming);
        info!("Conforming sequence");

        let matches = self.matches.read();
        if matches.is_empty() {
            return Err(ConformError::Other("No matches to conform".to_string()));
        }

        // Build timeline
        let fps = matches[0].clip.fps;
        let mut timeline = Timeline::new(self.name.clone(), fps);

        // Create video track
        let mut video_track = Track::new("V1".to_string(), TrackKind::Video);
        for clip_match in matches.iter() {
            if clip_match.clip.track.has_video() {
                let clip = TimelineClip::from_match(clip_match);
                video_track.add_clip(clip);
            }
        }
        video_track.sort_clips();
        timeline.add_video_track(video_track);

        // Create audio track
        let mut audio_track = Track::new("A1".to_string(), TrackKind::Audio);
        for clip_match in matches.iter() {
            if clip_match.clip.track.has_audio() {
                let clip = TimelineClip::from_match(clip_match);
                audio_track.add_clip(clip);
            }
        }
        audio_track.sort_clips();
        timeline.add_audio_track(audio_track);

        info!(
            "Timeline created with {} video tracks and {} audio tracks",
            timeline.video_tracks.len(),
            timeline.audio_tracks.len()
        );

        self.set_status(SessionStatus::Completed);
        Ok(timeline)
    }

    /// Export the conformed sequence.
    ///
    /// # Errors
    ///
    /// Returns an error if export fails.
    pub async fn export(&self, format: OutputFormat) -> ConformResult<()> {
        self.set_status(SessionStatus::Exporting);
        info!("Exporting to {:?}", format);

        let matches = self.matches.read();

        match format {
            OutputFormat::Mp4
            | OutputFormat::Matroska
            | OutputFormat::FrameSequenceDpx
            | OutputFormat::FrameSequenceTiff
            | OutputFormat::FrameSequencePng => {
                let exporter = SequenceExporter::new(matches.clone());
                exporter.export(&self.output_path, format)?;
            }
            OutputFormat::Edl
            | OutputFormat::FcpXml
            | OutputFormat::PremiereXml
            | OutputFormat::Aaf => {
                let exporter = ProjectExporter::new(matches.clone());
                exporter.export(&self.output_path, format)?;
            }
        }

        info!("Export complete");
        Ok(())
    }

    /// Generate a match report.
    #[must_use]
    pub fn get_match_report(&self) -> MatchReport {
        MatchReport::new(
            self.matches.read().clone(),
            self.missing.read().clone(),
            self.ambiguous.read().clone(),
        )
    }

    /// Run the complete conform workflow.
    ///
    /// # Errors
    ///
    /// Returns an error if any step fails.
    pub async fn run(&mut self) -> ConformResult<MatchReport> {
        info!("Starting conform session: {}", self.name);

        // Load timeline
        self.load_timeline().await?;

        // Scan sources
        self.scan_sources().await?;

        // Match clips
        let report = self.match_clips().await?;

        // Validate
        self.validate()?;

        // Conform
        self.conform().await?;

        info!("Conform session complete");
        Ok(report)
    }
}

// ── Watch folder mode ─────────────────────────────────────────────────────────

/// A lightweight watch-folder session that polls a directory at a fixed
/// interval and reports newly detected source files.
///
/// This is intentionally synchronous so it can be driven from a background
/// thread or a polling loop without requiring an async runtime.
pub struct WatchFolderSession {
    /// Directory to poll for new source files.
    pub poll_dir: PathBuf,
    /// Polling interval in seconds.
    pub poll_interval_secs: u64,
    /// Known paths from the previous poll — used to detect new arrivals.
    known_paths: parking_lot::Mutex<std::collections::HashSet<PathBuf>>,
}

impl WatchFolderSession {
    /// Create a new `WatchFolderSession` for `poll_dir` with the given
    /// polling interval.
    ///
    /// The set of "known" paths is initialised to the files present in
    /// `poll_dir` at construction time so that pre-existing files are not
    /// reported as new on the first call to [`check_for_new_sources`].
    ///
    /// [`check_for_new_sources`]: WatchFolderSession::check_for_new_sources
    #[must_use]
    pub fn new(poll_dir: PathBuf, poll_interval_secs: u64) -> Self {
        let initial = collect_source_paths(&poll_dir);
        Self {
            poll_dir,
            poll_interval_secs,
            known_paths: parking_lot::Mutex::new(initial),
        }
    }

    /// Poll `poll_dir` once and return paths of **newly detected** source
    /// files (files present now that were not present on the previous call).
    ///
    /// After this call the internal set of known paths is updated to include
    /// all currently visible files.
    #[must_use]
    pub fn check_for_new_sources(&self) -> Vec<PathBuf> {
        let current = collect_source_paths(&self.poll_dir);

        let mut known = self.known_paths.lock();
        let new_paths: Vec<PathBuf> = current
            .iter()
            .filter(|p| !known.contains(*p))
            .cloned()
            .collect();

        // Update known set with everything we see now.
        *known = current;
        new_paths
    }
}

/// Collect all regular-file paths inside `dir` (non-recursive, depth=1).
fn collect_source_paths(dir: &Path) -> std::collections::HashSet<PathBuf> {
    std::fs::read_dir(dir)
        .into_iter()
        .flatten()
        .filter_map(|entry| {
            let entry = entry.ok()?;
            let ft = entry.file_type().ok()?;
            if ft.is_file() {
                Some(entry.path())
            } else {
                None
            }
        })
        .collect()
}

use crate::types::TrackType;

impl TrackType {
    #[must_use]
    pub(crate) const fn has_video(&self) -> bool {
        matches!(self, Self::Video | Self::AudioVideo)
    }

    #[must_use]
    pub(crate) const fn has_audio(&self) -> bool {
        matches!(self, Self::Audio | Self::AudioVideo)
    }
}

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

    #[test]
    fn test_session_creation() {
        let session = ConformSession::new(
            "Test Session".to_string(),
            PathBuf::from("/test/timeline.edl"),
            vec![PathBuf::from("/test/media")],
            PathBuf::from("/test/output"),
            ConformConfig::default(),
        )
        .expect("test expectation failed");

        assert_eq!(session.name(), "Test Session");
        assert_eq!(session.status(), SessionStatus::Created);
    }

    #[test]
    fn test_status_changes() {
        let session = ConformSession::new(
            "Test".to_string(),
            PathBuf::from("/test/timeline.edl"),
            vec![],
            PathBuf::from("/test/output"),
            ConformConfig::default(),
        )
        .expect("test expectation failed");

        assert_eq!(session.status(), SessionStatus::Created);
        session.set_status(SessionStatus::Scanning);
        assert_eq!(session.status(), SessionStatus::Scanning);
    }

    // ── WatchFolderSession tests ──────────────────────────────────────────────

    #[test]
    fn test_watch_folder_no_new_files_initially() {
        let temp_dir = tempfile::TempDir::new().expect("temp dir should be created");
        // Place a file before constructing the session
        std::fs::write(temp_dir.path().join("pre_existing.mov"), b"x")
            .expect("write should succeed");

        let session = WatchFolderSession::new(temp_dir.path().to_path_buf(), 5);
        // On first check, nothing should be new (pre-existing files are known)
        let new = session.check_for_new_sources();
        assert!(
            new.is_empty(),
            "pre-existing files must not be reported as new, got {new:?}"
        );
    }

    #[test]
    fn test_watch_folder_detects_new_file() {
        let temp_dir = tempfile::TempDir::new().expect("temp dir should be created");

        let session = WatchFolderSession::new(temp_dir.path().to_path_buf(), 5);

        // No files yet — first check returns nothing
        assert!(session.check_for_new_sources().is_empty());

        // Add a new file
        let new_file = temp_dir.path().join("shot_001.mov");
        std::fs::write(&new_file, b"data").expect("write should succeed");

        let new = session.check_for_new_sources();
        assert_eq!(new.len(), 1, "new file should be detected");
        assert_eq!(new[0], new_file);
    }

    #[test]
    fn test_watch_folder_does_not_re_report_known_files() {
        let temp_dir = tempfile::TempDir::new().expect("temp dir should be created");
        let session = WatchFolderSession::new(temp_dir.path().to_path_buf(), 5);

        // Introduce a file and consume the notification
        std::fs::write(temp_dir.path().join("clip.mov"), b"data").expect("write should succeed");
        let first = session.check_for_new_sources();
        assert_eq!(first.len(), 1);

        // Second call must not re-report the same file
        let second = session.check_for_new_sources();
        assert!(
            second.is_empty(),
            "already-reported file must not be reported again"
        );
    }

    #[test]
    fn test_watch_folder_detects_multiple_new_files() {
        let temp_dir = tempfile::TempDir::new().expect("temp dir should be created");
        let session = WatchFolderSession::new(temp_dir.path().to_path_buf(), 1);

        // Baseline check
        assert!(session.check_for_new_sources().is_empty());

        // Add three files
        for i in 0..3u8 {
            std::fs::write(temp_dir.path().join(format!("clip_{i}.mov")), b"data")
                .expect("write should succeed");
        }

        let new = session.check_for_new_sources();
        assert_eq!(new.len(), 3, "all three new files should be detected");
    }
}