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
//! EDL roundtrip validation.
//!
//! A *roundtrip* test parses an EDL text string into an [`crate::Edl`],
//! generates it back to text, then re-parses the generated text and compares
//! the two parsed structures for semantic equality.  Any differences indicate
//! lossiness in the parser/generator pair.

#![allow(dead_code)]

use crate::error::EdlResult;
use crate::event::EdlEvent;
use crate::{parse_edl, Edl, EdlGenerator};

// ────────────────────────────────────────────────────────────────────────────
// RoundtripDiff
// ────────────────────────────────────────────────────────────────────────────

/// A single semantic difference found between two parsed EDLs.
#[derive(Debug, Clone, PartialEq)]
pub enum RoundtripDiff {
    /// The EDL title changed.
    TitleMismatch {
        /// Title from the original parse.
        original: Option<String>,
        /// Title from the re-parse.
        regenerated: Option<String>,
    },
    /// The event count changed.
    EventCountMismatch {
        /// Event count from the original parse.
        original: usize,
        /// Event count from the re-parse.
        regenerated: usize,
    },
    /// A specific event changed.
    EventMismatch {
        /// Event number (1-based).
        event_number: u32,
        /// Human-readable description of what changed.
        description: String,
    },
    /// The frame count mode (drop-frame / non-drop-frame) changed.
    FrameRateMismatch {
        /// Description of the original frame rate.
        original: String,
        /// Description of the regenerated frame rate.
        regenerated: String,
    },
}

// ────────────────────────────────────────────────────────────────────────────
// RoundtripReport
// ────────────────────────────────────────────────────────────────────────────

/// Full report produced by a roundtrip validation pass.
#[derive(Debug, Clone)]
pub struct RoundtripReport {
    /// The re-generated EDL text (useful for debugging).
    pub generated_text: String,
    /// Differences found, if any.
    pub diffs: Vec<RoundtripDiff>,
}

impl RoundtripReport {
    /// Returns `true` when the roundtrip was lossless.
    #[must_use]
    pub fn is_lossless(&self) -> bool {
        self.diffs.is_empty()
    }

    /// Number of differences found.
    #[must_use]
    pub fn diff_count(&self) -> usize {
        self.diffs.len()
    }
}

// ────────────────────────────────────────────────────────────────────────────
// RoundtripValidator
// ────────────────────────────────────────────────────────────────────────────

/// Validates an EDL by performing a parse → generate → re-parse cycle.
#[derive(Debug, Default)]
pub struct RoundtripValidator {
    /// If `true`, compare clip names attached to events.
    pub check_clip_names: bool,
    /// If `true`, compare comments attached to events.
    pub check_comments: bool,
}

impl RoundtripValidator {
    /// Create a new validator with all checks enabled.
    #[must_use]
    pub fn full() -> Self {
        Self {
            check_clip_names: true,
            check_comments: true,
        }
    }

    /// Validate `edl_text` for roundtrip losslessness.
    ///
    /// # Errors
    ///
    /// Returns an [`crate::error::EdlError`] if either parse or generation
    /// step fails.
    pub fn validate(&self, edl_text: &str) -> EdlResult<RoundtripReport> {
        // Step 1: original parse.
        let original = parse_edl(edl_text)?;

        // Step 2: generate.
        let generator = EdlGenerator::new();
        let generated_text = generator.generate(&original)?;

        // Step 3: re-parse.
        let regenerated = parse_edl(&generated_text)?;

        // Step 4: compare.
        let diffs = self.compare(&original, &regenerated);

        Ok(RoundtripReport {
            generated_text,
            diffs,
        })
    }

    /// Compare two parsed EDLs and return any differences.
    #[must_use]
    pub fn compare(&self, a: &Edl, b: &Edl) -> Vec<RoundtripDiff> {
        let mut diffs = Vec::new();

        // Title.
        if a.title != b.title {
            diffs.push(RoundtripDiff::TitleMismatch {
                original: a.title.clone(),
                regenerated: b.title.clone(),
            });
        }

        // Frame rate.
        if a.frame_rate != b.frame_rate {
            diffs.push(RoundtripDiff::FrameRateMismatch {
                original: format!("{:?}", a.frame_rate),
                regenerated: format!("{:?}", b.frame_rate),
            });
        }

        // Event count.
        if a.events.len() != b.events.len() {
            diffs.push(RoundtripDiff::EventCountMismatch {
                original: a.events.len(),
                regenerated: b.events.len(),
            });
            // Can't compare individual events if counts differ.
            return diffs;
        }

        // Per-event comparison.
        for (ea, eb) in a.events.iter().zip(b.events.iter()) {
            self.compare_event(ea, eb, &mut diffs);
        }

        diffs
    }

