ebustl-parser 0.7.0

Parse subtitle files in the EBU-STL format with Rust.
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! The Text Fields (TF) of TTI blocks: the types of the decoded content, and the encoding and
//! decoding of subtitle text with control codes (Tech 3264 section 5).

use textcode::{
    Iso8859_5, Iso8859_6, Iso8859_7, Iso8859_8, decode as decode_iso8859, encode as encode_iso8859,
};

use crate::{CharacterCodeTable, latin};

/// Length of the Text Field of a TTI block
pub(crate) const TF_LENGTH: usize = 112;
/// Text Field code for CR/LF
pub(crate) const TF_CR_LF: u8 = 0x8A;
/// Text Field code for unused space, also terminating the text
pub(crate) const TF_UNUSED_SPACE: u8 = 0x8F;

// Teletext control codes, Appendix 2
const TELETEXT_END_BOX: u8 = 0x0A;
const TELETEXT_START_BOX: u8 = 0x0B;
const TELETEXT_DOUBLE_HEIGHT: u8 = 0x0D;

/// A part of the decoded Text Field of a subtitle.
///
/// Characters between control codes are combined into a single [`TextElement::Text`]. The
/// unused space code (8Fh) ends the text and is not included.
///
/// # Example
///
/// ```rust
/// use ebustl_parser::{Color, TeletextControl, TextElement};
///
/// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
/// assert_eq!(
///     vec![
///         TextElement::Teletext(TeletextControl::DoubleHeight),
///         TextElement::Teletext(TeletextControl::AlphaColor(Color::Cyan)),
///         TextElement::Teletext(TeletextControl::StartBox),
///         TextElement::Teletext(TeletextControl::StartBox),
///         TextElement::Text("au pied de la statue de la Liberté.".to_string()),
///         TextElement::Teletext(TeletextControl::EndBox),
///         TextElement::NewLine,
///     ],
///     stl.ttis[2].text_elements()
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TextElement {
    /// Characters, decoded with the Character Code Table
    Text(String),
    /// CR/LF (8Ah), starting the next row
    NewLine,
    /// A teletext control code (00h-1Fh), used for teletext subtitles. Teletext control codes
    /// occupy a character position on screen.
    Teletext(TeletextControl),
    /// A control code for open subtitles (80h-85h)
    Open(OpenControl),
    /// A code reserved for future use (86h-89h, 8Bh-8Eh and 90h-9Fh)
    Reserved(u8),
}

impl TextElement {
    /// The element for a control code, i.e. 00h-1Fh or 80h-9Fh except unused space (8Fh).
    pub(crate) fn from_control_code(code: u8) -> TextElement {
        match code {
            0x00..=0x1F => TextElement::Teletext(TeletextControl::from_code(code)),
            0x80 => TextElement::Open(OpenControl::ItalicsOn),
            0x81 => TextElement::Open(OpenControl::ItalicsOff),
            0x82 => TextElement::Open(OpenControl::UnderlineOn),
            0x83 => TextElement::Open(OpenControl::UnderlineOff),
            0x84 => TextElement::Open(OpenControl::BoxingOn),
            0x85 => TextElement::Open(OpenControl::BoxingOff),
            0x8A => TextElement::NewLine,
            code => TextElement::Reserved(code),
        }
    }
}

/// A teletext control code (00h-1Fh), Tech 3264 Appendix 2, reproduced from EBU Tech 3240.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TeletextControl {
    /// Alphanumeric characters in the color (00h-07h)
    AlphaColor(Color),
    /// Flash (08h)
    Flash,
    /// Steady (09h)
    Steady,
    /// End box (0Ah)
    EndBox,
    /// Start box (0Bh)
    StartBox,
    /// Normal height (0Ch)
    NormalHeight,
    /// Double height (0Dh)
    DoubleHeight,
    /// Double width (0Eh)
    DoubleWidth,
    /// Double size (0Fh)
    DoubleSize,
    /// Mosaic graphics in the color (10h-17h)
    MosaicColor(Color),
    /// Conceal (18h)
    Conceal,
    /// Contiguous mosaic (19h)
    ContiguousMosaic,
    /// Separated mosaic (1Ah)
    SeparatedMosaic,
    /// Reserved (1Bh)
    Reserved,
    /// Black background (1Ch)
    BlackBackground,
    /// New background (1Dh), the background takes the current foreground color
    NewBackground,
    /// Hold mosaic (1Eh)
    HoldMosaic,
    /// Release mosaic (1Fh)
    ReleaseMosaic,
}

