ttml_processor 0.3.1

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
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
use quick_xml::{
    Reader,
    events::{
        BytesStart,
        Event,
    },
};

use crate::{
    constants::{
        attrs,
        tags,
    },
    error::{
        ParseErrorKind,
        Result,
        ResultExt as _,
        TTMLProcessorError,
    },
    model::{
        BackgroundVocal,
        LyricLine,
    },
    parser::{
        ext::{
            BytesStartExt as _,
            QNameExt as _,
            ReaderExt as _,
        },
        span::process_span,
        state::ParserContext,
        utils::{
            build_full_text,
            is_spacing_text,
            mark_last_syllable_space,
            normalize_line_text,
            normalize_words_spaces,
            resolve_xml_entity,
            strip_outer_parens,
            strip_outer_parens_from_words,
        },
    },
};

/// 解析 `<body>` 标签,其中包含多个歌词区块
pub fn parse_body(
    reader: &mut Reader<&[u8]>,
    context: &mut ParserContext,
    lines: &mut Vec<LyricLine>,
) -> 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::DIV) {
                    parse_section(reader, e, context, lines)?;
                    context.tag_stack.pop();
                }
            }
            Event::End(ref e) => {
                if e.name().is(tags::BODY) {
                    break;
                }
                context.tag_stack.pop();
            }
            Event::Eof => return Err(ParseErrorKind::UnexpectedEof).with_context(reader, context),
            _ => (),
        }
        buf.clear();
    }
    Ok(())
}

/// 解析歌词区块,即一个 `<div>` 标签
///
/// ## 示例
/// ```xml
/// <div begin="10.522" end="43.125" itunes:songPart="Verse">
///     <p begin="10.522" end="13.518" itunes:key="L3" ttm:agent="v1">
///         ...
///     </p>
///     <p begin="12.791" end="19.911" itunes:key="L4" ttm:agent="v1">
///         ...
///     </p>
///     <p begin="19.257" end="24.640" itunes:key="L5" ttm:agent="v1">
///         ...
///     </p>
///     <p begin="24.262" end="29.397" itunes:key="L6" ttm:agent="v1">
///         ...
///     </p>
///     <p begin="28.487" end="34.116" itunes:key="L7" ttm:agent="v1">
///         ...
///     </p>
///     <p begin="32.977" end="38.719" itunes:key="L8" ttm:agent="v1">
///        ...
///     </p>
///     <p begin="37.894" end="43.125" itunes:key="L9" ttm:agent="v1">
///         ...
///     </p>
/// </div>
/// ```
fn parse_section(
    reader: &mut Reader<&[u8]>,
    div_event: &BytesStart,
    context: &mut ParserContext,
    lines: &mut Vec<LyricLine>,
) -> Result<()> {
    // 当前 div 的 songPart,如 "Verse", "Chorus"
    let mut current_song_part =
        div_event.get_attr_value(attrs::ITUNES_SONGPART, reader, context)?;
    if current_song_part.is_none() {
        current_song_part =
            div_event.get_attr_value(attrs::ITUNES_SONGPART_KEBAB, reader, context)?;
    }

    // 维护 block_index
    context.current_block_index += 1;
    if context.last_song_part != current_song_part {
        context.last_song_part = current_song_part;
    }

    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::P) {
                    if let Some(line) = parse_line(reader, e, context)? {
                        lines.push(line);
                    }
                    context.tag_stack.pop();
                }
            }
            Event::End(ref e) => {
                if e.name().is(tags::DIV) {
                    break;
                }
                context.tag_stack.pop();
            }
            Event::Eof => return Err(ParseErrorKind::UnexpectedEof).with_context(reader, context),
            _ => (),
        }
        buf.clear();
    }
    Ok(())
}

