oximedia-subtitle 0.1.1

Subtitle and closed caption rendering 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
//! Subtitle validation rules and reporting.
//!
//! Provides configurable rule-based validation of subtitle entries, producing
//! structured violation reports suitable for QC workflows.

#![allow(dead_code)]

/// A subtitle validation rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ValidationRule {
    /// Subtitle duration must be at least N milliseconds.
    MinDuration(u32),
    /// Subtitle duration must be no more than N milliseconds.
    MaxDuration(u32),
    /// Gap between consecutive subtitles must be at least N milliseconds.
    MinGap(u32),
    /// Text must not exceed N characters per line.
    MaxCharsPerLine(usize),
    /// Text must not have more than N lines.
    MaxLines(usize),
    /// Start time must not be negative.
    NonNegativeStart,
    /// End time must be greater than start time.
    EndAfterStart,
}

impl ValidationRule {
    /// Return a human-readable name for this rule.
    pub fn rule_name(&self) -> &'static str {
        match self {
            ValidationRule::MinDuration(_) => "min_duration",
            ValidationRule::MaxDuration(_) => "max_duration",
            ValidationRule::MinGap(_) => "min_gap",
            ValidationRule::MaxCharsPerLine(_) => "max_chars_per_line",
            ValidationRule::MaxLines(_) => "max_lines",
            ValidationRule::NonNegativeStart => "non_negative_start",
            ValidationRule::EndAfterStart => "end_after_start",
        }
    }
}

/// A subtitle validation violation.
#[derive(Debug, Clone)]
pub struct SubtitleViolation {
    /// 0-based index of the offending subtitle.
    pub entry_index: usize,
    /// The rule that was violated.
    pub rule: ValidationRule,
    /// Human-readable description.
    pub message: String,
}

impl SubtitleViolation {
    /// Create a new violation.
    pub fn new(entry_index: usize, rule: ValidationRule, message: impl Into<String>) -> Self {
        Self {
            entry_index,
            rule,
            message: message.into(),
        }
    }

    /// Returns `true` if this violation is a timing-related error.
    pub fn is_timing_error(&self) -> bool {
        matches!(
            self.rule,
            ValidationRule::MinDuration(_)
                | ValidationRule::MaxDuration(_)
                | ValidationRule::MinGap(_)
                | ValidationRule::NonNegativeStart
                | ValidationRule::EndAfterStart
        )
    }
}

/// A subtitle entry used as input to the validator.
#[derive(Debug, Clone)]
pub struct ValidatorEntry {
    /// Start time in milliseconds.
    pub start_ms: i64,
    /// End time in milliseconds.
    pub end_ms: i64,
    /// Text content (may be multi-line).
    pub text: String,
}

impl ValidatorEntry {
    /// Create a new `ValidatorEntry`.
    pub fn new(start_ms: i64, end_ms: i64, text: impl Into<String>) -> Self {
        Self {
            start_ms,
            end_ms,
            text: text.into(),
        }
    }

    /// Return the duration in milliseconds.
    pub fn duration_ms(&self) -> i64 {
        self.end_ms - self.start_ms
    }

    /// Return the maximum line length in the text.
    pub fn max_line_length(&self) -> usize {
        self.text.lines().map(|l| l.len()).max().unwrap_or(0)
    }

    /// Return the number of lines in the text.
    pub fn line_count(&self) -> usize {
        if self.text.is_empty() {
            0
        } else {
            self.text.lines().count()
        }
    }
}

/// Validates a sequence of subtitle entries against a set of rules.
#[derive(Debug)]
pub struct SubtitleValidator {
    rules: Vec<ValidationRule>,
}

impl SubtitleValidator {
    /// Create a new validator with the given rules.
    pub fn new(rules: Vec<ValidationRule>) -> Self {
        Self { rules }
    }

    /// Create a validator with sensible broadcast defaults.
    pub fn broadcast_defaults() -> Self {
        Self::new(vec![
            ValidationRule::NonNegativeStart,
            ValidationRule::EndAfterStart,
            ValidationRule::MinDuration(500),
            ValidationRule::MaxDuration(8000),
            ValidationRule::MaxCharsPerLine(42),
            ValidationRule::MaxLines(2),
            ValidationRule::MinGap(40),
        ])
    }

    /// Validate a slice of entries and return all violations.
    pub fn validate(&self, entries: &[ValidatorEntry]) -> SubtitleReport {
        let mut violations = Vec::new();

        for (idx, entry) in entries.iter().enumerate() {
            for rule in &self.rules {
                if let Some(v) = self.check_rule(idx, entry, rule) {
                    violations.push(v);
                }
            }
            // Gap check requires the previous entry
            if idx > 0 {
                for rule in &self.rules {
                    if let ValidationRule::MinGap(min_ms) = *rule {
                        let prev = &entries[idx - 1];
                        let gap = entry.start_ms - prev.end_ms;
                        if gap < i64::from(min_ms) {
                            violations.push(SubtitleViolation::new(
                                idx,
                                *rule,
                                format!(
                                    "Gap {}ms between entries {} and {} is less than minimum {}ms",
                                    gap,
                                    idx - 1,
                                    idx,
                                    min_ms
                                ),
                            ));
                        }
                    }
                }
            }
        }

        SubtitleReport { violations }
    }