impl TeletextControl {
    /// The control for a code 00h-1Fh.
    fn from_code(code: u8) -> TeletextControl {
        match code {
            0x00..=0x07 => TeletextControl::AlphaColor(Color::from_code(code)),
            0x08 => TeletextControl::Flash,
            0x09 => TeletextControl::Steady,
            0x0A => TeletextControl::EndBox,
            0x0B => TeletextControl::StartBox,
            0x0C => TeletextControl::NormalHeight,
            0x0D => TeletextControl::DoubleHeight,
            0x0E => TeletextControl::DoubleWidth,
            0x0F => TeletextControl::DoubleSize,
            0x10..=0x17 => TeletextControl::MosaicColor(Color::from_code(code)),
            0x18 => TeletextControl::Conceal,
            0x19 => TeletextControl::ContiguousMosaic,
            0x1A => TeletextControl::SeparatedMosaic,
            0x1B => TeletextControl::Reserved,
            0x1C => TeletextControl::BlackBackground,
            0x1D => TeletextControl::NewBackground,
            0x1E => TeletextControl::HoldMosaic,
            _ => TeletextControl::ReleaseMosaic,
        }
    }
}

/// A teletext color, used by [`TeletextControl::AlphaColor`] and
/// [`TeletextControl::MosaicColor`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Color {
    /// Black (0)
    Black,
    /// Red (1)
    Red,
    /// Green (2)
    Green,
    /// Yellow (3)
    Yellow,
    /// Blue (4)
    Blue,
    /// Magenta (5)
    Magenta,
    /// Cyan (6)
    Cyan,
    /// White (7)
    White,
}

impl Color {
    /// The color in the lowest three bits of a teletext color code.
    fn from_code(code: u8) -> Color {
        match code & 0x07 {
            0 => Color::Black,
            1 => Color::Red,
            2 => Color::Green,
            3 => Color::Yellow,
            4 => Color::Blue,
            5 => Color::Magenta,
            6 => Color::Cyan,
            _ => Color::White,
        }
    }
}

/// A control code for open (in-vision) subtitles (80h-85h).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenControl {
    /// Italics on (80h)
    ItalicsOn,
    /// Italics off (81h)
    ItalicsOff,
    /// Underline on (82h)
    UnderlineOn,
    /// Underline off (83h)
    UnderlineOff,
    /// Boxing on (84h)
    BoxingOn,
    /// Boxing off (85h)
    BoxingOff,
}

/// How the rows of a subtitle are presented
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Presentation {
    /// Teletext subtitles, each row boxed and optionally in double height
    Teletext { double_height: bool },
    /// Open (in-vision) subtitles, which must not use teletext control codes
    Open,
}

impl Presentation {
    /// Control codes starting each row
    fn row_start(self) -> &'static [u8] {
        match self {
            Presentation::Teletext {
                double_height: true,
            } => &[
                TELETEXT_DOUBLE_HEIGHT,
                TELETEXT_START_BOX,
                TELETEXT_START_BOX,
            ],
            Presentation::Teletext {
                double_height: false,
            } => &[TELETEXT_START_BOX, TELETEXT_START_BOX],
            Presentation::Open => &[],
        }
    }

    /// Control codes ending each row
    fn row_end(self) -> &'static [u8] {
        match self {
            Presentation::Teletext { .. } => &[TELETEXT_END_BOX, TELETEXT_END_BOX],
            Presentation::Open => &[],
        }
    }

    /// Codes between two rows. A double height row occupies two teletext rows.
    fn row_separator(self) -> &'static [u8] {
        match self {
            Presentation::Teletext {
                double_height: true,
            } => &[TF_CR_LF, TF_CR_LF],
            _ => &[TF_CR_LF],
        }
    }
}