/// 解析一行歌词,即一个 `<p>` 标签
///
/// ## 示例
/// ```xml
/// <p begin="10.522" end="13.518" itunes:key="L3" ttm:agent="v1">
///     <span begin="10.522" end="10.716">It</span>
///     <span begin="10.716" end="10.908">was</span>
///     <span begin="10.908" end="11.193">my</span>
///     <span begin="11.193" end="11.759">wedding</span>
///     <span begin="11.759" end="12.645">day</span>
///     <span ttm:role="x-bg">
///         <span begin="11.724" end="11.894">(It</span>
///         <span begin="11.894" end="12.059">was</span>
///         <span begin="12.059" end="12.314">our</span>
///         <span begin="12.314" end="12.851">wedding</span>
///         <span begin="12.851" end="13.518">day)</span>
///     </span>
/// </p>
/// ```
fn parse_line(
    reader: &mut Reader<&[u8]>,
    p_event: &BytesStart,
    context: &mut ParserContext,
) -> Result<Option<LyricLine>> {
    let line_id = p_event.get_attr_value(attrs::ITUNES_KEY, reader, context)?;
    context.current_line_id.clone_from(&line_id);

    let start_time = p_event.get_required_timestamp_attr(attrs::BEGIN, reader, context)?;
    let end_time = p_event.get_required_timestamp_attr(attrs::END, reader, context)?;

    let mut line = LyricLine {
        id: line_id.clone(),
        agent_id: p_event.get_attr_value(attrs::TTM_AGENT, reader, context)?,
        song_part: context.last_song_part.clone(),
        block_index: Some(context.current_block_index),
        start_time,
        end_time,
        ..Default::default()
    };

    // 提取之前从 `<iTunesMetadata>` 解析出来的外挂翻译和音译并放入主歌词行中
    if let Some(id) = &line.id {
        line.translations = context.translations_map.remove(id);
        line.romanizations = context.romanizations_map.remove(id);

        let bg_trans = context.bg_translations_map.remove(id);
        let bg_rom = context.bg_romanizations_map.remove(id);

        if bg_trans.is_some() || bg_rom.is_some() {
            line.background_vocal = Some(BackgroundVocal {
                translations: bg_trans,
                romanizations: bg_rom,
                ..Default::default()
            });
        }
    }

    let mut raw_text = String::new();

    // 解析内部的 span
    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) {
                    process_span(reader, context, e, &mut line, false)?;
                    context.tag_stack.pop();
                }
            }
            Event::Text(e) => {
                let text =
                    std::str::from_utf8(e.as_ref()).map_err(TTMLProcessorError::Utf8Error)?;
                if is_spacing_text(text) {
                    mark_last_syllable_space(&mut line, false);
                }
                raw_text.push_str(text);
            }
            Event::GeneralRef(reference) => {
                raw_text.push_str(&resolve_xml_entity(&reference).with_context(reader, context)?);
            }
            Event::End(ref e) => {
                if e.name().is(tags::P) {
                    break;
                }
                context.tag_stack.pop();
            }
            Event::Eof => return Err(ParseErrorKind::UnexpectedEof).with_context(reader, context),
            _ => (),
        }
        buf.clear();
    }

    post_process_line(&mut line, raw_text);

    context.current_line_id = None;

    Ok(Some(line))
}