    /// Check a single rule against a single entry.  Returns a violation or `None`.
    fn check_rule(
        &self,
        idx: usize,
        entry: &ValidatorEntry,
        rule: &ValidationRule,
    ) -> Option<SubtitleViolation> {
        match *rule {
            ValidationRule::NonNegativeStart => {
                if entry.start_ms < 0 {
                    Some(SubtitleViolation::new(
                        idx,
                        *rule,
                        format!("Entry {} has negative start time {}ms", idx, entry.start_ms),
                    ))
                } else {
                    None
                }
            }
            ValidationRule::EndAfterStart => {
                if entry.end_ms <= entry.start_ms {
                    Some(SubtitleViolation::new(
                        idx,
                        *rule,
                        format!(
                            "Entry {} end {}ms is not after start {}ms",
                            idx, entry.end_ms, entry.start_ms
                        ),
                    ))
                } else {
                    None
                }
            }
            ValidationRule::MinDuration(min_ms) => {
                let dur = entry.duration_ms();
                if dur < i64::from(min_ms) {
                    Some(SubtitleViolation::new(
                        idx,
                        *rule,
                        format!(
                            "Entry {} duration {}ms is less than minimum {}ms",
                            idx, dur, min_ms
                        ),
                    ))
                } else {
                    None
                }
            }
            ValidationRule::MaxDuration(max_ms) => {
                let dur = entry.duration_ms();
                if dur > i64::from(max_ms) {
                    Some(SubtitleViolation::new(
                        idx,
                        *rule,
                        format!(
                            "Entry {} duration {}ms exceeds maximum {}ms",
                            idx, dur, max_ms
                        ),
                    ))
                } else {
                    None
                }
            }
            ValidationRule::MaxCharsPerLine(max_chars) => {
                let longest = entry.max_line_length();
                if longest > max_chars {
                    Some(SubtitleViolation::new(
                        idx,
                        *rule,
                        format!(
                            "Entry {} has a line with {} characters (max {})",
                            idx, longest, max_chars
                        ),
                    ))
                } else {
                    None
                }
            }
            ValidationRule::MaxLines(max_lines) => {
                let count = entry.line_count();
                if count > max_lines {
                    Some(SubtitleViolation::new(
                        idx,
                        *rule,
                        format!("Entry {} has {} lines (max {})", idx, count, max_lines),
                    ))
                } else {
                    None
                }
            }
            // MinGap is handled in the outer loop
            ValidationRule::MinGap(_) => None,
        }
    }
}

/// A complete validation report for a subtitle file.
#[derive(Debug)]
pub struct SubtitleReport {
    /// All violations found during validation.
    pub violations: Vec<SubtitleViolation>,
}

impl SubtitleReport {
    /// Return the total number of violations.
    pub fn violation_count(&self) -> usize {
        self.violations.len()
    }

    /// Return the number of timing-related errors.
    pub fn error_count(&self) -> usize {
        self.violations
            .iter()
            .filter(|v| v.is_timing_error())
            .count()
    }

    /// Return `true` if there are no violations.
    pub fn is_clean(&self) -> bool {
        self.violations.is_empty()
    }