/// Encodes `text` into Text Fields, one per TTI block, padded with unused space (8Fh).
///
/// Rows are separated by `\n` or `\r\n`, other control characters are dropped. A character is
/// never split between two Text Fields, and the last Text Field always ends with unused space
/// as the spec requires.
pub(crate) fn encode_text_fields(
    text: &str,
    presentation: Presentation,
    cct: CharacterCodeTable,
) -> Vec<Vec<u8>> {
    let terminator = [TF_UNUSED_SPACE];
    let units = text_units(text, presentation, cct);

    let mut fields = Vec::new();
    let mut field = Vec::with_capacity(TF_LENGTH);
    for unit in units
        .iter()
        .map(Vec::as_slice)
        .chain([terminator.as_slice()])
    {
        if field.len() + unit.len() > TF_LENGTH {
            fields.push(pad(field));
            field = Vec::with_capacity(TF_LENGTH);
        }
        field.extend_from_slice(unit);
    }
    fields.push(pad(field));
    fields
}

/// Encodes `text` into a single Text Field like [`encode_text_fields`], truncating text that
/// does not fit.
pub(crate) fn encode_truncated_text_field(
    text: &str,
    presentation: Presentation,
    cct: CharacterCodeTable,
) -> Vec<u8> {
    let units = text_units(text, presentation, cct);
    // Keep at least one byte for the terminating unused space
    let mut len = 0;
    let fitting = units
        .iter()
        .take_while(|unit| {
            len += unit.len();
            len < TF_LENGTH
        })
        .count();
    pad(units[..fitting].concat())
}

/// Encodes the text as units, the bytes of a character or control code, which must be kept
/// together in one Text Field.
fn text_units(text: &str, presentation: Presentation, cct: CharacterCodeTable) -> Vec<Vec<u8>> {
    let control_codes = |codes: &[u8]| codes.iter().map(|&code| vec![code]).collect::<Vec<_>>();

    let mut units = Vec::new();
    for (i, row) in text.lines().enumerate() {
        if i > 0 {
            units.extend(control_codes(presentation.row_separator()));
        }
        units.extend(control_codes(presentation.row_start()));
        units.extend(
            row.chars()
                .filter(|c| !c.is_control())
                .map(|c| encode_characters(c.encode_utf8(&mut [0; 4]), cct)),
        );
        units.extend(control_codes(presentation.row_end()));
    }
    units
}

/// Encodes text using the given character code table.
fn encode_characters(text: &str, cct: CharacterCodeTable) -> Vec<u8> {
    match cct {
        CharacterCodeTable::Latin => latin::encode(text),
        CharacterCodeTable::LatinCyrillic => encode_iso8859::<Iso8859_5>(text),
        CharacterCodeTable::LatinArabic => encode_iso8859::<Iso8859_6>(text),
        CharacterCodeTable::LatinGreek => encode_iso8859::<Iso8859_7>(text),
        CharacterCodeTable::LatinHebrew => encode_iso8859::<Iso8859_8>(text),
    }
}

fn pad(mut field: Vec<u8>) -> Vec<u8> {
    field.resize(TF_LENGTH, TF_UNUSED_SPACE);
    field
}

/// The Text Field up to, but not including, the first unused space code (8Fh).
pub(crate) fn content(tf: &[u8]) -> &[u8] {
    let end = tf
        .iter()
        .position(|&c| c == TF_UNUSED_SPACE)
        .unwrap_or(tf.len());
    &tf[..end]
}

/// Decodes a Text Field, or several concatenated ones, into characters and control codes.
///
/// Decoding stops at the first unused space code (8Fh).
pub(crate) fn decode_elements(tf: &[u8], cct: CharacterCodeTable) -> Vec<TextElement> {
    let mut elements = Vec::new();
    // Start of the current run of character codes
    let mut run_start = 0;
    for (i, &code) in tf.iter().enumerate() {
        let is_control_code = matches!(code, 0x00..=0x1F | 0x80..=0x9F);
        if !is_control_code {
            continue;
        }
        push_text(&mut elements, &tf[run_start..i], cct);
        if code == TF_UNUSED_SPACE {
            return elements;
        }
        elements.push(TextElement::from_control_code(code));
        run_start = i + 1;
    }
    // The text may fill the field without a terminating control code
    push_text(&mut elements, &tf[run_start..], cct);
    elements
}

fn push_text(elements: &mut Vec<TextElement>, data: &[u8], cct: CharacterCodeTable) {
    if !data.is_empty() {
        elements.push(TextElement::Text(decode_characters(data, cct)));
    }
}

