oximedia-edl 0.1.8

Edit Decision List (EDL) parser and generator for media workflows
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
//! OxiMedia EDL - CMX 3600 Edit Decision List parser and generator.
//!
//! This crate provides comprehensive support for EDL (Edit Decision List) files,
//! with a focus on the CMX 3600 format and related formats.
//!
//! # Features
//!
//! - CMX 3600, CMX 3400, GVG, and Sony BVE-9000 format support
//! - Event types: Cut, Dissolve, Wipe, Key
//! - Timecode support: Drop-frame, Non-drop-frame (24, 25, 30, 60 fps)
//! - Reel names and source references
//! - Motion effects (speed changes, reverse playback, freeze frames)
//! - Audio channel mapping and routing
//! - EDL validation and compliance checking
//! - Format conversion and optimization
//!
//! # Example: Parsing an EDL
//!
//! ```
//! use oximedia_edl::{parse_edl, Edl};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let edl_text = r#"
//! TITLE: Example EDL
//! FCM: DROP FRAME
//!
//! 001  AX       V     C        01:00:00:00 01:00:05:00 01:00:00:00 01:00:05:00
//! * FROM CLIP NAME: shot001.mov
//! "#;
//!
//! let edl = parse_edl(edl_text)?;
//! assert_eq!(edl.title, Some("Example EDL".to_string()));
//! assert_eq!(edl.events.len(), 1);
//! # Ok(())
//! # }
//! ```
//!
//! # Example: Generating an EDL
//!
//! ```
//! use oximedia_edl::{Edl, EdlFormat, EdlGenerator};
//! use oximedia_edl::event::{EdlEvent, EditType, TrackType};
//! use oximedia_edl::timecode::{EdlFrameRate, EdlTimecode};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut edl = Edl::new(EdlFormat::Cmx3600);
//! edl.set_title("My EDL".to_string());
//! edl.set_frame_rate(EdlFrameRate::Fps25);
//!
//! let tc1 = EdlTimecode::new(1, 0, 0, 0, EdlFrameRate::Fps25)?;
//! let tc2 = EdlTimecode::new(1, 0, 5, 0, EdlFrameRate::Fps25)?;
//!
//! let event = EdlEvent::new(
//!     1,
//!     "A001".to_string(),
//!     TrackType::Video,
//!     EditType::Cut,
//!     tc1,
//!     tc2,
//!     tc1,
//!     tc2,
//! );
//!
//! edl.add_event(event)?;
//!
//! let generator = EdlGenerator::new();
//! let output = generator.generate(&edl)?;
//! assert!(output.contains("TITLE: My EDL"));
//! # Ok(())
//! # }
//! ```
//!
//! # Example: Validating an EDL
//!
//! ```
//! use oximedia_edl::{Edl, EdlFormat, EdlValidator};
//! use oximedia_edl::validator::ValidationLevel;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let edl = Edl::new(EdlFormat::Cmx3600);
//! let validator = EdlValidator::strict();
//! let report = validator.validate(&edl)?;
//! # Ok(())
//! # }
//! ```

#![warn(missing_docs)]
#![allow(
    clippy::module_name_repetitions,
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss,
    dead_code,
    clippy::pedantic
)]

pub mod aaf;
pub mod ale;
pub mod audio;
pub mod batch_export;
pub mod cmx3600;
pub mod conform_report;
pub mod consolidate;
pub mod converter;
pub mod diff;
pub mod edl_ascii_timeline;
pub mod edl_changelist;
pub mod edl_comments;
pub mod edl_compare;
pub mod edl_duration;
pub mod edl_event;
pub mod edl_filter;
pub mod edl_merge;
pub mod edl_sanitize;
pub mod edl_statistics;
pub mod edl_timeline;
pub mod edl_validator;
pub mod error;
pub mod event;
pub mod event_list;
pub mod fcpxml;
pub mod filter;
pub mod frame_count;
pub mod fuzz_tests;
pub mod generator;
pub mod lazy_parser;
pub mod metadata;
pub mod motion;
pub mod multicam;
pub mod optimizer;
pub mod otio;
pub mod parser;
pub mod parser_opt;
pub mod reel;
pub mod reel_map;
pub mod reel_registry;
pub mod roundtrip;
pub mod subframe;
pub mod tc_cache;
pub mod tc_list;
pub mod timecode;
pub mod to_timeline;
pub mod transition_events;
pub mod validator;
pub mod version_history;

