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