Skip to main content

timed_metadata/webvtt/
teletext.rs

1//! EBU Teletext (ETSI EN 300 706 V1.2.1) subtitle page decode.
2//!
3//! Cite: `private/specs-verified/dvb/timed-metadata/teletext-subtitles.md` (curated transcription of the sections
4//! used here: §7.1 packet structure, §8.1/§8.2 FEC, §9.3.1 page header,
5//! Table 2 control bits, §12.2 spacing attributes, §15.1-15.2 national option
6//! selection, Table 35/36 Latin G0 character set; the Table 36 reading is in
7//! `private/specs-verified/dvb/timed-metadata/teletext-national-options.md`).
8//!
9//! `dvb-vbi` carries the EN 301 775 VBI PES framing (`TeletextDataField`, a
10//! 42-byte opaque `txt_data_block`) but — by its own module docs — does not
11//! decode EN 300 706 (a large, separate spec covering FEC, character sets and
12//! page composition, not carriage). This module owns that decode, consuming
13//! only `dvb_vbi::TeletextDataField`'s raw bytes:
14//!
15//! - [`decode_hamming_8_4`] / [`encode_hamming_8_4`] — the 4-data-bit +
16//!   4-parity-bit code protecting packet addresses and page header fields
17//!   (§8.2): single-bit errors corrected, double-bit errors rejected.
18//! - `broadcast_common::parity::{strip_parity, set_odd_parity}` — the 7-data-bit + 1-parity
19//!   code protecting displayable row bytes (§8.1): errors only *detected*
20//!   (odd parity carries no correction capability), rendered as
21//!   `'\u{FFFD}'`.
22//! - [`NationalOption`] — the C12/C13/C14 national option sub-set selector
23//!   (§15.1, Table 32's first ["Latin 0", Level-1-ambiguous] group, the
24//!   interpretation clause 15.1 mandates at presentation Level 1). Every
25//!   Table 36 row is a variant; the header can select the first seven.
26//! - [`latin_g0_char`] — Table 35 (Latin G0 Primary Set, identical to 7-bit
27//!   ASCII `0x20`-`0x7F` outside 13 reserved positions) + the Table 36
28//!   substitutions at those positions for the page's national option.
29//! - [`PacketAddress`] / [`decode_packet_address`] — the magazine + row
30//!   number prefix common to every packet (§7.1.2).
31//! - [`PageHeader`] / [`PageHeader::parse`] — the page header packet (`Y=0`,
32//!   §9.3.1): page number, sub-code, and all eleven control bits (Table 2).
33//! - `PageAssembler` (crate-private) — accumulates a single tracked
34//!   `(magazine, page)`'s row packets (`Y=1..=24`) into display text,
35//!   applying the erase-page (C4) and inhibit-display (C10) control bits;
36//!   drives [`crate::webvtt::TeletextCueExtractor`].
37//!
38//! # Documented losses (first pass, matching this crate's `cc-data`
39//! extractors' lossy-by-design philosophy)
40//!
41//! - **No enhancement packets**: `X/26` (character/attribute overwrite),
42//!   `X/27`/`X/28`/`M/29` (page linking, character-set re-designation, side
43//!   panels, CLUTs) are not processed. Only basic Level-1 page composition
44//!   (`X/0` header + `X/1`-`X/24` display rows) is decoded.
45//! - **No styling**: spacing-attribute control codes (`0x00`-`0x1F`, clause
46//!   12.2 — colour, flash, double-height, etc.) are rendered as a space, not
47//!   carried into the WebVTT payload as cue styling. Start Box / End Box are
48//!   interpreted: a C5/C6 page displays only the boxed text.
49//! - **Sub-code ignored for page matching**: a page is matched by magazine +
50//!   page number only; multi-subpage rotation (e.g. multi-language subtitle
51//!   variants sharing one page number) is not distinguished.
52//! - **National options**: only the Level 1 reading of C12-C14 (Table 32's
53//!   first group); X/28 and M/29 designations are not processed.
54use alloc::string::String;
55use alloc::vec::Vec;
56
57/// Decode a Hamming-8/4 protected byte (ETSI EN 300 706 §8.2): bits 1,3,5,7
58/// (transmission order, i.e. the LSB-first bit positions `0x01,0x04,0x10,0x40`)
59/// are the protection bits P1-P4, bits 2,4,6,8 (`0x02,0x08,0x20,0x80`) carry
60/// the 4 data bits D1-D4.
61///
62/// Implemented as a brute-force nearest-codeword search against
63/// [`encode_hamming_8_4`] rather than a hand-derived syndrome table: the code
64/// has minimum distance 4 (a (7,4) Hamming code extended with an overall
65/// parity bit), so a 0-bit-error byte matches its own re-encoding exactly, a
66/// single-bit error matches after flipping exactly one bit, and a
67/// (rejected) double-bit error matches no single flip — this is
68/// mathematically equivalent to the spec's "four odd parity tests A-D"
69/// procedure and was cross-checked against it (see the crate tests below).
70///
71/// Returns the corrected 4-bit data nibble (`D1` in bit 0 .. `D4` in bit 3),
72/// or `None` if the byte is not within Hamming distance 1 of any valid
73/// codeword (an uncorrectable, "double error", byte per §8.2's decode table).
74#[must_use]
75pub fn decode_hamming_8_4(byte: u8) -> Option<u8> {
76    let candidate =
77        (byte >> 1) & 1 | ((byte >> 3) & 1) << 1 | ((byte >> 5) & 1) << 2 | ((byte >> 7) & 1) << 3;
78    if encode_hamming_8_4(candidate) == byte {
79        return Some(candidate);
80    }
81    for bit in 0..8u8 {
82        let flipped = byte ^ (1 << bit);
83        let candidate = (flipped >> 1) & 1
84            | ((flipped >> 3) & 1) << 1
85            | ((flipped >> 5) & 1) << 2
86            | ((flipped >> 7) & 1) << 3;
87        if encode_hamming_8_4(candidate) == flipped {
88            return Some(candidate);
89        }
90    }
91    None
92}
93
94/// Encode a 4-bit data nibble (`D1` in bit 0 .. `D4` in bit 3) as a
95/// Hamming-8/4 protected byte, per the ETSI EN 300 706 §8.2 encoding
96/// equations:
97///
98/// ```text
99/// P1 = 1 ⊕ D1 ⊕ D3 ⊕ D4
100/// P2 = 1 ⊕ D1 ⊕ D2 ⊕ D4
101/// P3 = 1 ⊕ D1 ⊕ D2 ⊕ D3
102/// P4 = 1 ⊕ P1 ⊕ D1 ⊕ P2 ⊕ D2 ⊕ P3 ⊕ D3 ⊕ D4
103/// ```
104///
105/// with wire bit order (transmission order, LSB first) `P1 D1 P2 D2 P3 D3 P4 D4`.
106/// Only the low 4 bits of `nibble` are used.
107#[must_use]
108pub fn encode_hamming_8_4(nibble: u8) -> u8 {
109    let d1 = nibble & 1;
110    let d2 = (nibble >> 1) & 1;
111    let d3 = (nibble >> 2) & 1;
112    let d4 = (nibble >> 3) & 1;
113    let p1 = 1 ^ d1 ^ d3 ^ d4;
114    let p2 = 1 ^ d1 ^ d2 ^ d4;
115    let p3 = 1 ^ d1 ^ d2 ^ d3;
116    let p4 = 1 ^ p1 ^ d1 ^ p2 ^ d2 ^ p3 ^ d3 ^ d4;
117    p1 | (d1 << 1) | (p2 << 2) | (d2 << 3) | (p3 << 4) | (d3 << 5) | (p4 << 6) | (d4 << 7)
118}
119
120/// The C12/C13/C14 "National Option Character Subset" selector (ETSI
121/// EN 300 706 Table 2, page header control bits) — decoded per Table 32's
122/// first group (`0000XXX`, "Latin 0"), which clause 15.1 states is the
123/// interpretation at presentation Level 1 ("the national option sub-set in
124/// use on the page is defined by the C12, C13 and C14 control bits in the
125/// page header alone").
126///
127/// [`latin_g0_char`] applies the Table 36 substitutions of the option in
128/// force; a [`NationalOption::Reserved`] value substitutes nothing.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
131#[non_exhaustive]
132pub enum NationalOption {
133    /// `000` — English.
134    English,
135    /// `001` — German.
136    German,
137    /// `010` — Swedish/Finnish/Hungarian.
138    SwedishFinnishHungarian,
139    /// `011` — Italian.
140    Italian,
141    /// `100` — French.
142    French,
143    /// `101` — Portuguese/Spanish.
144    PortugueseSpanish,
145    /// `110` — Czech/Slovak.
146    CzechSlovak,
147    /// Polish (Table 36). Not selectable by C12-C14 at Level 1 (Table 32
148    /// places it in a later group), kept so every Table 36 row is addressable.
149    Polish,
150    /// Rumanian (Table 36); not selectable by C12-C14 at Level 1.
151    Rumanian,
152    /// Turkish (Table 36); not selectable by C12-C14 at Level 1.
153    Turkish,
154    /// Serbian/Croatian/Slovenian (Table 36); not selectable by C12-C14 at
155    /// Level 1.
156    SerbianCroatianSlovenian,
157    /// Estonian (Table 36); not selectable by C12-C14 at Level 1.
158    Estonian,
159    /// Lettish/Lithuanian (Table 36); not selectable by C12-C14 at Level 1.
160    LettishLithuanian,
161    /// `111` — reserved (Table 32's first group defines no option here); the
162    /// raw 3-bit value is retained.
163    Reserved(u8),
164}
165
166impl NationalOption {
167    /// Decode from the packed 3-bit value `(c12 << 2) | (c13 << 1) | c14`.
168    #[must_use]
169    pub fn from_bits(v: u8) -> Self {
170        match v & 0x7 {
171            0 => NationalOption::English,
172            1 => NationalOption::German,
173            2 => NationalOption::SwedishFinnishHungarian,
174            3 => NationalOption::Italian,
175            4 => NationalOption::French,
176            5 => NationalOption::PortugueseSpanish,
177            6 => NationalOption::CzechSlovak,
178            other => NationalOption::Reserved(other),
179        }
180    }
181
182    /// Spec token (issue #204 label convention).
183    #[must_use]
184    pub fn name(&self) -> &'static str {
185        match self {
186            NationalOption::English => "English",
187            NationalOption::German => "German",
188            NationalOption::SwedishFinnishHungarian => "Swedish/Finnish/Hungarian",
189            NationalOption::Italian => "Italian",
190            NationalOption::French => "French",
191            NationalOption::PortugueseSpanish => "Portuguese/Spanish",
192            NationalOption::CzechSlovak => "Czech/Slovak",
193            NationalOption::Polish => "Polish",
194            NationalOption::Rumanian => "Rumanian",
195            NationalOption::Turkish => "Turkish",
196            NationalOption::SerbianCroatianSlovenian => "Serbian/Croatian/Slovenian",
197            NationalOption::Estonian => "Estonian",
198            NationalOption::LettishLithuanian => "Lettish/Lithuanian",
199            NationalOption::Reserved(_) => "reserved",
200        }
201    }
202}
203broadcast_common::impl_spec_display!(NationalOption, Reserved);
204
205/// Decode one Latin G0 (Table 35) code position (`0x20`-`0x7F`) to its
206/// display character, applying the Table 36 national-option substitution of
207/// `option` at the 13 reserved positions. The glyph chart is an image in the
208/// spec; the reading is recorded in
209/// `private/specs-verified/dvb/timed-metadata/teletext-national-options.md`.
210///
211/// Codes below `0x20` are Level-1 spacing attributes (clause 12.2); each
212/// occupies a character cell displayed as a SPACE, so they decode to a space
213/// here (the box attributes are interpreted by the row renderer, not here).
214/// Code `0x7F` is the Level-1 "reserved position" full block (Table 35
215/// note 4), rendered as `'\u{2588}'` (FULL BLOCK). A [`NationalOption::Reserved`]
216/// option substitutes nothing and yields the base ASCII glyph.
217#[must_use]
218pub fn latin_g0_char(code: u8, option: NationalOption) -> char {
219    let code = code & CODE_MASK_7BIT;
220    if code < FIRST_GRAPHIC_CODE {
221        return ' ';
222    }
223    if code == FULL_BLOCK_CODE {
224        return '\u{2588}';
225    }
226    if let Some(subset) = national_subset(option)
227        && let Some(slot) = NATIONAL_POSITIONS.iter().position(|&p| p == code)
228    {
229        return subset[slot];
230    }
231    code as char
232}
233
234const CODE_MASK_7BIT: u8 = 0x7F;
235const FIRST_GRAPHIC_CODE: u8 = 0x20;
236const FULL_BLOCK_CODE: u8 = 0x7F;
237
238/// Spacing attribute 0/A, End Box (EN 300 706 clause 12.2, Table 26).
239const END_BOX: u8 = 0x0A;
240/// Spacing attribute 0/B, Start Box (EN 300 706 clause 12.2, Table 26).
241const START_BOX: u8 = 0x0B;
242
243/// The 13 Table 35 code positions a national option replaces, in the column
244/// order of Table 36 (2/3 2/4 4/0 5/B 5/C 5/D 5/E 5/F 6/0 7/B 7/C 7/D 7/E).
245const NATIONAL_POSITIONS: [u8; 13] = [
246    0x23, 0x24, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x7B, 0x7C, 0x7D, 0x7E,
247];
248
249type NationalSubset = [char; 13];
250
251const CZECH_SLOVAK: NationalSubset = [
252    '#', 'ů', 'č', 'ť', 'ž', 'ý', 'í', 'ř', 'é', 'á', 'ě', 'ú', 'š',
253];
254const ENGLISH: NationalSubset = [
255    '£', '$', '@', '←', '½', '→', '↑', '#', '\u{2015}', '¼', '\u{2016}', '¾', '÷',
256];
257const ESTONIAN: NationalSubset = [
258    '#', 'õ', 'Š', 'Ä', 'Ö', 'Ž', 'Ü', 'Õ', 'š', 'ä', 'ö', 'ž', 'ü',
259];
260const FRENCH: NationalSubset = [
261    'é', 'ï', 'à', 'ë', 'ê', 'ù', 'î', '#', 'è', 'â', 'ô', 'û', 'ç',
262];
263const GERMAN: NationalSubset = [
264    '#', '$', '§', 'Ä', 'Ö', 'Ü', '^', '_', '°', 'ä', 'ö', 'ü', 'ß',
265];
266const ITALIAN: NationalSubset = [
267    '£', '$', 'é', '°', 'ç', '→', '↑', '#', 'ù', 'à', 'ò', 'è', 'ì',
268];
269const LETTISH_LITHUANIAN: NationalSubset = [
270    '#', '$', 'Š', 'ė', 'ę', 'Ž', 'č', 'ū', 'š', 'ą', 'ų', 'ž', 'į',
271];
272const POLISH: NationalSubset = [
273    '#', 'ń', 'ą', 'Ż', 'Ś', 'Ł', 'ć', 'ó', 'ę', 'ż', 'ś', 'ł', 'ź',
274];
275const PORTUGUESE_SPANISH: NationalSubset = [
276    'ç', '$', '¡', 'á', 'é', 'í', 'ó', 'ú', '¿', 'ü', 'ñ', 'è', 'à',
277];
278const RUMANIAN: NationalSubset = [
279    '#', '¤', 'Ţ', 'Â', 'Ş', 'Ă', 'Î', 'ı', 'ţ', 'â', 'ş', 'ă', 'î',
280];
281const SERBIAN_CROATIAN_SLOVENIAN: NationalSubset = [
282    '#', 'Ë', 'Č', 'Ć', 'Ž', 'Đ', 'Š', 'ë', 'č', 'ć', 'ž', 'đ', 'š',
283];
284const SWEDISH_FINNISH_HUNGARIAN: NationalSubset = [
285    '#', '¤', 'É', 'Ä', 'Ö', 'Å', 'Ü', '_', 'é', 'ä', 'ö', 'å', 'ü',
286];
287const TURKISH: NationalSubset = [
288    '\u{20BA}', 'ğ', 'İ', 'Ş', 'Ö', 'Ç', 'Ü', 'Ğ', 'ı', 'ş', 'ö', 'ç', 'ü',
289];
290
291fn national_subset(option: NationalOption) -> Option<&'static NationalSubset> {
292    Some(match option {
293        NationalOption::English => &ENGLISH,
294        NationalOption::German => &GERMAN,
295        NationalOption::SwedishFinnishHungarian => &SWEDISH_FINNISH_HUNGARIAN,
296        NationalOption::Italian => &ITALIAN,
297        NationalOption::French => &FRENCH,
298        NationalOption::PortugueseSpanish => &PORTUGUESE_SPANISH,
299        NationalOption::CzechSlovak => &CZECH_SLOVAK,
300        NationalOption::Polish => &POLISH,
301        NationalOption::Rumanian => &RUMANIAN,
302        NationalOption::Turkish => &TURKISH,
303        NationalOption::SerbianCroatianSlovenian => &SERBIAN_CROATIAN_SLOVENIAN,
304        NationalOption::Estonian => &ESTONIAN,
305        NationalOption::LettishLithuanian => &LETTISH_LITHUANIAN,
306        NationalOption::Reserved(_) => return None,
307    })
308}
309
310/// The magazine + row number packet address prefix common to every Teletext
311/// packet (ETSI EN 300 706 §7.1.2): 2 bytes, both Hamming-8/4 coded.
312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
313pub struct PacketAddress {
314    /// Magazine number, `1..=8` (a packet address magazine field of `0`
315    /// denotes magazine 8 — §3, "magazine number 8").
316    pub magazine: u8,
317    /// Packet number `Y`, `0..=31` (`0` = page header, `1..=25` = display
318    /// rows, `26..=31` = non-displayable enhancement packets).
319    pub row: u8,
320}
321
322/// Decode the 2-byte packet address prefix (`txt_data_block[0..2]` of a
323/// [`dvb_vbi::TeletextDataField`] — EN 300 706 bytes 4-5, since
324/// `txt_data_block` starts after the clock-run-in/framing-code).
325///
326/// Returns `None` if either byte is an uncorrectable (double-bit-error)
327/// Hamming-8/4 byte; the packet is then silently ignored by
328/// `PageAssembler` (a robustness choice, not a spec requirement).
329#[must_use]
330pub fn decode_packet_address(b4: u8, b5: u8) -> Option<PacketAddress> {
331    let n4 = decode_hamming_8_4(b4)?;
332    let n5 = decode_hamming_8_4(b5)?;
333    let mag_field = n4 & 0x7;
334    let magazine = if mag_field == 0 { 8 } else { mag_field };
335    let y0 = (n4 >> 3) & 1;
336    let row = y0 | (n5 << 1);
337    Some(PacketAddress { magazine, row })
338}
339
340/// A decoded page header packet (`Y = 0`, ETSI EN 300 706 §9.3.1): page
341/// address, sub-code, and all eleven control bits (Table 2).
342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
343pub struct PageHeader {
344    /// Page number, `Pt << 4 | Pu` (§9.3.1.1; both nibbles `0x0`-`0xF`).
345    pub page: u8,
346    /// Page sub-code element S1 (§9.3.1.2, byte 8; `0x0`-`0xF`).
347    pub s1: u8,
348    /// Page sub-code element S2 (byte 9 bits 2/4/6; `0x0`-`0x7`).
349    pub s2: u8,
350    /// Page sub-code element S3 (byte 10; `0x0`-`0xF`).
351    pub s3: u8,
352    /// Page sub-code element S4 (byte 11 bits 2/4; `0x0`-`0x3`).
353    pub s4: u8,
354    /// C4 Erase Page.
355    pub erase_page: bool,
356    /// C5 Newsflash.
357    pub newsflash: bool,
358    /// C6 Subtitle.
359    pub subtitle: bool,
360    /// C7 Suppress Header (row 0 not displayed).
361    pub suppress_header: bool,
362    /// C8 Update Indicator.
363    pub update_indicator: bool,
364    /// C9 Interrupted Sequence.
365    pub interrupted_sequence: bool,
366    /// C10 Inhibit Display (rows 1-24 not displayed).
367    pub inhibit_display: bool,
368    /// C11 Magazine Serial (`true` = serial mode, `false` = parallel mode).
369    pub magazine_serial: bool,
370    /// C12/C13/C14 National Option Character Subset.
371    pub national_option: NationalOption,
372}
373
374impl PageHeader {
375    /// Decode a page header from the 8 Hamming-8/4 bytes at
376    /// `txt_data_block[2..10]` (EN 300 706 bytes 6-13 — the 2 bytes of
377    /// packet address precede these). Returns `None` if any of the 8 bytes
378    /// is an uncorrectable Hamming-8/4 byte.
379    #[must_use]
380    pub fn parse(txt_data_block: &[u8; 42]) -> Option<PageHeader> {
381        let page_units = decode_hamming_8_4(txt_data_block[2])?;
382        let page_tens = decode_hamming_8_4(txt_data_block[3])?;
383        let s1 = decode_hamming_8_4(txt_data_block[4])?;
384        let n_s2_c4 = decode_hamming_8_4(txt_data_block[5])?;
385        let s3 = decode_hamming_8_4(txt_data_block[6])?;
386        let n_s4_c5_c6 = decode_hamming_8_4(txt_data_block[7])?;
387        let n_c7_c10 = decode_hamming_8_4(txt_data_block[8])?;
388        let n_c11_c14 = decode_hamming_8_4(txt_data_block[9])?;
389
390        let s2 = n_s2_c4 & 0x7;
391        let c4 = (n_s2_c4 >> 3) & 1;
392        let s4 = n_s4_c5_c6 & 0x3;
393        let c5 = (n_s4_c5_c6 >> 2) & 1;
394        let c6 = (n_s4_c5_c6 >> 3) & 1;
395        let c7 = n_c7_c10 & 1;
396        let c8 = (n_c7_c10 >> 1) & 1;
397        let c9 = (n_c7_c10 >> 2) & 1;
398        let c10 = (n_c7_c10 >> 3) & 1;
399        let c11 = n_c11_c14 & 1;
400        let c12 = (n_c11_c14 >> 1) & 1;
401        let c13 = (n_c11_c14 >> 2) & 1;
402        let c14 = (n_c11_c14 >> 3) & 1;
403
404        Some(PageHeader {
405            page: (page_tens << 4) | page_units,
406            s1,
407            s2,
408            s3,
409            s4,
410            erase_page: c4 != 0,
411            newsflash: c5 != 0,
412            subtitle: c6 != 0,
413            suppress_header: c7 != 0,
414            update_indicator: c8 != 0,
415            interrupted_sequence: c9 != 0,
416            inhibit_display: c10 != 0,
417            magazine_serial: c11 != 0,
418            national_option: NationalOption::from_bits((c12 << 2) | (c13 << 1) | c14),
419        })
420    }
421}
422
423const ROW_LEN: usize = 40;
424const DISPLAY_ROWS: usize = 24;
425const ROW_PAYLOAD_START: usize = 2;
426
427/// One display row's 40 columns after odd-parity decode (§8.1): `Some` holds
428/// the 7-bit code, `None` a byte that failed its parity check.
429type RowCodes = [Option<u8>; ROW_LEN];
430
431fn decode_row_codes(txt_data_block: &[u8; 42]) -> RowCodes {
432    let mut codes = [None; ROW_LEN];
433    for (slot, &b) in codes
434        .iter_mut()
435        .zip(&txt_data_block[ROW_PAYLOAD_START..ROW_PAYLOAD_START + ROW_LEN])
436    {
437        *slot = broadcast_common::parity::strip_parity(b);
438    }
439    codes
440}
441
442fn push_code(out: &mut String, code: Option<u8>, option: NationalOption) {
443    match code {
444        Some(code) => out.push(latin_g0_char(code, option)),
445        None => out.push('\u{FFFD}'),
446    }
447}
448
449/// Render one row. On a boxed (C5 newsflash / C6 subtitle) page only the
450/// columns after a Start Box and before the next End Box are displayed
451/// (clause 12.2, Table 26, attributes 0/A and 0/B: "characters outside this
452/// area are not displayed"; both reset at the start of a row); the two
453/// attribute cells and the padding at the box edges are not text and are
454/// trimmed. On any other page the whole row is rendered, trailing spaces
455/// trimmed.
456fn render_row(codes: &RowCodes, option: NationalOption, boxed_page: bool) -> String {
457    let mut out = String::with_capacity(ROW_LEN);
458    if boxed_page {
459        let mut in_box = false;
460        for &code in codes {
461            match code {
462                Some(START_BOX) => in_box = true,
463                Some(END_BOX) => in_box = false,
464                _ if in_box => push_code(&mut out, code, option),
465                _ => {}
466            }
467        }
468        out.trim().into()
469    } else {
470        for &code in codes {
471            push_code(&mut out, code, option);
472        }
473        out.trim_end().into()
474    }
475}
476
477/// Accumulates one tracked `(magazine, page)`'s row packets into display
478/// text (ETSI EN 300 706 §7.2: a page's body is its header packet plus all
479/// subsequent `Y=1..=24` packets in the same magazine, up to the next
480/// header). Crate-private: the public surface is
481/// [`crate::webvtt::TeletextCueExtractor`].
482pub(crate) struct PageAssembler {
483    magazine: u8,
484    page: u8,
485    /// Whether the magazine's most-recently-seen header packet matched
486    /// `(magazine, page)` — row packets in a magazine belong to whichever
487    /// page was last headed, per §7.2.1.
488    active: bool,
489    inhibited: bool,
490    boxed_page: bool,
491    national_option: NationalOption,
492    /// Index `0` = row 1 .. index `23` = row 24.
493    rows: [Option<RowCodes>; DISPLAY_ROWS],
494}
495
496impl PageAssembler {
497    pub(crate) fn new(magazine: u8, page: u8) -> Self {
498        PageAssembler {
499            magazine,
500            page,
501            active: false,
502            inhibited: false,
503            boxed_page: false,
504            national_option: NationalOption::English,
505            rows: [None; DISPLAY_ROWS],
506        }
507    }
508
509    pub(crate) fn push(&mut self, field: &dvb_vbi::TeletextDataField) {
510        // EN 300 706 transmits each byte of the magazine/packet address and
511        // data block LSB-first (§7.1.2/§8.1/§8.2's "bslbf" fields, EN 301 775
512        // §4.5) — `txt_data_block_logical()` undoes that wire order; run
513        // Hamming-8/4 / odd-parity decode (which assume the spec's bit order
514        // directly) against its output, not the raw `txt_data_block`.
515        let block: [u8; 42] = field.txt_data_block_logical();
516        let block = &block;
517        let Some(addr) = decode_packet_address(block[0], block[1]) else {
518            return;
519        };
520        if addr.magazine != self.magazine {
521            return;
522        }
523        if addr.row == 0 {
524            let Some(header) = PageHeader::parse(block) else {
525                return;
526            };
527            self.active = header.page == self.page;
528            if self.active {
529                if header.erase_page {
530                    self.rows = [None; DISPLAY_ROWS];
531                }
532                self.inhibited = header.inhibit_display;
533                self.boxed_page = header.subtitle || header.newsflash;
534                self.national_option = header.national_option;
535            }
536            return;
537        }
538        if !self.active || usize::from(addr.row) > DISPLAY_ROWS {
539            return;
540        }
541        self.rows[usize::from(addr.row) - 1] = Some(decode_row_codes(block));
542    }
543
544    /// The currently displayed subtitle text: non-empty rows 1-24 as rendered
545    /// by [`render_row`], in row order, joined with `\n`. Empty if the page
546    /// is currently inhibited (C10) or no row is non-empty.
547    pub(crate) fn display_text(&self) -> String {
548        if self.inhibited {
549            return String::new();
550        }
551        let lines: Vec<String> = self
552            .rows
553            .iter()
554            .flatten()
555            .map(|codes| render_row(codes, self.national_option, self.boxed_page))
556            .filter(|r| !r.is_empty())
557            .collect();
558        lines.join("\n")
559    }
560}
561
562#[cfg(test)]
563mod tests {
564    use super::*;
565    use alloc::vec;
566
567    #[test]
568    fn hamming_8_4_round_trips_all_16_nibbles() {
569        for nibble in 0u8..16 {
570            let byte = encode_hamming_8_4(nibble);
571            assert_eq!(
572                decode_hamming_8_4(byte),
573                Some(nibble),
574                "nibble {nibble:#X} round-trip"
575            );
576        }
577    }
578
579    #[test]
580    fn hamming_8_4_corrects_every_single_bit_error() {
581        for nibble in 0u8..16 {
582            let byte = encode_hamming_8_4(nibble);
583            for bit in 0..8u8 {
584                let corrupted = byte ^ (1 << bit);
585                assert_eq!(
586                    decode_hamming_8_4(corrupted),
587                    Some(nibble),
588                    "nibble {nibble:#X}, single-bit error at bit {bit} must be corrected"
589                );
590            }
591        }
592    }
593
594    #[test]
595    fn hamming_8_4_rejects_double_bit_errors() {
596        // Flip 2 bits of a known-good codeword: per §8.2, "double bit errors
597        // can be detected" (rejected, not silently accepted as some other
598        // nibble).
599        let byte = encode_hamming_8_4(0b0110);
600        let corrupted = byte ^ 0b0000_0011; // flip bits 0 and 1
601        assert_eq!(
602            decode_hamming_8_4(corrupted),
603            None,
604            "a double-bit error must be rejected, not miscorrected"
605        );
606    }
607
608    #[test]
609    fn hamming_manual_cross_check_against_spec_encoding_equations() {
610        // Manually compute nibble 0b0110 (D1=0,D2=1,D3=1,D4=0) by hand from
611        // §8.2's stated equations, cross-checking `encode_hamming_8_4`:
612        // P1 = 1^D1^D3^D4 = 1^0^1^0 = 0
613        // P2 = 1^D1^D2^D4 = 1^0^1^0 = 0
614        // P3 = 1^D1^D2^D3 = 1^0^1^1 = 1
615        // P4 = 1^P1^D1^P2^D2^P3^D3^D4 = 1^0^0^0^1^1^1^0 = 0
616        // wire bits (transmission order P1 D1 P2 D2 P3 D3 P4 D4) = 0 0 0 1 1 1 0 0
617        // packed LSB-first: bit1=P1=0,bit2=D1=0,bit3=P2=0,bit4=D2=1,
618        //                    bit5=P3=1,bit6=D3=1,bit7=P4=0,bit8=D4=0
619        // byte = 0b0011_1000 = 0x38
620        assert_eq!(encode_hamming_8_4(0b0110), 0x38);
621        assert_eq!(decode_hamming_8_4(0x38), Some(0b0110));
622    }
623
624    #[test]
625    fn odd_parity_round_trips_all_128_values() {
626        for data7 in 0u8..128 {
627            let byte = broadcast_common::parity::set_odd_parity(data7);
628            assert_eq!(
629                byte.count_ones() % 2,
630                1,
631                "encoded byte must have odd parity"
632            );
633            assert_eq!(broadcast_common::parity::strip_parity(byte), Some(data7));
634        }
635    }
636
637    #[test]
638    fn odd_parity_detects_but_does_not_correct() {
639        let byte = broadcast_common::parity::set_odd_parity(b'H' & 0x7F);
640        let corrupted = byte ^ 0x01; // flip one data bit -> even parity
641        assert_eq!(
642            broadcast_common::parity::strip_parity(corrupted),
643            None,
644            "odd parity only detects errors; a corrupted byte must not decode"
645        );
646    }
647
648    #[test]
649    fn latin_g0_base_matches_ascii_outside_reserved_positions() {
650        for code in 0x20u8..0x7F {
651            let is_reserved = matches!(
652                code,
653                0x23 | 0x24
654                    | 0x40
655                    | 0x5B
656                    | 0x5C
657                    | 0x5D
658                    | 0x5E
659                    | 0x5F
660                    | 0x60
661                    | 0x7B
662                    | 0x7C
663                    | 0x7D
664                    | 0x7E
665            );
666            if !is_reserved {
667                assert_eq!(
668                    latin_g0_char(code, NationalOption::English),
669                    code as char,
670                    "non-reserved position {code:#04X} must match base ASCII"
671                );
672            }
673        }
674    }
675
676    #[test]
677    fn latin_g0_english_substitutions_verified_against_table_36() {
678        // Values read directly from ETSI EN 300 706 Table 36's "English" row
679        // (bitmap glyph chart, visually verified — see private/specs-verified/dvb/timed-metadata/teletext-subtitles.md).
680        assert_eq!(latin_g0_char(0x23, NationalOption::English), '£');
681        assert_eq!(latin_g0_char(0x24, NationalOption::English), '$');
682        assert_eq!(latin_g0_char(0x40, NationalOption::English), '@');
683        assert_eq!(latin_g0_char(0x5B, NationalOption::English), '←');
684        assert_eq!(latin_g0_char(0x5C, NationalOption::English), '½');
685        assert_eq!(latin_g0_char(0x5D, NationalOption::English), '→');
686        assert_eq!(latin_g0_char(0x5E, NationalOption::English), '↑');
687        assert_eq!(latin_g0_char(0x5F, NationalOption::English), '#');
688        assert_eq!(latin_g0_char(0x7B, NationalOption::English), '¼');
689        assert_eq!(latin_g0_char(0x7C, NationalOption::English), '‖');
690        assert_eq!(latin_g0_char(0x7D, NationalOption::English), '¾');
691        assert_eq!(latin_g0_char(0x7E, NationalOption::English), '÷');
692    }
693
694    #[test]
695    fn latin_g0_reserved_option_substitutes_nothing() {
696        assert_eq!(latin_g0_char(0x24, NationalOption::Reserved(7)), '$');
697        assert_eq!(latin_g0_char(0x5B, NationalOption::Reserved(7)), '[');
698    }
699
700    #[test]
701    fn latin_g0_other_rows_of_table_36() {
702        let row = |option| -> String {
703            NATIONAL_POSITIONS
704                .iter()
705                .map(|&c| latin_g0_char(c, option))
706                .collect()
707        };
708        assert_eq!(row(NationalOption::German), "#$§ÄÖÜ^_°äöüß");
709        assert_eq!(row(NationalOption::Italian), "£$é°ç→↑#ùàòèì");
710        assert_eq!(row(NationalOption::PortugueseSpanish), "ç$¡áéíóú¿üñèà");
711        assert_eq!(row(NationalOption::Turkish), "\u{20BA}ğİŞÖÇÜĞışöçü");
712    }
713
714    #[test]
715    fn latin_g0_french_row_of_table_36() {
716        let got: String = NATIONAL_POSITIONS
717            .iter()
718            .map(|&c| latin_g0_char(c, NationalOption::French))
719            .collect();
720        assert_eq!(got, "éïàëêùî#èâôûç");
721    }
722
723    #[test]
724    fn page_assembler_applies_the_header_national_option() {
725        let mut asm = PageAssembler::new(8, 0x88);
726        asm.push(&field_from_block(
727            build_header_block(8, 0x88, true, true, false, NationalOption::French),
728            0,
729        ));
730        let row = [
731            START_BOX, START_BOX, b'd', 0x23, b'p', b'a', b's', b's', b'e', b'r', END_BOX,
732        ];
733        asm.push(&field_from_block(build_row_bytes(8, 20, &row), 20));
734        assert_eq!(asm.display_text(), "dépasser");
735    }
736
737    #[test]
738    fn boxed_page_shows_only_text_between_start_box_and_end_box() {
739        let mut asm = PageAssembler::new(8, 0x88);
740        asm.push(&field_from_block(
741            build_header_block(8, 0x88, true, true, false, NationalOption::English),
742            0,
743        ));
744        let mut row = vec![b' ', b' ', b' ', b'x', START_BOX, START_BOX, b' '];
745        row.extend_from_slice(b"Hi there");
746        row.extend_from_slice(&[b' ', END_BOX, END_BOX, b'y', b'z']);
747        asm.push(&field_from_block(build_row_bytes(8, 20, &row), 20));
748        assert_eq!(asm.display_text(), "Hi there");
749    }
750
751    #[test]
752    fn row_without_start_box_is_not_displayed_on_a_boxed_page() {
753        let mut asm = PageAssembler::new(8, 0x88);
754        asm.push(&field_from_block(
755            build_header_block(8, 0x88, true, true, false, NationalOption::English),
756            0,
757        ));
758        asm.push(&field_from_block(build_row_block(8, 20, "outside"), 20));
759        assert_eq!(asm.display_text(), "");
760    }
761
762    #[test]
763    fn box_attributes_are_ignored_on_a_page_that_is_not_boxed() {
764        let mut asm = PageAssembler::new(8, 0x88);
765        asm.push(&field_from_block(
766            build_header_block(8, 0x88, true, false, false, NationalOption::English),
767            0,
768        ));
769        asm.push(&field_from_block(build_row_block(8, 20, "plain"), 20));
770        assert_eq!(asm.display_text(), "plain");
771    }
772
773    #[test]
774    fn control_codes_render_as_space_and_0x7f_as_full_block() {
775        assert_eq!(latin_g0_char(0x00, NationalOption::English), ' ');
776        assert_eq!(latin_g0_char(0x1F, NationalOption::English), ' ');
777        assert_eq!(latin_g0_char(0x7F, NationalOption::English), '\u{2588}');
778    }
779
780    #[test]
781    fn national_option_decodes_all_8_values() {
782        assert_eq!(NationalOption::from_bits(0), NationalOption::English);
783        assert_eq!(NationalOption::from_bits(1), NationalOption::German);
784        assert_eq!(
785            NationalOption::from_bits(2),
786            NationalOption::SwedishFinnishHungarian
787        );
788        assert_eq!(NationalOption::from_bits(3), NationalOption::Italian);
789        assert_eq!(NationalOption::from_bits(4), NationalOption::French);
790        assert_eq!(
791            NationalOption::from_bits(5),
792            NationalOption::PortugueseSpanish
793        );
794        assert_eq!(NationalOption::from_bits(6), NationalOption::CzechSlovak);
795        assert_eq!(NationalOption::from_bits(7), NationalOption::Reserved(7));
796    }
797
798    #[test]
799    fn packet_address_decodes_magazine_0_as_magazine_8() {
800        // magazine field = 0 (nibble low 3 bits = 0), row = 0.
801        let b4 = encode_hamming_8_4(0); // magazine field 0, Y bit0 = 0
802        let b5 = encode_hamming_8_4(0); // Y bits 1-4 = 0
803        let addr = decode_packet_address(b4, b5).unwrap();
804        assert_eq!(
805            addr.magazine, 8,
806            "magazine field 0 must decode as magazine 8"
807        );
808        assert_eq!(addr.row, 0);
809    }
810
811    #[test]
812    fn packet_address_decodes_magazine_and_row() {
813        // magazine field = 3, Y = 17 (0b10001): Y bit0=1 (goes in byte4 D4),
814        // Y bits1-4 = 0b1000 (goes in byte5 nibble).
815        let b4 = encode_hamming_8_4(0b1_011); // D1..D3=011(mag=3), D4=1(Y bit0)
816        let b5 = encode_hamming_8_4(0b1000); // Y bits1..4 = 1000
817        let addr = decode_packet_address(b4, b5).unwrap();
818        assert_eq!(addr.magazine, 3);
819        assert_eq!(addr.row, 17);
820    }
821
822    #[test]
823    fn page_assembler_tracks_target_page_and_ignores_others() {
824        let mut asm = PageAssembler::new(8, 0x88);
825
826        // Header for magazine 8, page 0x88, C6 subtitle set, C4 erase set.
827        let header_block = build_header_block(8, 0x88, true, true, false, NationalOption::English);
828        asm.push(&field_from_block(header_block, 0));
829        assert!(asm.active);
830
831        // Row 20: "HI"
832        let row_block = build_boxed_row(8, 20, "HI");
833        asm.push(&field_from_block(row_block, 20));
834        assert_eq!(asm.display_text(), "HI");
835
836        // A row for a DIFFERENT magazine must be ignored.
837        let other_mag_row = build_boxed_row(1, 21, "IGNORED");
838        asm.push(&field_from_block(other_mag_row, 21));
839        assert_eq!(
840            asm.display_text(),
841            "HI",
842            "other magazine's row must be ignored"
843        );
844
845        // A header for a different page in the same magazine deactivates us.
846        let other_page_header =
847            build_header_block(8, 0x01, true, false, false, NationalOption::English);
848        asm.push(&field_from_block(other_page_header, 0));
849        assert!(!asm.active);
850        let row_after_switch = build_boxed_row(8, 21, "SHOULD NOT APPEAR");
851        asm.push(&field_from_block(row_after_switch, 21));
852        assert_eq!(
853            asm.display_text(),
854            "HI",
855            "rows while another page is active must not be stored"
856        );
857
858        // Switch back with erase -> old row content is cleared.
859        let back_header = build_header_block(8, 0x88, true, true, false, NationalOption::English);
860        asm.push(&field_from_block(back_header, 0));
861        assert_eq!(asm.display_text(), "", "erase_page must clear old rows");
862    }
863
864    #[test]
865    fn page_assembler_inhibit_display_blanks_text() {
866        let mut asm = PageAssembler::new(8, 0x88);
867        asm.push(&field_from_block(
868            build_header_block(8, 0x88, true, true, false, NationalOption::English),
869            0,
870        ));
871        asm.push(&field_from_block(build_boxed_row(8, 20, "HELLO"), 20));
872        assert_eq!(asm.display_text(), "HELLO");
873
874        // A header with C10 (inhibit_display) set, but C4 (erase) NOT set,
875        // must blank the display while leaving the row buffer itself
876        // populated (proves inhibit is a display-time gate, not a clear).
877        asm.push(&field_from_block(
878            build_header_block(8, 0x88, false, false, true, NationalOption::English),
879            0,
880        ));
881        assert_eq!(
882            asm.display_text(),
883            "",
884            "inhibit_display must blank the text"
885        );
886        assert!(
887            asm.rows[19].is_some(),
888            "inhibit_display must not clear the underlying row buffer"
889        );
890    }
891
892    /// Test-only helper: build a 42-byte `txt_data_block` for a page header
893    /// packet (`Y=0`) at `(magazine, page)` with the given C4/C6/C10 bits.
894    /// Uses [`encode_hamming_8_4`] — the same function proven correct by the
895    /// round-trip and manual-cross-check tests above — to build spec-valid
896    /// wire bytes (this project's established "construct from verified spec
897    /// encode rules" fixture fallback; see `private/specs-verified/dvb/timed-metadata/teletext-subtitles.md`).
898    pub(super) fn build_header_block(
899        magazine: u8,
900        page: u8,
901        erase_page: bool,
902        subtitle: bool,
903        inhibit_display: bool,
904        option: NationalOption,
905    ) -> [u8; 42] {
906        let mut b = [0u8; 42];
907        let mag_field = if magazine == 8 { 0 } else { magazine };
908        b[0] = encode_hamming_8_4(mag_field); // Y bit0 = 0 (row 0)
909        b[1] = encode_hamming_8_4(0); // Y bits1..4 = 0
910        b[2] = encode_hamming_8_4(page & 0xF); // page units
911        b[3] = encode_hamming_8_4((page >> 4) & 0xF); // page tens
912        b[4] = encode_hamming_8_4(0); // S1 = 0
913        let c4 = u8::from(erase_page);
914        b[5] = encode_hamming_8_4(c4 << 3); // S2=0, C4
915        b[6] = encode_hamming_8_4(0); // S3 = 0
916        let c6 = u8::from(subtitle);
917        b[7] = encode_hamming_8_4(c6 << 3); // S4=0, C5=0, C6
918        let c10 = u8::from(inhibit_display);
919        b[8] = encode_hamming_8_4(c10 << 3); // C7=C8=C9=0, C10
920        let opt_bits = match option {
921            NationalOption::English => 0u8,
922            NationalOption::German => 1,
923            NationalOption::SwedishFinnishHungarian => 2,
924            NationalOption::Italian => 3,
925            NationalOption::French => 4,
926            NationalOption::PortugueseSpanish => 5,
927            NationalOption::CzechSlovak => 6,
928            NationalOption::Reserved(v) => v,
929            other => panic!("{other} has no Level 1 header encoding"),
930        };
931        let c12 = (opt_bits >> 2) & 1;
932        let c13 = (opt_bits >> 1) & 1;
933        let c14 = opt_bits & 1;
934        b[9] = encode_hamming_8_4((c14 << 3) | (c13 << 2) | (c12 << 1)); // C11=0
935        for byte in b.iter_mut().skip(10) {
936            *byte = broadcast_common::parity::set_odd_parity(0x20); // row-0 text: spaces
937        }
938        b
939    }
940
941    /// Test-only helper: build a 42-byte `txt_data_block` for a display row
942    /// packet (`Y=1..=24`) carrying `text` (ASCII only, right-padded with
943    /// spaces to 40 columns), odd-parity encoded per §8.1.
944    pub(super) fn build_row_block(magazine: u8, row: u8, text: &str) -> [u8; 42] {
945        assert!((1..=24).contains(&row));
946        let mut b = [0u8; 42];
947        let mag_field = if magazine == 8 { 0 } else { magazine };
948        let y0 = row & 1;
949        b[0] = encode_hamming_8_4(mag_field | (y0 << 3));
950        b[1] = encode_hamming_8_4(row >> 1);
951        let bytes = text.as_bytes();
952        for i in 0..40usize {
953            let ch = bytes.get(i).copied().unwrap_or(b' ');
954            b[2 + i] = broadcast_common::parity::set_odd_parity(ch & 0x7F);
955        }
956        b
957    }
958
959    /// A row whose text is wrapped in the doubled Start Box / End Box pair a
960    /// subtitle page carries.
961    pub(super) fn build_boxed_row(magazine: u8, row: u8, text: &str) -> [u8; 42] {
962        let mut codes = vec![START_BOX, START_BOX];
963        codes.extend_from_slice(text.as_bytes());
964        codes.extend_from_slice(&[END_BOX, END_BOX]);
965        build_row_bytes(magazine, row, &codes)
966    }
967
968    /// Like [`build_row_block`] but from raw 7-bit codes, so spacing
969    /// attributes can be placed in the row.
970    pub(super) fn build_row_bytes(magazine: u8, row: u8, codes: &[u8]) -> [u8; 42] {
971        assert!((1..=24).contains(&row));
972        let mut b = [0u8; 42];
973        let mag_field = if magazine == 8 { 0 } else { magazine };
974        b[0] = encode_hamming_8_4(mag_field | ((row & 1) << 3));
975        b[1] = encode_hamming_8_4(row >> 1);
976        for i in 0..40usize {
977            let code = codes.get(i).copied().unwrap_or(b' ');
978            b[2 + i] = broadcast_common::parity::set_odd_parity(code & 0x7F);
979        }
980        b
981    }
982
983    pub(super) fn field_from_block(block: [u8; 42], line: u8) -> dvb_vbi::TeletextDataField {
984        // `build_header_block`/`build_row_block` produce the spec's own
985        // (canonical) byte values via `encode_hamming_8_4`/`set_odd_parity`;
986        // reverse each bit to emulate the LSB-first wire bytes `push` now
987        // un-reverses, so these tests exercise the real wire path.
988        dvb_vbi::TeletextDataField {
989            header: dvb_vbi::LineHeader::new(true, line % 24),
990            framing_code: dvb_vbi::FRAMING_CODE_EBU,
991            txt_data_block: block.map(u8::reverse_bits),
992        }
993    }
994}