pub use ale::{parse_ale_records, AleRecord};
pub use batch_export::BatchEdlExporter;
pub use error::{EdlError, EdlResult};
pub use generator::EdlGenerator;
pub use parser::{parse_edl, EdlParser};
pub use validator::EdlValidator;

use crate::event::EdlEvent;
use crate::reel::ReelTable;
use crate::timecode::EdlFrameRate;
use std::path::PathBuf;

/// EDL format identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum EdlFormat {
    /// CMX 3600 format (most common).
    Cmx3600,
    /// CMX 3400 format (older).
    Cmx3400,
    /// CMX 340 format.
    Cmx340,
    /// GVG (Grass Valley Group) format.
    Gvg,
    /// Sony BVE-9000 format.
    SonyBve9000,
}

impl EdlFormat {
    /// Get the format name as a string.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Cmx3600 => "CMX 3600",
            Self::Cmx3400 => "CMX 3400",
            Self::Cmx340 => "CMX 340",
            Self::Gvg => "GVG",
            Self::SonyBve9000 => "Sony BVE-9000",
        }
    }
}

impl std::fmt::Display for EdlFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Main EDL structure containing all events and metadata.
#[derive(Debug, Clone)]
pub struct Edl {
    /// EDL format.
    pub format: EdlFormat,

    /// Optional title of the EDL.
    pub title: Option<String>,

    /// Frame rate for timecodes.
    pub frame_rate: EdlFrameRate,

    /// List of events in the EDL.
    pub events: Vec<EdlEvent>,

    /// Reel table with source information.
    pub reel_table: ReelTable,

    /// Optional source file path (for reference).
    pub source_file: Option<PathBuf>,

    /// Optional comments not associated with specific events.
    pub global_comments: Vec<String>,
}

impl Edl {
    /// Create a new empty EDL with the specified format.
    #[must_use]
    pub fn new(format: EdlFormat) -> Self {
        Self {
            format,
            title: None,
            frame_rate: EdlFrameRate::Fps2997NDF,
            events: Vec::new(),
            reel_table: ReelTable::new(),
            source_file: None,
            global_comments: Vec::new(),
        }
    }

    /// Create a new CMX 3600 EDL (most common format).
    #[must_use]
    pub fn cmx3600() -> Self {
        Self::new(EdlFormat::Cmx3600)
    }

    /// Set the EDL title.
    pub fn set_title(&mut self, title: String) {
        self.title = Some(title);
    }

    /// Set the frame rate.
    pub fn set_frame_rate(&mut self, frame_rate: EdlFrameRate) {
        self.frame_rate = frame_rate;
    }

    /// Set the source file path.
    pub fn set_source_file(&mut self, path: PathBuf) {
        self.source_file = Some(path);
    }

    /// Add an event to the EDL.
    ///
    /// # Errors
    ///
    /// Returns an error if the event is invalid.
    pub fn add_event(&mut self, event: EdlEvent) -> EdlResult<()> {
        event.validate()?;
        self.events.push(event);
        Ok(())
    }

    /// Add a global comment.
    pub fn add_global_comment(&mut self, comment: String) {
        self.global_comments.push(comment);
    }

    /// Get an event by number.
    #[must_use]
    pub fn get_event(&self, number: u32) -> Option<&EdlEvent> {
        self.events.iter().find(|e| e.number == number)
    }

    /// Get a mutable event by number.
    pub fn get_event_mut(&mut self, number: u32) -> Option<&mut EdlEvent> {
        self.events.iter_mut().find(|e| e.number == number)
    }

    /// Remove an event by number.
    pub fn remove_event(&mut self, number: u32) -> Option<EdlEvent> {
        if let Some(index) = self.events.iter().position(|e| e.number == number) {
            Some(self.events.remove(index))
        } else {
            None
        }
    }

    /// Get the number of events.
    #[must_use]
    pub fn event_count(&self) -> usize {
        self.events.len()
    }

    /// Get the total duration of the EDL in frames.
    #[must_use]
    pub fn total_duration_frames(&self) -> u64 {
        self.events.iter().map(|e| e.duration_frames()).sum()
    }

    /// Get the total duration in seconds.
    #[must_use]
    pub fn total_duration_seconds(&self) -> f64 {
        self.total_duration_frames() as f64 / self.frame_rate.fps() as f64
    }

    /// Sort events by record in timecode.
    pub fn sort_events(&mut self) {
        self.events.sort_by_key(|e| e.record_in.to_frames());
    }

    /// Renumber events sequentially starting from 1.
    pub fn renumber_events(&mut self) {
        for (i, event) in self.events.iter_mut().enumerate() {
            event.number = (i + 1) as u32;
        }
    }

