oximedia-caption-gen 0.1.2

Advanced caption and subtitle generation — speech alignment, line breaking, WCAG compliance, and speaker diarization 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
//! Caption format adapter: serialize [`CaptionBlock`] tracks to SRT, WebVTT,
//! and TTML output strings.
//!
//! ## Supported formats
//!
//! | Format | Standard       | Extension |
//! |--------|----------------|-----------|
//! | SRT    | SubRip Text    | `.srt`    |
//! | VTT    | WebVTT (W3C)   | `.vtt`    |
//! | TTML   | Timed Text ML  | `.ttml`   |
//!
//! ## Usage
//!
//! ```rust
//! use oximedia_caption_gen::caption_format_adapter::{CaptionFormatAdapter, OutputFormat};
//! use oximedia_caption_gen::{CaptionBlock, CaptionPosition};
//!
//! let block = CaptionBlock {
//!     id: 1,
//!     start_ms: 0,
//!     end_ms: 2000,
//!     lines: vec!["Hello world".to_string()],
//!     speaker_id: None,
//!     position: CaptionPosition::Bottom,
//! };
//! let srt = CaptionFormatAdapter::convert(&[block], OutputFormat::Srt).unwrap();
//! assert!(srt.contains("00:00:00,000 --> 00:00:02,000"));
//! ```

use crate::alignment::CaptionBlock;

/// Error type for format adaptation failures.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum FormatAdapterError {
    /// The block list is empty and the format requires at least one entry.
    #[error("caption track is empty")]
    EmptyTrack,

    /// A timestamp value is invalid (start_ms >= end_ms).
    #[error("block {block_id}: invalid timestamp (start_ms={start_ms} >= end_ms={end_ms})")]
    InvalidTimestamp {
        block_id: u32,
        start_ms: u64,
        end_ms: u64,
    },
}

/// Target output format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// SubRip Text (`.srt`).
    Srt,
    /// Web Video Text Tracks (`.vtt`).
    Vtt,
    /// Timed Text Markup Language (`.ttml`).
    Ttml,
}

/// Converts a caption track (slice of [`CaptionBlock`]) to various text-based
/// subtitle formats.
pub struct CaptionFormatAdapter;

impl CaptionFormatAdapter {
    /// Convert `blocks` to the requested `format`.
    ///
    /// # Errors
    /// Returns [`FormatAdapterError`] if any block has an invalid timestamp.
    pub fn convert(
        blocks: &[CaptionBlock],
        format: OutputFormat,
    ) -> Result<String, FormatAdapterError> {
        // Validate timestamps first.
        for block in blocks {
            if block.start_ms >= block.end_ms && !(block.start_ms == 0 && block.end_ms == 0) {
                return Err(FormatAdapterError::InvalidTimestamp {
                    block_id: block.id,
                    start_ms: block.start_ms,
                    end_ms: block.end_ms,
                });
            }
        }

        match format {
            OutputFormat::Srt => Ok(Self::to_srt(blocks)),
            OutputFormat::Vtt => Ok(Self::to_vtt(blocks)),
            OutputFormat::Ttml => Ok(Self::to_ttml(blocks)),
        }
    }

    // ─── SRT ──────────────────────────────────────────────────────────────────

    fn to_srt(blocks: &[CaptionBlock]) -> String {
        let mut out = String::new();
        for block in blocks {
            out.push_str(&block.id.to_string());
            out.push('\n');
            out.push_str(&format_srt_timestamp(block.start_ms));
            out.push_str(" --> ");
            out.push_str(&format_srt_timestamp(block.end_ms));
            out.push('\n');
            for line in &block.lines {
                out.push_str(line);
                out.push('\n');
            }
            out.push('\n');
        }
        out
    }

    // ─── VTT ──────────────────────────────────────────────────────────────────

