ttml_processor 0.3.3

A Rust library for parsing and generating TTML lyrics files, specifically designed for Apple Music and AMLL formats.
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
//! 用于解析 `<iTunesMetadata>` 中的翻译或音译内容的模块

use quick_xml::{
    Reader,
    events::Event,
};

use crate::{
    constants::{
        attrs,
        tags,
        vals,
    },
    error::{
        ParseErrorKind,
        Result,
        ResultExt as _,
        TTMLProcessorError,
    },
    model::{
        SubLyricContent,
        Syllable,
    },
    parser::{
        ext::{
            BytesStartExt as _,
            QNameExt as _,
            ReaderExt as _,
        },
        state::ParserContext,
        utils::{
            build_full_text,
            is_spacing_text,
            mark_slice_last_space,
            normalize_words_spaces,
            parse_basic_syllable,
            resolve_xml_entity,
        },
    },
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubLyricType {
    Translation,
    Transliteration,
}

/// 解析 `<iTunesMetadata>` 中的翻译或音译内容
///
/// ## 示例
/// ```xml
/// <translations>
///     <translation type="subtitle" xml:lang="zh-Hans">
///         ...
///     </translation>
/// </translations>
/// ```
///
/// ```xml
/// <translations>
///     <translation type="replacement" xml:lang="zh-Hans">
///         ...
///     </translation>
/// </translations>
/// ```
///
/// ```xml
/// <transliterations>
///     <transliteration xml:lang="zh-Latn-pinyin">
///         ...
///     </transliteration>
/// </transliterations>
/// ```
pub fn parse_sub_lyrics(
    reader: &mut Reader<&[u8]>,
    context: &mut ParserContext,
    group_tag: &str,
    item_tag: &str,
    sub_type: SubLyricType,
) -> Result<()> {
    let mut buf = Vec::new();
    loop {
        match reader.read_event_with_context(&mut buf, context)? {
            Event::Start(ref e) => {
                let qname = e.name();
                let tag_name =
                    std::str::from_utf8(qname.as_ref()).map_err(TTMLProcessorError::Utf8Error)?;

                context.tag_stack.push(tag_name.to_string());

                if qname.is(item_tag) {
                    let lang = e.get_attr_value(attrs::XML_LANG, reader, context)?;
                    parse_sub_lyric_block(reader, context, item_tag, lang.as_ref(), sub_type)?;
                    context.tag_stack.pop();
                }
            }
            Event::End(ref e) => {
                if e.name().is(group_tag) {
                    break;
                }
                context.tag_stack.pop();
            }
            Event::Eof => return Err(ParseErrorKind::UnexpectedEof).with_context(reader, context),
            _ => (),
        }
        buf.clear();
    }
    Ok(())
}

/// 解析一个 `<text>` 标签
///
/// ## 示例
/// ```xml
/// <text for="L20">...</text>
/// ```
fn parse_sub_lyric_block(
    reader: &mut Reader<&[u8]>,
    context: &mut ParserContext,
    item_tag: &str,
    lang: Option<&String>,
    sub_type: SubLyricType,
) -> Result<()> {
    let mut buf = Vec::new();
    loop {
        match reader.read_event_with_context(&mut buf, context)? {
            Event::Start(ref e) => {
                let qname = e.name();
                let tag_name =
                    std::str::from_utf8(qname.as_ref()).map_err(TTMLProcessorError::Utf8Error)?;

                context.tag_stack.push(tag_name.to_string());

                if qname.is(tags::TEXT) {
                    let line_id = e.get_required_attr(attrs::FOR, reader, context)?;
                    parse_sub_lyric_text(reader, context, line_id, lang, sub_type)?;
                    context.tag_stack.pop();
                }
            }
            Event::End(ref e) => {
                if e.name().is(item_tag) {
                    break;
                }
                context.tag_stack.pop();
            }
            Event::Eof => return Err(ParseErrorKind::UnexpectedEof).with_context(reader, context),
            _ => (),
        }
        buf.clear();
    }
    Ok(())
}

/// 解析 `<text>` 标签中的内容
///
/// ## 示例
/// ```xml
/// <text for="L21">
///     没错 他潜入你梦境 乐见你尖叫
///     <span xmlns:ttm="http://www.w3.org/ns/ttml#metadata" ttm:role="x-bg" xmlns="http://www.w3.org/ns/ttml">
///         (嘿)
///     </span>
/// </text>
/// ```
///
/// ```xml
/// <text for="L1">
///     <span begin="27.549" end="28.088">窗</span>
///     <span begin="28.088" end="29.033">外</span>
///     <span begin="29.033" end="29.350">的</span>
///     <span begin="29.350" end="29.647">麻</span>
///     <span begin="29.647" end="30.419">雀</span>
///     <span begin="31.009" end="31.512">在</span>
///     <span begin="31.512" end="32.712">电线杆</span>
///     <span begin="32.712" end="33.023">上</span>
///     <span begin="33.023" end="33.291">多</span>
///     <span begin="33.291" end="33.956">嘴</span>
/// </text>
/// ```
///
/// ```xml
/// <text for="L10">
///     <span begin="54.500" end="55.060">rèn</span>
///     <span begin="55.060" end="55.400">yán</span>
///     <span begin="55.400" end="56.550">yǔ</span>
///     <span begin="57.310" end="57.560">huǎn</span>
///     <span begin="57.560" end="57.910">huǎn</span>
///     <span begin="57.910" end="58.580">rù</span>
///     <span begin="58.580" end="59.580">mián</span>
///     <span ttm:role="x-bg">
///         <span begin="58.560" end="58.890">(huǎn</span>
///         <span begin="58.890" end="59.110">huǎn</span>
///         <span begin="59.110" end="59.490">rù</span>
///         <span begin="59.490" end="1:00.440">mián)</span>
///     </span>
/// </text>
/// ```
fn parse_sub_lyric_text(
    reader: &mut Reader<&[u8]>,
    context: &mut ParserContext,
    line_id: String,
    lang: Option<&String>,
    sub_type: SubLyricType,
) -> Result<()> {
    context.current_line_id = Some(line_id.clone());

    let mut main_words: Vec<Syllable> = Vec::new();
    let mut bg_words: Vec<Syllable> = Vec::new();

    let mut raw_main_text = String::new();
    let mut raw_bg_text = String::new();

    let mut in_bg_span = false;
    let mut buf = Vec::new();

    loop {
        match reader.read_event_with_context(&mut buf, context)? {
            Event::Start(ref e) => {
                let qname = e.name();
                let tag_name =
                    std::str::from_utf8(qname.as_ref()).map_err(TTMLProcessorError::Utf8Error)?;

                context.tag_stack.push(tag_name.to_string());

                if qname.is(tags::SPAN) {
                    let mut is_current_bg = false;
                    for attr_res in e.attributes().flatten() {
                        if attr_res.key.as_ref() == attrs::b::TTM_ROLE {
                            is_current_bg = attr_res.value.as_ref() == vals::b::ROLE_BG;
                            break;
                        }
                    }

                    if is_current_bg {
                        in_bg_span = true;
                    } else {
                        let syllable = parse_basic_syllable(reader, context, e)?;

                        if in_bg_span {
                            bg_words.push(syllable);
                        } else {
                            main_words.push(syllable);
                        }
                        context.tag_stack.pop();
                    }
                }
            }
            Event::End(ref e) => {
                if e.name().is(tags::SPAN) {
                    in_bg_span = false;
                    context.tag_stack.pop();
                } else if e.name().is(tags::TEXT) {
                    break;
                } else {
                    context.tag_stack.pop();
                }
            }
            Event::Text(e) => {
                let text_str =
                    std::str::from_utf8(e.as_ref()).map_err(TTMLProcessorError::Utf8Error)?;
                if is_spacing_text(text_str) {
                    let target_words = if in_bg_span {
                        &mut bg_words
                    } else {
                        &mut main_words
                    };
                    mark_slice_last_space(target_words);
                }

                if in_bg_span {
                    raw_bg_text.push_str(text_str);
                } else {
                    raw_main_text.push_str(text_str);
                }
            }
            Event::GeneralRef(reference) => {
                let ch_str = resolve_xml_entity(&reference).with_context(reader, context)?;
                if in_bg_span {
                    raw_bg_text.push_str(&ch_str);
                } else {
                    raw_main_text.push_str(&ch_str);
                }
            }
            Event::Eof => return Err(ParseErrorKind::UnexpectedEof).with_context(reader, context),
            _ => (),
        }
        buf.clear();
    }

    context.current_line_id = None;

    // 移除部分歌词可能出现的尾随空格
    if let Some(last) = main_words.last_mut() {
        last.ends_with_space = None;
    }
    if let Some(last) = bg_words.last_mut() {
        last.ends_with_space = None;
    }

    let build_content = |mut words: Vec<Syllable>, raw_text: String| -> Option<SubLyricContent> {
        if words.is_empty() {
            let text = raw_text.trim().to_string();
            if text.is_empty() {
                None
            } else {
                Some(SubLyricContent {
                    language: lang.cloned(),
                    text,
                    words: None,
                })
            }
        } else {
            normalize_words_spaces(&mut words);
            let text = build_full_text(&words, false);
            Some(SubLyricContent {
                language: lang.cloned(),
                text,
                words: Some(words),
            })
        }
    };

    if let Some(main_content) = build_content(main_words, raw_main_text) {
        let map = match sub_type {
            SubLyricType::Translation => &mut context.translations_map,
            SubLyricType::Transliteration => &mut context.romanizations_map,
        };
        map.entry(line_id.clone()).or_default().push(main_content);
    }

    if let Some(bg_content) = build_content(bg_words, raw_bg_text) {
        let bg_map = match sub_type {
            SubLyricType::Translation => &mut context.bg_translations_map,
            SubLyricType::Transliteration => &mut context.bg_romanizations_map,
        };
        bg_map.entry(line_id).or_default().push(bg_content);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use quick_xml::events::Event;

    use super::*;
    use crate::parser::state::ParserContext;

    fn advance_to_start_tag(reader: &mut Reader<&[u8]>, tag_name: &str) {
        let mut buf = Vec::new();
        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(ref e)) if e.name().is(tag_name) => break,
                Ok(Event::Eof) => panic!("Reached EOF before finding tag: {tag_name}"),
                _ => (),
            }
            buf.clear();
        }
    }

    #[test]
    fn test_parse_sub_lyric_text() {
        let xml = r#"
        <text for="L1">
            <span begin="0.000" end="1.000">测</span>
            <span begin="1.000" end="2.000">试</span>
            <span ttm:role="x-bg">
                <span begin="1.000" end="2.000">(背景)</span>
            </span>
        </text>"#;

        let mut reader = Reader::from_str(xml);
        let mut context = ParserContext::default();
        let lang = "zh-Hans".to_string();

        advance_to_start_tag(&mut reader, "text");

        parse_sub_lyric_text(
            &mut reader,
            &mut context,
            "L1".to_string(),
            Some(&lang),
            SubLyricType::Translation,
        )
        .expect("Failed to parse sub lyric text");

        assert!(context.translations_map.contains_key("L1"));
        let main_content = &context.translations_map["L1"][0];
        assert_eq!(main_content.language.as_deref(), Some("zh-Hans"));
        assert_eq!(main_content.text, "测试");
        assert_eq!(main_content.words.as_ref().unwrap().len(), 2);
        assert_eq!(main_content.words.as_ref().unwrap()[0].text, "测");

        assert!(context.bg_translations_map.contains_key("L1"));
        let bg_content = &context.bg_translations_map["L1"][0];
        assert_eq!(bg_content.text, "(背景)");
        assert_eq!(bg_content.words.as_ref().unwrap().len(), 1);
        assert_eq!(bg_content.words.as_ref().unwrap()[0].text, "(背景)");
    }

    #[test]
    fn test_parse_sub_lyric_block() {
        let xml = r#"
        <translation xml:lang="zh-Hans">
            <text for="L10">
                <span begin="0.0" end="1.0">第</span>
                <span begin="1.0" end="2.0">十</span>
                <span begin="2.0" end="3.0">行</span>
            </text>
            <text for="L11">只有纯文本翻译</text>
        </translation>"#;

        let mut reader = Reader::from_str(xml);
        let mut context = ParserContext::default();
        let lang = "zh-Hans".to_string();

        advance_to_start_tag(&mut reader, "translation");

        parse_sub_lyric_block(
            &mut reader,
            &mut context,
            "translation",
            Some(&lang),
            SubLyricType::Translation,
        )
        .expect("Failed to parse sub lyric block");

        assert!(context.translations_map.contains_key("L10"));
        let l10_content = &context.translations_map["L10"][0];
        assert_eq!(l10_content.text, "第十行");
        assert!(l10_content.words.is_some());
        assert_eq!(l10_content.words.as_ref().unwrap().len(), 3);

        assert!(context.translations_map.contains_key("L11"));
        let l11_content = &context.translations_map["L11"][0];
        assert_eq!(l11_content.text, "只有纯文本翻译");
        assert!(l11_content.words.is_none());
    }

    #[test]
    fn test_parse_sub_lyrics() {
        let xml = r#"
        <transliterations>
            <transliteration xml:lang="zh-Latn-pinyin">
                <text for="L1">
                    <span begin="0.0" end="1.0">pīn</span> <span begin="1.0" end="2.0">yīn</span>
                </text>
                <text for="L2">
                    <span begin="1.0" end="2.0">abc</span>
                    <span begin="1.0" end="2.0">def</span>
                </text>
            </transliteration>
        </transliterations>"#;

        let mut reader = Reader::from_str(xml);
        let mut context = ParserContext::default();

        advance_to_start_tag(&mut reader, "transliterations");

        parse_sub_lyrics(
            &mut reader,
            &mut context,
            "transliterations",
            "transliteration",
            SubLyricType::Transliteration,
        )
        .expect("Failed to parse sub lyrics");

        assert!(context.romanizations_map.contains_key("L1"));
        assert!(context.translations_map.is_empty());

        let rom_content1 = &context.romanizations_map["L1"][0];
        assert_eq!(rom_content1.language.as_deref(), Some("zh-Latn-pinyin"));
        assert_eq!(rom_content1.text, "pīn yīn");
        assert_eq!(rom_content1.words.as_ref().unwrap().len(), 2);

        let rom_content2 = &context.romanizations_map["L2"][0];
        assert_eq!(rom_content2.language.as_deref(), Some("zh-Latn-pinyin"));
        assert_eq!(rom_content2.text, "abcdef");
        assert_eq!(rom_content2.words.as_ref().unwrap().len(), 2);
    }
}