    /// Validate the entire EDL.
    ///
    /// # Errors
    ///
    /// Returns an error if the EDL is invalid.
    pub fn validate(&self) -> EdlResult<()> {
        let validator = EdlValidator::default();
        validator.validate(self)?;
        Ok(())
    }

    /// Generate the EDL as a string.
    ///
    /// # Errors
    ///
    /// Returns an error if generation fails.
    pub fn to_string_format(&self) -> EdlResult<String> {
        let generator = EdlGenerator::new();
        generator.generate(self)
    }

    /// Parse an EDL from a string.
    ///
    /// # Errors
    ///
    /// Returns an error if parsing fails.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(input: &str) -> EdlResult<Self> {
        parse_edl(input)
    }

    /// Load an EDL from a file.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or parsed.
    pub fn from_file(path: &std::path::Path) -> EdlResult<Self> {
        let content = std::fs::read_to_string(path)?;
        let mut edl = parse_edl(&content)?;
        edl.set_source_file(path.to_path_buf());
        Ok(edl)
    }

    /// Save the EDL to a file.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be written.
    pub fn to_file(&self, path: &std::path::Path) -> EdlResult<()> {
        let generator = EdlGenerator::new();
        generator.generate_to_file(self, path)
    }
}

impl Default for Edl {
    fn default() -> Self {
        Self::cmx3600()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::{EditType, TrackType};
    use crate::timecode::EdlTimecode;

    #[test]
    fn test_create_edl() {
        let edl = Edl::new(EdlFormat::Cmx3600);
        assert_eq!(edl.format, EdlFormat::Cmx3600);
        assert_eq!(edl.events.len(), 0);
    }

    #[test]
    fn test_add_event() {
        let mut edl = Edl::new(EdlFormat::Cmx3600);
        edl.set_frame_rate(EdlFrameRate::Fps25);

        let tc1 = EdlTimecode::new(1, 0, 0, 0, EdlFrameRate::Fps25).expect("failed to create");
        let tc2 = EdlTimecode::new(1, 0, 5, 0, EdlFrameRate::Fps25).expect("failed to create");

        let event = EdlEvent::new(
            1,
            "A001".to_string(),
            TrackType::Video,
            EditType::Cut,
            tc1,
            tc2,
            tc1,
            tc2,
        );

        edl.add_event(event).expect("add_event should succeed");
        assert_eq!(edl.events.len(), 1);
    }

    #[test]
    fn test_get_event() {
        let mut edl = Edl::new(EdlFormat::Cmx3600);
        edl.set_frame_rate(EdlFrameRate::Fps25);

        let tc1 = EdlTimecode::new(1, 0, 0, 0, EdlFrameRate::Fps25).expect("failed to create");
        let tc2 = EdlTimecode::new(1, 0, 5, 0, EdlFrameRate::Fps25).expect("failed to create");

        let event = EdlEvent::new(
            1,
            "A001".to_string(),
            TrackType::Video,
            EditType::Cut,
            tc1,
            tc2,
            tc1,
            tc2,
        );

        edl.add_event(event).expect("add_event should succeed");

        let retrieved = edl.get_event(1).expect("get_event should succeed");
        assert_eq!(retrieved.number, 1);
    }

    #[test]
    fn test_remove_event() {
        let mut edl = Edl::new(EdlFormat::Cmx3600);
        edl.set_frame_rate(EdlFrameRate::Fps25);

        let tc1 = EdlTimecode::new(1, 0, 0, 0, EdlFrameRate::Fps25).expect("failed to create");
        let tc2 = EdlTimecode::new(1, 0, 5, 0, EdlFrameRate::Fps25).expect("failed to create");

        let event = EdlEvent::new(
            1,
            "A001".to_string(),
            TrackType::Video,
            EditType::Cut,
            tc1,
            tc2,
            tc1,
            tc2,
        );

        edl.add_event(event).expect("add_event should succeed");
        assert_eq!(edl.events.len(), 1);

        edl.remove_event(1);
        assert_eq!(edl.events.len(), 0);
    }

    #[test]
    fn test_renumber_events() {
        let mut edl = Edl::new(EdlFormat::Cmx3600);
        edl.set_frame_rate(EdlFrameRate::Fps25);

        let tc1 = EdlTimecode::new(1, 0, 0, 0, EdlFrameRate::Fps25).expect("failed to create");
        let tc2 = EdlTimecode::new(1, 0, 5, 0, EdlFrameRate::Fps25).expect("failed to create");

        let event1 = EdlEvent::new(
            10,
            "A001".to_string(),
            TrackType::Video,
            EditType::Cut,
            tc1,
            tc2,
            tc1,
            tc2,
        );

        let event2 = EdlEvent::new(
            20,
            "A002".to_string(),
            TrackType::Video,
            EditType::Cut,
            tc1,
            tc2,
            tc1,
            tc2,
        );

        edl.add_event(event1).expect("add_event should succeed");
        edl.add_event(event2).expect("add_event should succeed");

        edl.renumber_events();

        assert_eq!(edl.events[0].number, 1);
        assert_eq!(edl.events[1].number, 2);
    }

    #[test]
    fn test_total_duration() {
        let mut edl = Edl::new(EdlFormat::Cmx3600);
        edl.set_frame_rate(EdlFrameRate::Fps25);

        let tc1 = EdlTimecode::new(1, 0, 0, 0, EdlFrameRate::Fps25).expect("failed to create");
        let tc2 = EdlTimecode::new(1, 0, 5, 0, EdlFrameRate::Fps25).expect("failed to create");

        let event = EdlEvent::new(
            1,
            "A001".to_string(),
            TrackType::Video,
            EditType::Cut,
            tc1,
            tc2,
            tc1,
            tc2,
        );

        edl.add_event(event).expect("add_event should succeed");

        let duration_frames = edl.total_duration_frames();
        assert_eq!(duration_frames, 125); // 5 seconds * 25 fps

        let duration_seconds = edl.total_duration_seconds();
        assert!((duration_seconds - 5.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_edl_format_display() {
        assert_eq!(EdlFormat::Cmx3600.to_string(), "CMX 3600");
        assert_eq!(EdlFormat::Cmx3400.to_string(), "CMX 3400");
        assert_eq!(EdlFormat::Gvg.to_string(), "GVG");
    }

    #[test]
    fn test_parse_and_generate_roundtrip() {
        let edl_text = r#"TITLE: Test EDL
FCM: NON-DROP FRAME

001  AX       V     C        01:00:00:00 01:00:05:00 01:00:00:00 01:00:05:00

"#;

        let edl = parse_edl(edl_text).expect("operation should succeed");
        let generated = edl.to_string_format().expect("formatting should succeed");

        // Parse the generated EDL again
        let edl2 = parse_edl(&generated).expect("operation should succeed");

        assert_eq!(edl.title, edl2.title);
        assert_eq!(edl.events.len(), edl2.events.len());
        assert_eq!(edl.events[0].number, edl2.events[0].number);
    }

    /// Requirement: test_cmx3600_roundtrip — creates an Edl with 3 events,
    /// serialises to CMX-3600 format, re-parses, and verifies event count and
    /// reel names are preserved.
    #[test]
    fn test_cmx3600_roundtrip() {
        let mut edl = Edl::new(EdlFormat::Cmx3600);
        edl.set_title("Roundtrip Test EDL".to_string());
        edl.set_frame_rate(EdlFrameRate::Fps25);

        let reels = ["ALPHA", "BETA", "GAMMA"];
        for (i, reel) in reels.iter().enumerate() {
            let n = i as u8;
            let tc_in = EdlTimecode::new(1, 0, n * 5, 0, EdlFrameRate::Fps25).expect("valid tc_in");
            let tc_out =
                EdlTimecode::new(1, 0, n * 5 + 5, 0, EdlFrameRate::Fps25).expect("valid tc_out");
            let event = EdlEvent::new(
                (i + 1) as u32,
                reel.to_string(),
                TrackType::Video,
                EditType::Cut,
                tc_in,
                tc_out,
                tc_in,
                tc_out,
            );
            edl.add_event(event).expect("add_event should succeed");
        }

        assert_eq!(
            edl.events.len(),
            3,
            "EDL should have 3 events before serialisation"
        );

        // Serialise to CMX-3600 format string.
        let cmx_string = edl
            .to_string_format()
            .expect("serialisation should succeed");
        assert!(
            cmx_string.contains("TITLE: Roundtrip Test EDL"),
            "generated text should contain the title"
        );

        // Re-parse the generated string.
        let edl2 = parse_edl(&cmx_string).expect("re-parse should succeed");

        // Verify event count.
        assert_eq!(
            edl2.events.len(),
            3,
            "re-parsed EDL should have 3 events; generated text:\n{cmx_string}"
        );

        // Verify reel names are preserved in order.
        for (orig_event, reparsed_event) in edl.events.iter().zip(edl2.events.iter()) {
            assert_eq!(
                orig_event.reel, reparsed_event.reel,
                "reel name should survive the roundtrip"
            );
        }
    }
}