    fn compare_event(&self, a: &EdlEvent, b: &EdlEvent, diffs: &mut Vec<RoundtripDiff>) {
        if a.number != b.number {
            diffs.push(RoundtripDiff::EventMismatch {
                event_number: a.number,
                description: format!("event number changed: {}{}", a.number, b.number),
            });
        }
        if a.reel != b.reel {
            diffs.push(RoundtripDiff::EventMismatch {
                event_number: a.number,
                description: format!("reel changed: {:?}{:?}", a.reel, b.reel),
            });
        }
        if a.edit_type != b.edit_type {
            diffs.push(RoundtripDiff::EventMismatch {
                event_number: a.number,
                description: format!("edit type changed: {:?}{:?}", a.edit_type, b.edit_type),
            });
        }
        if a.source_in != b.source_in {
            diffs.push(RoundtripDiff::EventMismatch {
                event_number: a.number,
                description: format!("source_in changed: {:?}{:?}", a.source_in, b.source_in),
            });
        }
        if a.source_out != b.source_out {
            diffs.push(RoundtripDiff::EventMismatch {
                event_number: a.number,
                description: format!(
                    "source_out changed: {:?}{:?}",
                    a.source_out, b.source_out
                ),
            });
        }
        if a.record_in != b.record_in {
            diffs.push(RoundtripDiff::EventMismatch {
                event_number: a.number,
                description: format!("record_in changed: {:?}{:?}", a.record_in, b.record_in),
            });
        }
        if a.record_out != b.record_out {
            diffs.push(RoundtripDiff::EventMismatch {
                event_number: a.number,
                description: format!(
                    "record_out changed: {:?}{:?}",
                    a.record_out, b.record_out
                ),
            });
        }
        if self.check_clip_names && a.clip_name != b.clip_name {
            diffs.push(RoundtripDiff::EventMismatch {
                event_number: a.number,
                description: format!("clip_name changed: {:?}{:?}", a.clip_name, b.clip_name),
            });
        }
    }
}

// ────────────────────────────────────────────────────────────────────────────
// Convenience helpers
// ────────────────────────────────────────────────────────────────────────────

/// Quick check: parse `edl_text`, generate, re-parse and confirm lossless.
///
/// Returns `Ok(true)` when lossless, `Ok(false)` when differences are found,
/// and `Err` when parsing/generation fails.
///
/// # Errors
///
/// Propagates any [`crate::error::EdlError`] from parse or generation.
pub fn is_lossless(edl_text: &str) -> EdlResult<bool> {
    let validator = RoundtripValidator::default();
    let report = validator.validate(edl_text)?;
    Ok(report.is_lossless())
}

// ────────────────────────────────────────────────────────────────────────────
// Tests
// ────────────────────────────────────────────────────────────────────────────

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

    const SIMPLE_EDL: &str = r#"TITLE: Roundtrip Test
FCM: NON-DROP FRAME

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