    fn to_vtt(blocks: &[CaptionBlock]) -> String {
        let mut out = String::from("WEBVTT\n\n");
        for block in blocks {
            // VTT cue identifier (optional but helpful).
            out.push_str(&format!("cue-{}\n", block.id));
            out.push_str(&format_vtt_timestamp(block.start_ms));
            out.push_str(" --> ");
            out.push_str(&format_vtt_timestamp(block.end_ms));
            // Append position cue settings if not bottom-default.
            let pos_setting = vtt_position_setting(&block.position);
            if !pos_setting.is_empty() {
                out.push(' ');
                out.push_str(&pos_setting);
            }
            out.push('\n');
            for line in &block.lines {
                out.push_str(line);
                out.push('\n');
            }
            out.push('\n');
        }
        out
    }

    // ─── TTML ─────────────────────────────────────────────────────────────────

    fn to_ttml(blocks: &[CaptionBlock]) -> String {
        let mut out = String::new();
        out.push_str(concat!(
            r#"<?xml version="1.0" encoding="UTF-8"?>"#,
            "\n",
            r#"<tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en">"#,
            "\n",
            "  <body>\n",
            "    <div>\n"
        ));

        for block in blocks {
            let begin = format_ttml_timestamp(block.start_ms);
            let end = format_ttml_timestamp(block.end_ms);
            out.push_str(&format!(
                "      <p begin=\"{}\" end=\"{}\" xml:id=\"s{}\">\n",
                begin, end, block.id
            ));
            for (i, line) in block.lines.iter().enumerate() {
                // Escape XML special characters.
                let escaped = xml_escape(line);
                if i + 1 < block.lines.len() {
                    out.push_str(&format!("        {}<br/>\n", escaped));
                } else {
                    out.push_str(&format!("        {}\n", escaped));
                }
            }
            out.push_str("      </p>\n");
        }

        out.push_str("    </div>\n");
        out.push_str("  </body>\n");
        out.push_str("</tt>\n");
        out
    }
}

// ─── Timestamp formatting helpers ─────────────────────────────────────────────

/// Format milliseconds as `HH:MM:SS,mmm` (SRT format).
fn format_srt_timestamp(ms: u64) -> String {
    let hours = ms / 3_600_000;
    let minutes = (ms % 3_600_000) / 60_000;
    let seconds = (ms % 60_000) / 1_000;
    let millis = ms % 1_000;
    format!("{:02}:{:02}:{:02},{:03}", hours, minutes, seconds, millis)
}

/// Format milliseconds as `HH:MM:SS.mmm` (VTT format).
fn format_vtt_timestamp(ms: u64) -> String {
    let hours = ms / 3_600_000;
    let minutes = (ms % 3_600_000) / 60_000;
    let seconds = (ms % 60_000) / 1_000;
    let millis = ms % 1_000;
    format!("{:02}:{:02}:{:02}.{:03}", hours, minutes, seconds, millis)
}

/// Format milliseconds as `HH:MM:SS.mmm` (TTML uses the same dot separator as VTT).
fn format_ttml_timestamp(ms: u64) -> String {
    format_vtt_timestamp(ms)
}

/// Generate VTT cue position settings for non-default caption positions.
fn vtt_position_setting(position: &crate::alignment::CaptionPosition) -> String {
    use crate::alignment::CaptionPosition;
    match position {
        CaptionPosition::Bottom => String::new(),
        CaptionPosition::Top => "line:10%".to_string(),
        CaptionPosition::Custom(x, y) => {
            format!("position:{:.0}% line:{:.0}%", x, y)
        }
    }
}