    /// Collect violations grouped by rule name.
    pub fn by_rule(&self) -> std::collections::HashMap<&'static str, Vec<&SubtitleViolation>> {
        let mut map: std::collections::HashMap<&'static str, Vec<&SubtitleViolation>> =
            std::collections::HashMap::new();
        for v in &self.violations {
            map.entry(v.rule.rule_name()).or_default().push(v);
        }
        map
    }
}

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

    fn entry(start: i64, end: i64, text: &str) -> ValidatorEntry {
        ValidatorEntry::new(start, end, text)
    }

    #[test]
    fn test_validation_rule_name() {
        assert_eq!(ValidationRule::MinDuration(500).rule_name(), "min_duration");
        assert_eq!(
            ValidationRule::MaxDuration(8000).rule_name(),
            "max_duration"
        );
        assert_eq!(ValidationRule::MinGap(40).rule_name(), "min_gap");
        assert_eq!(
            ValidationRule::MaxCharsPerLine(42).rule_name(),
            "max_chars_per_line"
        );
        assert_eq!(ValidationRule::MaxLines(2).rule_name(), "max_lines");
        assert_eq!(
            ValidationRule::NonNegativeStart.rule_name(),
            "non_negative_start"
        );
        assert_eq!(ValidationRule::EndAfterStart.rule_name(), "end_after_start");
    }

    #[test]
    fn test_subtitle_violation_is_timing_error_true() {
        let v = SubtitleViolation::new(0, ValidationRule::EndAfterStart, "err");
        assert!(v.is_timing_error());
    }

    #[test]
    fn test_subtitle_violation_is_timing_error_false() {
        let v = SubtitleViolation::new(0, ValidationRule::MaxCharsPerLine(42), "err");
        assert!(!v.is_timing_error());
    }

    #[test]
    fn test_validator_entry_duration_ms() {
        let e = entry(1000, 4500, "Hello");
        assert_eq!(e.duration_ms(), 3500);
    }

    #[test]
    fn test_validator_entry_max_line_length() {
        let e = entry(0, 1000, "Short\nA very long line indeed");
        assert_eq!(e.max_line_length(), 23);
    }

    #[test]
    fn test_validator_entry_line_count() {
        let e = entry(0, 1000, "Line one\nLine two");
        assert_eq!(e.line_count(), 2);
    }

    #[test]
    fn test_validator_entry_empty_text_line_count() {
        let e = entry(0, 1000, "");
        assert_eq!(e.line_count(), 0);
    }

    #[test]
    fn test_validate_clean_entries() {
        let validator = SubtitleValidator::broadcast_defaults();
        let entries = vec![
            entry(0, 2000, "Hello world"),
            entry(3000, 5000, "Second line"),
        ];
        let report = validator.validate(&entries);
        assert!(
            report.is_clean(),
            "Expected no violations: {:?}",
            report.violations
        );
    }

    #[test]
    fn test_validate_end_before_start() {
        let validator = SubtitleValidator::new(vec![ValidationRule::EndAfterStart]);
        let entries = vec![entry(5000, 3000, "Bad timing")];
        let report = validator.validate(&entries);
        assert_eq!(report.violation_count(), 1);
        assert!(report.violations[0].is_timing_error());
    }

    #[test]
    fn test_validate_negative_start() {
        let validator = SubtitleValidator::new(vec![ValidationRule::NonNegativeStart]);
        let entries = vec![entry(-100, 1000, "Negative")];
        let report = validator.validate(&entries);
        assert_eq!(report.violation_count(), 1);
    }

    #[test]
    fn test_validate_min_duration() {
        let validator = SubtitleValidator::new(vec![
            ValidationRule::EndAfterStart,
            ValidationRule::MinDuration(1000),
        ]);
        let entries = vec![entry(0, 200, "Too short")];
        let report = validator.validate(&entries);
        assert_eq!(report.error_count(), 1);
    }

    #[test]
    fn test_validate_max_duration() {
        let validator = SubtitleValidator::new(vec![ValidationRule::MaxDuration(3000)]);
        let entries = vec![entry(0, 10000, "Too long")];
        let report = validator.validate(&entries);
        assert_eq!(report.violation_count(), 1);
    }

    #[test]
    fn test_validate_max_chars_per_line() {
        let validator = SubtitleValidator::new(vec![ValidationRule::MaxCharsPerLine(10)]);
        let entries = vec![entry(0, 2000, "This line is too long for the rule")];
        let report = validator.validate(&entries);
        assert_eq!(report.violation_count(), 1);
        assert!(!report.violations[0].is_timing_error());
    }

    #[test]
    fn test_validate_max_lines() {
        let validator = SubtitleValidator::new(vec![ValidationRule::MaxLines(2)]);
        let entries = vec![entry(0, 2000, "Line 1\nLine 2\nLine 3")];
        let report = validator.validate(&entries);
        assert_eq!(report.violation_count(), 1);
    }

    #[test]
    fn test_validate_min_gap() {
        let validator = SubtitleValidator::new(vec![ValidationRule::MinGap(500)]);
        let entries = vec![
            entry(0, 2000, "A"),
            entry(2100, 4000, "B"), // only 100ms gap
        ];
        let report = validator.validate(&entries);
        assert_eq!(report.violation_count(), 1);
    }

    #[test]
    fn test_report_error_count() {
        let validator = SubtitleValidator::new(vec![
            ValidationRule::EndAfterStart,
            ValidationRule::MaxCharsPerLine(5),
        ]);
        let entries = vec![entry(5000, 3000, "Too many chars here")];
        let report = validator.validate(&entries);
        // EndAfterStart is timing, MaxCharsPerLine is not
        assert_eq!(report.error_count(), 1);
        assert_eq!(report.violation_count(), 2);
    }

    #[test]
    fn test_report_by_rule() {
        let validator = SubtitleValidator::new(vec![
            ValidationRule::MaxCharsPerLine(5),
            ValidationRule::MaxLines(1),
        ]);
        let entries = vec![entry(0, 2000, "Line 1 is very long\nLine 2")];
        let report = validator.validate(&entries);
        let by_rule = report.by_rule();
        assert!(by_rule.contains_key("max_chars_per_line"));
        assert!(by_rule.contains_key("max_lines"));
    }
}