/// Decodes a Text Field, or several concatenated ones, into a string.
///
/// Control codes are dropped, except CR/LF which becomes `\r\n`. Decoding stops at the first
/// unused space code (8Fh).
pub(crate) fn decode(tf: &[u8], cct: CharacterCodeTable) -> String {
    let mut result = String::new();
    for element in decode_elements(tf, cct) {
        match element {
            TextElement::Text(text) => result.push_str(&text),
            TextElement::NewLine => result.push_str("\r\n"),
            _ => {}
        }
    }
    result
}

/// Decodes character codes (no control codes) using the given character code table.
fn decode_characters(data: &[u8], cct: CharacterCodeTable) -> String {
    match cct {
        CharacterCodeTable::Latin => latin::decode(data),
        CharacterCodeTable::LatinCyrillic => decode_iso8859::<Iso8859_5>(data),
        CharacterCodeTable::LatinArabic => decode_iso8859::<Iso8859_6>(data),
        CharacterCodeTable::LatinGreek => decode_iso8859::<Iso8859_7>(data),
        CharacterCodeTable::LatinHebrew => decode_iso8859::<Iso8859_8>(data),
    }
}

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

    const TELETEXT: Presentation = Presentation::Teletext {
        double_height: false,
    };
    const TELETEXT_DH: Presentation = Presentation::Teletext {
        double_height: true,
    };
    const LATIN: CharacterCodeTable = CharacterCodeTable::Latin;

    /// The single Text Field of `text`, without the padding
    fn encoded(text: &str, presentation: Presentation) -> Vec<u8> {
        let fields = encode_text_fields(text, presentation, LATIN);
        assert_eq!(1, fields.len());
        without_padding(&fields[0])
    }

    fn without_padding(field: &[u8]) -> Vec<u8> {
        assert_eq!(TF_LENGTH, field.len());
        let end = field.iter().position(|&c| c == TF_UNUSED_SPACE).unwrap();
        assert!(field[end..].iter().all(|&c| c == TF_UNUSED_SPACE));
        field[..end].to_vec()
    }

    #[test]
    fn teletext_row_is_boxed() {
        assert_eq!(b"\x0B\x0BHi\x0A\x0A".to_vec(), encoded("Hi", TELETEXT));
    }

    #[test]
    fn teletext_double_height_row() {
        assert_eq!(
            b"\x0D\x0B\x0BHi\x0A\x0A".to_vec(),
            encoded("Hi", TELETEXT_DH)
        );
    }

    #[test]
    fn teletext_rows_are_separated_by_cr_lf() {
        assert_eq!(
            b"\x0B\x0BOne\x0A\x0A\x8A\x0B\x0BTwo\x0A\x0A".to_vec(),
            encoded("One\nTwo", TELETEXT)
        );
    }

    #[test]
    fn teletext_double_height_rows_are_separated_by_two_cr_lf() {
        assert_eq!(
            b"\x0D\x0B\x0BOne\x0A\x0A\x8A\x8A\x0D\x0B\x0BTwo\x0A\x0A".to_vec(),
            encoded("One\nTwo", TELETEXT_DH)
        );
    }

    #[test]
    fn open_subtitle_has_no_teletext_codes() {
        assert_eq!(
            b"One\x8ATwo".to_vec(),
            encoded("One\nTwo", Presentation::Open)
        );
    }

    #[test]
    fn crlf_and_trailing_newline() {
        assert_eq!(
            b"One\x8ATwo".to_vec(),
            encoded("One\r\nTwo\n", Presentation::Open)
        );
    }

    #[test]
    fn control_characters_are_dropped() {
        assert_eq!(
            b"OneTwo".to_vec(),
            encoded("One\tTwo\r", Presentation::Open)
        );
    }

    #[test]
    fn characters_are_encoded_with_the_table() {
        assert_eq!(b"\xC2e\xA4".to_vec(), encoded("é$", Presentation::Open));
        let fields = encode_text_fields("Ж", Presentation::Open, CharacterCodeTable::LatinCyrillic);
        assert_eq!(vec![0xB6], without_padding(&fields[0]));
    }

    #[test]
    fn empty_text_is_unused_space() {
        assert_eq!(Vec::<u8>::new(), encoded("", TELETEXT));
    }

    #[test]
    fn text_filling_one_field_leaves_room_for_unused_space() {
        let fields = encode_text_fields(&"a".repeat(TF_LENGTH - 1), Presentation::Open, LATIN);
        assert_eq!(1, fields.len());
        assert_eq!(TF_UNUSED_SPACE, fields[0][TF_LENGTH - 1]);
    }

    #[test]
    fn full_field_is_followed_by_field_of_unused_space() {
        let fields = encode_text_fields(&"a".repeat(TF_LENGTH), Presentation::Open, LATIN);
        assert_eq!(2, fields.len());
        assert_eq!(vec![b'a'; TF_LENGTH], fields[0]);
        assert_eq!(vec![TF_UNUSED_SPACE; TF_LENGTH], fields[1]);
    }

    #[test]
    fn long_text_continues_in_next_fields() {
        let text = "0123456789".repeat(30);
        let fields = encode_text_fields(&text, Presentation::Open, LATIN);

        assert_eq!(3, fields.len());
        assert_eq!(text.as_bytes()[..TF_LENGTH], fields[0][..]);
        assert_eq!(text.as_bytes()[TF_LENGTH..2 * TF_LENGTH], fields[1][..]);
        assert_eq!(
            text.as_bytes()[2 * TF_LENGTH..].to_vec(),
            without_padding(&fields[2])
        );
    }

    #[test]
    fn accented_character_is_not_split_between_fields() {
        // 'é' is two bytes (C2h 65h) and would straddle the end of the first field
        let text = format!("{}é", "a".repeat(TF_LENGTH - 1));
        let fields = encode_text_fields(&text, Presentation::Open, LATIN);

        assert_eq!(2, fields.len());
        assert_eq!(vec![b'a'; TF_LENGTH - 1], without_padding(&fields[0]));
        assert_eq!(b"\xC2e".to_vec(), without_padding(&fields[1]));
    }

    #[test]
    fn truncated_field_ends_with_unused_space() {
        let field = encode_truncated_text_field(&"a".repeat(200), TELETEXT, LATIN);

        let mut expected = b"\x0B\x0B".to_vec();
        expected.extend(vec![b'a'; TF_LENGTH - 3]);
        assert_eq!(expected, without_padding(&field));
    }

    #[test]
    fn truncated_field_does_not_split_accented_character() {
        let text = format!("{}é", "a".repeat(TF_LENGTH - 2));
        let field = encode_truncated_text_field(&text, Presentation::Open, LATIN);

        assert_eq!(vec![b'a'; TF_LENGTH - 2], without_padding(&field));
    }

    #[test]
    fn short_text_is_not_truncated() {
        let field = encode_truncated_text_field("One\nTwo", TELETEXT, LATIN);
        assert_eq!(encoded("One\nTwo", TELETEXT), without_padding(&field));
    }

    #[test]
    fn content_ends_at_unused_space() {
        assert_eq!(b"One", content(b"One\x8FTwo\x8F"));
        assert_eq!(b"", content(b"\x8F\x8F"));
        assert_eq!(b"Full", content(b"Full"));
    }

    #[test]
    fn decode_drops_control_codes_except_cr_lf() {
        let tf = b"\x0D\x0B\x0BOne\x0A\x0A\x8A\x80Two\x81\x8F";
        assert_eq!("One\r\nTwo", decode(tf, LATIN));
    }

    #[test]
    fn decode_stops_at_unused_space() {
        assert_eq!("One", decode(b"One\x8FTwo", LATIN));
    }

    #[test]
    fn decode_text_without_terminating_control_code() {
        assert_eq!("a".repeat(TF_LENGTH), decode(&[b'a'; TF_LENGTH], LATIN));
    }

    #[test]
    fn decode_uses_the_table() {
        assert_eq!("é$", decode(b"\xC2e\xA4", LATIN));
        assert_eq!("Ж", decode(&[0xB6], CharacterCodeTable::LatinCyrillic));
    }

    #[test]
    fn encode_decode_roundtrip() {
        let text = "Première ligne à $5\nDeuxième ligne";
        for presentation in [TELETEXT, Presentation::Open] {
            let fields = encode_text_fields(text, presentation, LATIN);
            assert_eq!(
                "Première ligne à $5\r\nDeuxième ligne",
                decode(&fields[0], LATIN)
            );
        }
        let fields = encode_text_fields(text, TELETEXT_DH, LATIN);
        assert_eq!(
            "Première ligne à $5\r\n\r\nDeuxième ligne",
            decode(&fields[0], LATIN)
        );
    }

    #[test]
    fn decode_elements_with_control_codes() {
        let tf = b"\x0D\x06\x0B\x0BHi\x0A\x0A\x8A\x80\xC2e\x81\x86\x8Fignored";
        assert_eq!(
            vec![
                TextElement::Teletext(TeletextControl::DoubleHeight),
                TextElement::Teletext(TeletextControl::AlphaColor(Color::Cyan)),
                TextElement::Teletext(TeletextControl::StartBox),
                TextElement::Teletext(TeletextControl::StartBox),
                TextElement::Text("Hi".to_string()),
                TextElement::Teletext(TeletextControl::EndBox),
                TextElement::Teletext(TeletextControl::EndBox),
                TextElement::NewLine,
                TextElement::Open(OpenControl::ItalicsOn),
                TextElement::Text("é".to_string()),
                TextElement::Open(OpenControl::ItalicsOff),
                TextElement::Reserved(0x86),
            ],
            decode_elements(tf, LATIN)
        );
    }

    #[test]
    fn decode_elements_of_empty_field() {
        assert_eq!(
            Vec::<TextElement>::new(),
            decode_elements(&[TF_UNUSED_SPACE; TF_LENGTH], LATIN)
        );
    }

    #[test]
    fn decode_elements_of_text_filling_the_field() {
        assert_eq!(
            vec![TextElement::Text("a".repeat(TF_LENGTH))],
            decode_elements(&[b'a'; TF_LENGTH], LATIN)
        );
    }

    #[test]
    fn decode_agrees_with_decode_elements() {
        let tf = b"\x0D\x0B\x0BOne\x0A\x0A\x8A\x8A\x80Two\x81\x8F";
        assert_eq!("One\r\n\r\nTwo", decode(tf, LATIN));
    }

    #[test]
    fn teletext_control_codes() {
        use TeletextControl::*;
        let expected = [
            AlphaColor(Color::Black),
            AlphaColor(Color::Red),
            AlphaColor(Color::Green),
            AlphaColor(Color::Yellow),
            AlphaColor(Color::Blue),
            AlphaColor(Color::Magenta),
            AlphaColor(Color::Cyan),
            AlphaColor(Color::White),
            Flash,
            Steady,
            EndBox,
            StartBox,
            NormalHeight,
            DoubleHeight,
            DoubleWidth,
            DoubleSize,
            MosaicColor(Color::Black),
            MosaicColor(Color::Red),
            MosaicColor(Color::Green),
            MosaicColor(Color::Yellow),
            MosaicColor(Color::Blue),
            MosaicColor(Color::Magenta),
            MosaicColor(Color::Cyan),
            MosaicColor(Color::White),
            Conceal,
            ContiguousMosaic,
            SeparatedMosaic,
            Reserved,
            BlackBackground,
            NewBackground,
            HoldMosaic,
            ReleaseMosaic,
        ];
        for (code, control) in (0x00..=0x1F).zip(expected) {
            assert_eq!(
                TextElement::Teletext(control),
                TextElement::from_control_code(code),
                "code {code:02X}h"
            );
        }
    }

    #[test]
    fn open_subtitle_control_codes() {
        use OpenControl::*;
        let expected = [
            ItalicsOn,
            ItalicsOff,
            UnderlineOn,
            UnderlineOff,
            BoxingOn,
            BoxingOff,
        ];
        for (code, control) in (0x80..=0x85).zip(expected) {
            assert_eq!(
                TextElement::Open(control),
                TextElement::from_control_code(code),
                "code {code:02X}h"
            );
        }
    }

    #[test]
    fn cr_lf_and_reserved_codes() {
        assert_eq!(TextElement::NewLine, TextElement::from_control_code(0x8A));
        for code in (0x86..=0x89).chain(0x8B..=0x8E).chain(0x90..=0x9F) {
            assert_eq!(
                TextElement::Reserved(code),
                TextElement::from_control_code(code)
            );
        }
    }
}