/// 后处理一行歌词,包括:
/// * 移除整行歌词的尾随空格
/// * 从逐字歌词拼接逐行文本
/// * 规范化歌词音节、翻译、音译中的空格
/// * 移除背景人声中的括号
fn post_process_line(line: &mut LyricLine, raw_line_text: String) {
    // 移除部分歌词可能出现的尾随空格
    if let Some(words) = &mut line.words
        && let Some(last) = words.last_mut()
    {
        last.ends_with_space = None;
    }
    if let Some(bg) = &mut line.background_vocal
        && let Some(bg_words) = &mut bg.words
        && let Some(last) = bg_words.last_mut()
    {
        last.ends_with_space = None;
    }

    // 规范化主歌词的内容
    match &mut line.words {
        Some(words) if !words.is_empty() => {
            normalize_words_spaces(words);
            line.text = build_full_text(words);
        }
        _ => {
            line.words = None;
            line.text = raw_line_text;
            normalize_line_text(&mut line.text);
        }
    }

    // 规范化主歌词的翻译
    if let Some(translations) = &mut line.translations {
        for t in translations {
            if let Some(t_words) = &mut t.words {
                normalize_words_spaces(t_words);
                t.text = build_full_text(t_words);
            } else {
                normalize_line_text(&mut t.text);
            }
        }
    }

    // 规范化主歌词的音译
    if let Some(romanizations) = &mut line.romanizations {
        for r in romanizations {
            if let Some(r_words) = &mut r.words {
                normalize_words_spaces(r_words);
                r.text = build_full_text(r_words);
            } else {
                normalize_line_text(&mut r.text);
            }
        }
    }

    // 后处理背景人声的括号、空格与文本拼接
    if let Some(bg) = &mut line.background_vocal {
        // 背景人声的主歌词
        if let Some(bg_words) = &mut bg.words {
            strip_outer_parens_from_words(bg_words);
            normalize_words_spaces(bg_words);
            bg.text = build_full_text(bg_words);
        } else {
            strip_outer_parens(&mut bg.text);
            normalize_line_text(&mut bg.text);
        }

        // 背景人声的翻译
        if let Some(translations) = &mut bg.translations {
            for t in translations {
                if let Some(t_words) = &mut t.words {
                    strip_outer_parens_from_words(t_words);
                    normalize_words_spaces(t_words);
                    t.text = build_full_text(t_words);
                } else {
                    strip_outer_parens(&mut t.text);
                    normalize_line_text(&mut t.text);
                }
            }
        }

        // 背景人声的音译
        if let Some(romanizations) = &mut bg.romanizations {
            for r in romanizations {
                if let Some(r_words) = &mut r.words {
                    strip_outer_parens_from_words(r_words);
                    normalize_words_spaces(r_words);
                    r.text = build_full_text(r_words);
                } else {
                    strip_outer_parens(&mut r.text);
                    normalize_line_text(&mut r.text);
                }
            }
        }
    }
}

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

    use super::*;
    use crate::model::{
        BackgroundVocal,
        SubLyricContent,
        Syllable,
    };

    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();
        }
    }

    fn get_start_event<'a>(reader: &mut Reader<&'a [u8]>, tag: &str) -> BytesStart<'a> {
        let mut buf = Vec::new();
        loop {
            match reader
                .read_event_into(&mut buf)
                .expect("Failed to read XML")
            {
                Event::Start(e) if e.name().as_ref() == tag.as_bytes() => return e.into_owned(),
                Event::Eof => panic!("Reached EOF before finding start tag"),
                _ => (),
            }
        }
    }

    #[test]
    fn test_post_process_line() {
        let mut line = LyricLine {
            start_time: 1000,
            end_time: 2000,
            background_vocal: Some(BackgroundVocal {
                words: Some(vec![
                    Syllable {
                        text: "(Ah".to_string(),
                        ends_with_space: Some(true),
                        ..Default::default()
                    },
                    Syllable {
                        text: "ha)".to_string(),
                        ..Default::default()
                    },
                ]),
                ..Default::default()
            }),
            ..Default::default()
        };

        post_process_line(&mut line, "  raw   line   text  ".to_string());

        assert_eq!(line.text, "raw line text");
        assert_eq!(line.start_time, 1000);
        assert_eq!(line.end_time, 2000);

        let bg = line.background_vocal.as_ref().unwrap();
        assert_eq!(bg.text, "Ah ha");
        let bg_words = bg.words.as_ref().unwrap();
        assert_eq!(bg_words[0].text, "Ah");
        assert_eq!(bg_words[1].text, "ha");
    }

    #[test]
    fn test_parse_line() {
        let xml = r#"<p begin="10.522" end="13.518" itunes:key="L3" ttm:agent="v1">
            <span begin="10.522" end="11.000">Hello</span>
        </p>"#;
        let mut reader = Reader::from_str(xml);
        let start_event = get_start_event(&mut reader, "p");

        let mut context = ParserContext::default();

        context.translations_map.insert(
            "L3".to_string(),
            vec![SubLyricContent {
                language: Some("zh".to_string()),
                text: "你好".to_string(),
                words: None,
            }],
        );
        context.last_song_part = Some("Verse".to_string());
        context.current_block_index = 1;

        let line = parse_line(&mut reader, &start_event, &mut context)
            .expect("Failed to parse line")
            .unwrap();

        assert_eq!(line.id.as_deref(), Some("L3"));
        assert_eq!(line.agent_id.as_deref(), Some("v1"));
        assert_eq!(line.song_part.as_deref(), Some("Verse"));
        assert_eq!(line.block_index, Some(1));

        assert_eq!(line.start_time, 10522);
        assert_eq!(line.end_time, 13518);

        assert_eq!(line.text, "Hello");
        assert_eq!(line.words.unwrap().len(), 1);

        let translations = line.translations.unwrap();
        assert_eq!(translations.len(), 1);
        assert_eq!(translations[0].text, "你好");
        assert!(context.translations_map.is_empty());
    }

    #[test]
    fn test_parse_section() {
        let xml = r#"<div itunes:songPart="Chorus">
            <p begin="0.0" end="1.0" itunes:key="L1">Line 1</p>
            <p begin="1.0" end="2.0" itunes:key="L2">Line 2</p>
        </div>"#;
        let mut reader = Reader::from_str(xml);
        let start_event = get_start_event(&mut reader, "div");

        let mut context = ParserContext::default();
        let mut lines = Vec::new();

        parse_section(&mut reader, &start_event, &mut context, &mut lines)
            .expect("Failed to parse section");

        assert_eq!(context.last_song_part.as_deref(), Some("Chorus"));
        assert_eq!(context.current_block_index, 1);

        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].id.as_deref(), Some("L1"));
        assert_eq!(lines[0].song_part.as_deref(), Some("Chorus"));
        assert_eq!(lines[0].block_index, Some(1));
        assert_eq!(lines[1].id.as_deref(), Some("L2"));
        assert_eq!(lines[1].song_part.as_deref(), Some("Chorus"));
        assert_eq!(lines[1].block_index, Some(1));
    }

    #[test]
    fn test_parse_body() {
        let xml = r#"<body>
            <div itunes:songPart="Verse">
                <p begin="0.0" end="1.0">V1</p>
            </div>
            <div itunes:songPart="Chorus">
                <p begin="1.0" end="2.0">C1</p>
            </div>
        </body>"#;
        let mut reader = Reader::from_str(xml);

        advance_to_start_tag(&mut reader, "body");

        let mut context = ParserContext::default();
        let mut lines = Vec::new();

        parse_body(&mut reader, &mut context, &mut lines).expect("Failed to parse body");

        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].song_part.as_deref(), Some("Verse"));
        assert_eq!(lines[0].block_index, Some(1));
        assert_eq!(lines[1].song_part.as_deref(), Some("Chorus"));
        assert_eq!(lines[1].block_index, Some(2));
        assert_eq!(context.current_block_index, 2);
    }
}