"#;

    #[test]
    fn test_lossless_simple_edl() {
        let result = is_lossless(SIMPLE_EDL).expect("operation should succeed");
        assert!(result, "Simple EDL should survive a roundtrip unchanged");
    }

    #[test]
    fn test_roundtrip_report_is_lossless() {
        let validator = RoundtripValidator::default();
        let report = validator
            .validate(SIMPLE_EDL)
            .expect("validation should succeed");
        assert!(report.is_lossless());
        assert_eq!(report.diff_count(), 0);
    }

    #[test]
    fn test_generated_text_not_empty() {
        let validator = RoundtripValidator::default();
        let report = validator
            .validate(SIMPLE_EDL)
            .expect("validation should succeed");
        assert!(!report.generated_text.is_empty());
    }

    #[test]
    fn test_generated_text_contains_title() {
        let validator = RoundtripValidator::default();
        let report = validator
            .validate(SIMPLE_EDL)
            .expect("validation should succeed");
        assert!(report.generated_text.contains("Roundtrip Test"));
    }

    #[test]
    fn test_two_event_edl_roundtrip() {
        let edl_text = r#"TITLE: Two Events
FCM: NON-DROP FRAME

001  A001     V     C        01:00:00:00 01:00:05:00 01:00:00:00 01:00:05:00
002  B001     V     C        01:00:05:00 01:00:10:00 01:00:05:00 01:00:10:00

"#;
        let result = is_lossless(edl_text).expect("operation should succeed");
        assert!(result);
    }

    #[test]
    fn test_compare_identical_edls_no_diffs() {
        let a = parse_edl(SIMPLE_EDL).expect("operation should succeed");
        let b = parse_edl(SIMPLE_EDL).expect("operation should succeed");
        let validator = RoundtripValidator::default();
        let diffs = validator.compare(&a, &b);
        assert!(diffs.is_empty());
    }

    #[test]
    fn test_compare_different_titles_produces_diff() {
        let mut a = parse_edl(SIMPLE_EDL).expect("operation should succeed");
        let b = parse_edl(SIMPLE_EDL).expect("operation should succeed");
        a.title = Some("Different Title".to_string());
        let validator = RoundtripValidator::default();
        let diffs = validator.compare(&a, &b);
        assert!(!diffs.is_empty());
        assert!(matches!(diffs[0], RoundtripDiff::TitleMismatch { .. }));
    }

    #[test]
    fn test_compare_different_event_counts_produces_diff() {
        let a = parse_edl(SIMPLE_EDL).expect("operation should succeed");
        let mut b = parse_edl(SIMPLE_EDL).expect("operation should succeed");
        b.events.clear();
        let validator = RoundtripValidator::default();
        let diffs = validator.compare(&a, &b);
        assert!(!diffs.is_empty());
        assert!(matches!(diffs[0], RoundtripDiff::EventCountMismatch { .. }));
    }

    #[test]
    fn test_roundtrip_diff_event_count_mismatch_values() {
        let diff = RoundtripDiff::EventCountMismatch {
            original: 3,
            regenerated: 2,
        };
        if let RoundtripDiff::EventCountMismatch {
            original,
            regenerated,
        } = diff
        {
            assert_eq!(original, 3);
            assert_eq!(regenerated, 2);
        }
    }

    #[test]
    fn test_roundtrip_diff_title_mismatch_values() {
        let diff = RoundtripDiff::TitleMismatch {
            original: Some("A".to_string()),
            regenerated: Some("B".to_string()),
        };
        if let RoundtripDiff::TitleMismatch {
            original,
            regenerated,
        } = diff
        {
            assert_eq!(original, Some("A".to_string()));
            assert_eq!(regenerated, Some("B".to_string()));
        }
    }

    #[test]
    fn test_full_validator_checks_clip_names() {
        let v = RoundtripValidator::full();
        assert!(v.check_clip_names);
        assert!(v.check_comments);
    }

    #[test]
    fn test_report_diff_count_matches_diffs_vec() {
        let report = RoundtripReport {
            generated_text: String::new(),
            diffs: vec![
                RoundtripDiff::TitleMismatch {
                    original: None,
                    regenerated: None,
                },
                RoundtripDiff::EventCountMismatch {
                    original: 0,
                    regenerated: 1,
                },
            ],
        };
        assert_eq!(report.diff_count(), 2);
        assert!(!report.is_lossless());
    }

    #[test]
    fn test_is_lossless_helper_returns_true_for_valid_edl() {
        let result = is_lossless(SIMPLE_EDL);
        assert!(result.is_ok());
        assert!(result.expect("result should be valid"));
    }

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

001  AX       V     C        01:00:00:00 01:00:03:00 01:00:00:00 01:00:03:00
002  AX       V     C        01:00:03:00 01:00:06:00 01:00:03:00 01:00:06:00
003  AX       V     C        01:00:06:00 01:00:09:00 01:00:06:00 01:00:09:00

"#;
        let validator = RoundtripValidator::default();
        let report = validator
            .validate(edl_text)
            .expect("validation should succeed");
        assert!(report.is_lossless(), "diffs: {:?}", report.diffs);
    }
}