/// Escape XML special characters in a text string.
fn xml_escape(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 8);
    for ch in text.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            other => out.push(other),
        }
    }
    out
}

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

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

    fn make_block(id: u32, start_ms: u64, end_ms: u64, text: &str) -> CaptionBlock {
        CaptionBlock {
            id,
            start_ms,
            end_ms,
            lines: vec![text.to_string()],
            speaker_id: None,
            position: CaptionPosition::Bottom,
        }
    }

    fn make_two_line_block(id: u32, start_ms: u64, end_ms: u64) -> CaptionBlock {
        CaptionBlock {
            id,
            start_ms,
            end_ms,
            lines: vec!["Line one".to_string(), "Line two".to_string()],
            speaker_id: None,
            position: CaptionPosition::Bottom,
        }
    }

    // ─── timestamp helpers ────────────────────────────────────────────────────

    #[test]
    fn srt_timestamp_zero() {
        assert_eq!(format_srt_timestamp(0), "00:00:00,000");
    }

    #[test]
    fn srt_timestamp_one_hour() {
        assert_eq!(format_srt_timestamp(3_600_000), "01:00:00,000");
    }

    #[test]
    fn srt_timestamp_mixed() {
        // 1h 2m 3s 456ms
        let ms = 3_600_000 + 2 * 60_000 + 3_000 + 456;
        assert_eq!(format_srt_timestamp(ms), "01:02:03,456");
    }

    #[test]
    fn vtt_timestamp_uses_dot_separator() {
        assert_eq!(format_vtt_timestamp(0), "00:00:00.000");
    }

    #[test]
    fn vtt_timestamp_mixed() {
        let ms = 3_600_000 + 2 * 60_000 + 3_000 + 456;
        assert_eq!(format_vtt_timestamp(ms), "01:02:03.456");
    }

    // ─── SRT output ───────────────────────────────────────────────────────────

    #[test]
    fn srt_single_block() {
        let block = make_block(1, 0, 2000, "Hello world");
        let srt = CaptionFormatAdapter::convert(&[block], OutputFormat::Srt).expect("convert should succeed");
        assert!(srt.contains("1\n"));
        assert!(srt.contains("00:00:00,000 --> 00:00:02,000"));
        assert!(srt.contains("Hello world"));
    }

    #[test]
    fn srt_multiple_blocks() {
        let blocks = vec![
            make_block(1, 0, 2000, "Block one"),
            make_block(2, 2500, 4000, "Block two"),
        ];
        let srt = CaptionFormatAdapter::convert(&blocks, OutputFormat::Srt).expect("convert should succeed");
        assert!(srt.contains("Block one"));
        assert!(srt.contains("Block two"));
        assert!(srt.contains("2\n"));
    }

    #[test]
    fn srt_two_line_block_emits_two_lines() {
        let block = make_two_line_block(1, 0, 2000);
        let srt = CaptionFormatAdapter::convert(&[block], OutputFormat::Srt).expect("convert should succeed");
        assert!(srt.contains("Line one\n"));
        assert!(srt.contains("Line two\n"));
    }

    #[test]
    fn srt_blocks_separated_by_blank_line() {
        let blocks = vec![make_block(1, 0, 1000, "A"), make_block(2, 1500, 2500, "B")];
        let srt = CaptionFormatAdapter::convert(&blocks, OutputFormat::Srt).expect("convert should succeed");
        // Each block ends with double newline.
        assert!(srt.contains("A\n\n"));
        assert!(srt.contains("B\n\n"));
    }

    #[test]
    fn srt_empty_track_produces_empty_string() {
        let srt = CaptionFormatAdapter::convert(&[], OutputFormat::Srt).expect("convert should succeed");
        assert!(srt.is_empty());
    }

    // ─── VTT output ───────────────────────────────────────────────────────────

    #[test]
    fn vtt_starts_with_webvtt_header() {
        let block = make_block(1, 0, 2000, "Hello");
        let vtt = CaptionFormatAdapter::convert(&[block], OutputFormat::Vtt).expect("convert should succeed");
        assert!(vtt.starts_with("WEBVTT\n"));
    }

    #[test]
    fn vtt_uses_dot_separator_in_timestamps() {
        let block = make_block(1, 0, 2000, "Hello");
        let vtt = CaptionFormatAdapter::convert(&[block], OutputFormat::Vtt).expect("convert should succeed");
        assert!(vtt.contains("00:00:00.000 --> 00:00:02.000"));
    }

    #[test]
    fn vtt_cue_identifier_present() {
        let block = make_block(3, 0, 1000, "Test");
        let vtt = CaptionFormatAdapter::convert(&[block], OutputFormat::Vtt).expect("convert should succeed");
        assert!(vtt.contains("cue-3"));
    }

    #[test]
    fn vtt_top_position_adds_line_cue_setting() {
        let block = CaptionBlock {
            id: 1,
            start_ms: 0,
            end_ms: 1000,
            lines: vec!["Top caption".to_string()],
            speaker_id: None,
            position: CaptionPosition::Top,
        };
        let vtt = CaptionFormatAdapter::convert(&[block], OutputFormat::Vtt).expect("convert should succeed");
        assert!(vtt.contains("line:10%"));
    }

    #[test]
    fn vtt_bottom_position_no_cue_setting() {
        let block = make_block(1, 0, 1000, "Bottom");
        let vtt = CaptionFormatAdapter::convert(&[block], OutputFormat::Vtt).expect("convert should succeed");
        // No extra position setting on the timestamp line.
        let ts_line = vtt.lines().find(|l| l.contains("-->")).unwrap_or_default();
        assert!(!ts_line.contains("line:"));
    }

    // ─── TTML output ──────────────────────────────────────────────────────────

    #[test]
    fn ttml_has_xml_declaration() {
        let block = make_block(1, 0, 1000, "Hello");
        let ttml = CaptionFormatAdapter::convert(&[block], OutputFormat::Ttml).expect("convert should succeed");
        assert!(ttml.contains(r#"<?xml version="1.0""#));
    }

    #[test]
    fn ttml_has_tt_element() {
        let block = make_block(1, 0, 1000, "Hello");
        let ttml = CaptionFormatAdapter::convert(&[block], OutputFormat::Ttml).expect("convert should succeed");
        assert!(ttml.contains("<tt "));
        assert!(ttml.contains("</tt>"));
    }

    #[test]
    fn ttml_has_p_element_with_timestamps() {
        let block = make_block(1, 0, 2000, "Hello world");
        let ttml = CaptionFormatAdapter::convert(&[block], OutputFormat::Ttml).expect("convert should succeed");
        assert!(ttml.contains(r#"begin="00:00:00.000""#));
        assert!(ttml.contains(r#"end="00:00:02.000""#));
    }

    #[test]
    fn ttml_multi_line_uses_br_element() {
        let block = make_two_line_block(1, 0, 2000);
        let ttml = CaptionFormatAdapter::convert(&[block], OutputFormat::Ttml).expect("convert should succeed");
        assert!(ttml.contains("<br/>"));
    }

    #[test]
    fn ttml_escapes_xml_special_chars() {
        let block = make_block(1, 0, 2000, "A & B <test>");
        let ttml = CaptionFormatAdapter::convert(&[block], OutputFormat::Ttml).expect("convert should succeed");
        assert!(ttml.contains("A &amp; B &lt;test&gt;"));
    }

    // ─── Error handling ───────────────────────────────────────────────────────

    #[test]
    fn invalid_timestamp_returns_error() {
        let block = CaptionBlock {
            id: 1,
            start_ms: 5000,
            end_ms: 1000, // end < start → invalid
            lines: vec!["bad".to_string()],
            speaker_id: None,
            position: CaptionPosition::Bottom,
        };
        let result = CaptionFormatAdapter::convert(&[block], OutputFormat::Srt);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            FormatAdapterError::InvalidTimestamp { .. }
        ));
    }

    // ─── xml_escape ───────────────────────────────────────────────────────────

    #[test]
    fn xml_escape_all_specials() {
        let result = xml_escape("&<>\"'");
        assert_eq!(result, "&amp;&lt;&gt;&quot;&apos;");
    }

    #[test]
    fn xml_escape_plain_text_unchanged() {
        assert_eq!(xml_escape("Hello world"), "Hello world");
    }
}