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, §15.1-15.2 national option selection, Table 35/36
6//! Latin G0 character set).
7//!
8//! `dvb-vbi` carries the EN 301 775 VBI PES framing (`TeletextDataField`, a
9//! 42-byte opaque `txt_data_block`) but — by its own module docs — does not
10//! decode EN 300 706 (a large, separate spec covering FEC, character sets and
11//! page composition, not carriage). This module owns that decode, consuming
12//! only `dvb_vbi::TeletextDataField`'s raw bytes:
13//!
14//! - [`decode_hamming_8_4`] / [`encode_hamming_8_4`] — the 4-data-bit +
15//!   4-parity-bit code protecting packet addresses and page header fields
16//!   (§8.2): single-bit errors corrected, double-bit errors rejected.
17//! - [`decode_odd_parity`] / [`encode_odd_parity`] — the 7-data-bit + 1-parity
18//!   code protecting displayable row bytes (§8.1): errors only *detected*
19//!   (odd parity carries no correction capability), rendered as
20//!   `'\u{FFFD}'`.
21//! - [`NationalOption`] — the C12/C13/C14 national option sub-set selector
22//!   (§15.1, Table 32's first ["Latin 0", Level-1-ambiguous] group, the
23//!   interpretation clause 15.1 mandates at presentation Level 1). Every
24//!   variant is decoded and labelled; only [`NationalOption::English`]'s
25//!   character substitutions are applied by [`latin_g0_char`] — others fall
26//!   back to the base/IRV glyph at the 13 nationally-substitutable positions
27//!   (a documented gap: see the crate doc above and `docs/teletext-subtitles.md`).
28//! - [`latin_g0_char`] — Table 35 (Latin G0 Primary Set, identical to 7-bit
29//!   ASCII `0x20`-`0x7F` outside 13 reserved positions) + Table 36 (English
30//!   national option substitutions at those positions).
31//! - [`PacketAddress`] / [`decode_packet_address`] — the magazine + row
32//!   number prefix common to every packet (§7.1.2).
33//! - [`PageHeader`] / [`PageHeader::parse`] — the page header packet (`Y=0`,
34//!   §9.3.1): page number, sub-code, and all eleven control bits (Table 2).
35//! - `PageAssembler` (crate-private) — accumulates a single tracked
36//!   `(magazine, page)`'s row packets (`Y=1..=24`) into display text,
37//!   applying the erase-page (C4) and inhibit-display (C10) control bits;
38//!   drives [`crate::webvtt::TeletextCueExtractor`].
39//!
40//! # Documented losses (first pass, matching this crate's `cc-data`
41//! extractors' lossy-by-design philosophy)
42//!
43//! - **No enhancement packets**: `X/26` (character/attribute overwrite),
44//!   `X/27`/`X/28`/`M/29` (page linking, character-set re-designation, side
45//!   panels, CLUTs) are not processed. Only basic Level-1 page composition
46//!   (`X/0` header + `X/1`-`X/24` display rows) is decoded.
47//! - **No styling**: spacing-attribute control codes (`0x00`-`0x1F`, clause
48//!   12.2 — colour, flash, double-height, box mode, etc.) are rendered as a
49//!   space, not carried into the WebVTT payload as cue styling.
50//! - **Sub-code ignored for page matching**: a page is matched by magazine +
51//!   page number only; multi-subpage rotation (e.g. multi-language subtitle
52//!   variants sharing one page number) is not distinguished.
53//! - **National options**: see [`NationalOption`] above — only English's
54//!   character substitutions are applied.
55use alloc::string::String;
56use alloc::vec::Vec;
57
58/// Decode a Hamming-8/4 protected byte (ETSI EN 300 706 §8.2): bits 1,3,5,7
59/// (transmission order, i.e. the LSB-first bit positions `0x01,0x04,0x10,0x40`)
60/// are the protection bits P1-P4, bits 2,4,6,8 (`0x02,0x08,0x20,0x80`) carry
61/// the 4 data bits D1-D4.
62///
63/// Implemented as a brute-force nearest-codeword search against
64/// [`encode_hamming_8_4`] rather than a hand-derived syndrome table: the code
65/// has minimum distance 4 (a (7,4) Hamming code extended with an overall
66/// parity bit), so a 0-bit-error byte matches its own re-encoding exactly, a
67/// single-bit error matches after flipping exactly one bit, and a
68/// (rejected) double-bit error matches no single flip — this is
69/// mathematically equivalent to the spec's "four odd parity tests A-D"
70/// procedure and was cross-checked against it (see the crate tests below).
71///
72/// Returns the corrected 4-bit data nibble (`D1` in bit 0 .. `D4` in bit 3),
73/// or `None` if the byte is not within Hamming distance 1 of any valid
74/// codeword (an uncorrectable, "double error", byte per §8.2's decode table).
75#[must_use]
76pub fn decode_hamming_8_4(byte: u8) -> Option<u8> {
77    let candidate =
78        (byte >> 1) & 1 | ((byte >> 3) & 1) << 1 | ((byte >> 5) & 1) << 2 | ((byte >> 7) & 1) << 3;
79    if encode_hamming_8_4(candidate) == byte {
80        return Some(candidate);
81    }
82    for bit in 0..8u8 {
83        let flipped = byte ^ (1 << bit);
84        let candidate = (flipped >> 1) & 1
85            | ((flipped >> 3) & 1) << 1
86            | ((flipped >> 5) & 1) << 2
87            | ((flipped >> 7) & 1) << 3;
88        if encode_hamming_8_4(candidate) == flipped {
89            return Some(candidate);
90        }
91    }
92    None
93}
94
95/// Encode a 4-bit data nibble (`D1` in bit 0 .. `D4` in bit 3) as a
96/// Hamming-8/4 protected byte, per the ETSI EN 300 706 §8.2 encoding
97/// equations:
98///
99/// ```text
100/// P1 = 1 ⊕ D1 ⊕ D3 ⊕ D4
101/// P2 = 1 ⊕ D1 ⊕ D2 ⊕ D4
102/// P3 = 1 ⊕ D1 ⊕ D2 ⊕ D3
103/// P4 = 1 ⊕ P1 ⊕ D1 ⊕ P2 ⊕ D2 ⊕ P3 ⊕ D3 ⊕ D4
104/// ```
105///
106/// with wire bit order (transmission order, LSB first) `P1 D1 P2 D2 P3 D3 P4 D4`.
107/// Only the low 4 bits of `nibble` are used.
108#[must_use]
109pub fn encode_hamming_8_4(nibble: u8) -> u8 {
110    let d1 = nibble & 1;
111    let d2 = (nibble >> 1) & 1;
112    let d3 = (nibble >> 2) & 1;
113    let d4 = (nibble >> 3) & 1;
114    let p1 = 1 ^ d1 ^ d3 ^ d4;
115    let p2 = 1 ^ d1 ^ d2 ^ d4;
116    let p3 = 1 ^ d1 ^ d2 ^ d3;
117    let p4 = 1 ^ p1 ^ d1 ^ p2 ^ d2 ^ p3 ^ d3 ^ d4;
118    p1 | (d1 << 1) | (p2 << 2) | (d2 << 3) | (p3 << 4) | (d3 << 5) | (p4 << 6) | (d4 << 7)
119}
120
121/// Decode an odd-parity protected byte (ETSI EN 300 706 §8.1): bit 8 (the
122/// MSB, `0x80`) is the parity bit, bits 1-7 (`0x7F`) carry the 7 data bits.
123/// Odd parity **detects but cannot correct** single-bit errors (unlike
124/// Hamming-8/4): returns `None` on any parity mismatch.
125///
126/// Returns the 7-bit data value, or `None` if the byte does not have odd
127/// parity (an even count of set bits).
128#[must_use]
129pub fn decode_odd_parity(byte: u8) -> Option<u8> {
130    broadcast_common::parity::strip_parity(byte)
131}
132
133/// Encode a 7-bit data value with odd parity in bit 8 (MSB), per ETSI
134/// EN 300 706 §8.1. Only the low 7 bits of `data7` are used.
135#[must_use]
136pub fn encode_odd_parity(data7: u8) -> u8 {
137    broadcast_common::parity::set_odd_parity(data7)
138}
139
140/// The C12/C13/C14 "National Option Character Subset" selector (ETSI
141/// EN 300 706 Table 2, page header control bits) — decoded per Table 32's
142/// first group (`0000XXX`, "Latin 0"), which clause 15.1 states is the
143/// interpretation at presentation Level 1 ("the national option sub-set in
144/// use on the page is defined by the C12, C13 and C14 control bits in the
145/// page header alone").
146///
147/// Only [`NationalOption::English`]'s character substitutions are applied by
148/// [`latin_g0_char`]; the other variants are decoded and labelled (spec
149/// fidelity — every value of this 3-bit field has a name) but fall back to
150/// the base Latin G0 glyph at the 13 nationally-substitutable positions, a
151/// documented gap (see the module docs and `docs/teletext-subtitles.md`).
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
154#[non_exhaustive]
155pub enum NationalOption {
156    /// `000` — English. The only option whose Table 36 substitutions are
157    /// implemented (see [`latin_g0_char`]).
158    English,
159    /// `001` — German.
160    German,
161    /// `010` — Swedish/Finnish/Hungarian.
162    SwedishFinnishHungarian,
163    /// `011` — Italian.
164    Italian,
165    /// `100` — French.
166    French,
167    /// `101` — Portuguese/Spanish.
168    PortugueseSpanish,
169    /// `110` — Czech/Slovak.
170    CzechSlovak,
171    /// `111` — reserved (Table 32's first group defines no option here); the
172    /// raw 3-bit value is retained.
173    Reserved(u8),
174}
175
176impl NationalOption {
177    /// Decode from the packed 3-bit value `(c12 << 2) | (c13 << 1) | c14`.
178    #[must_use]
179    pub fn from_bits(v: u8) -> Self {
180        match v & 0x7 {
181            0 => NationalOption::English,
182            1 => NationalOption::German,
183            2 => NationalOption::SwedishFinnishHungarian,
184            3 => NationalOption::Italian,
185            4 => NationalOption::French,
186            5 => NationalOption::PortugueseSpanish,
187            6 => NationalOption::CzechSlovak,
188            other => NationalOption::Reserved(other),
189        }
190    }
191
192    /// Spec token (issue #204 label convention).
193    #[must_use]
194    pub fn name(&self) -> &'static str {
195        match self {
196            NationalOption::English => "English",
197            NationalOption::German => "German",
198            NationalOption::SwedishFinnishHungarian => "Swedish/Finnish/Hungarian",
199            NationalOption::Italian => "Italian",
200            NationalOption::French => "French",
201            NationalOption::PortugueseSpanish => "Portuguese/Spanish",
202            NationalOption::CzechSlovak => "Czech/Slovak",
203            NationalOption::Reserved(_) => "reserved",
204        }
205    }
206}
207broadcast_common::impl_spec_display!(NationalOption, Reserved);
208
209/// Decode one Latin G0 (Table 35) code position (`0x20`-`0x7F`) to its
210/// display character, applying English (Table 36) national-option
211/// substitutions at the 13 reserved positions when `option` is
212/// [`NationalOption::English`] (verified against the ETSI EN 300 706 PDF's
213/// Table 35/36 glyph charts — these are rendered as images in the spec, not
214/// extractable text, so they were read visually; see
215/// `docs/teletext-subtitles.md`).
216///
217/// Codes below `0x20` are Level-1 spacing attributes (clause 12.2: colour,
218/// flash, height, box mode, …) — not decoded to a glyph; rendered as a space
219/// (this crate's lossy-first-pass philosophy, matching the `cc-data`
220/// extractors' documented styling losses). Code `0x7F` is the Level-1
221/// "reserved position" full block (Table 35 note 4); rendered as `'\u{2588}'`
222/// (FULL BLOCK).
223#[must_use]
224pub fn latin_g0_char(code: u8, option: NationalOption) -> char {
225    let code = code & 0x7F;
226    if code < 0x20 {
227        return ' ';
228    }
229    if code == 0x7F {
230        return '\u{2588}';
231    }
232    if option == NationalOption::English
233        && let Some(c) = english_substitution(code)
234    {
235        return c;
236    }
237    // Base Latin G0 / International Reference Version: identical to ASCII
238    // at every position outside the 13 reserved ones.
239    code as char
240}
241
242/// The English (Table 36) substitution for one of Table 35's 13 reserved
243/// code positions, or `None` if `code` is not one of them (in which case the
244/// base ASCII/IRV glyph applies).
245fn english_substitution(code: u8) -> Option<char> {
246    Some(match code {
247        0x23 => '£', // POUND SIGN
248        0x24 => '$', // DOLLAR SIGN (unchanged from base for English)
249        0x40 => '@', // COMMERCIAL AT (unchanged from base for English)
250        0x5B => '←', // LEFTWARDS ARROW
251        0x5C => '½', // VULGAR FRACTION ONE HALF
252        0x5D => '→', // RIGHTWARDS ARROW
253        0x5E => '↑', // UPWARDS ARROW
254        0x5F => '#', // NUMBER SIGN
255        0x60 => '―', // HORIZONTAL BAR (glyph is a plain horizontal
256        // rule in the spec's bitmap chart; U+2015 is this crate's choice of
257        // Unicode codepoint for it — a judgment call, see module docs)
258        0x7B => '¼', // VULGAR FRACTION ONE QUARTER
259        0x7C => '‖', // DOUBLE VERTICAL LINE
260        0x7D => '¾', // VULGAR FRACTION THREE QUARTERS
261        0x7E => '÷', // DIVISION SIGN
262        _ => return None,
263    })
264}
265
266/// The magazine + row number packet address prefix common to every Teletext
267/// packet (ETSI EN 300 706 §7.1.2): 2 bytes, both Hamming-8/4 coded.
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269pub struct PacketAddress {
270    /// Magazine number, `1..=8` (a packet address magazine field of `0`
271    /// denotes magazine 8 — §3, "magazine number 8").
272    pub magazine: u8,
273    /// Packet number `Y`, `0..=31` (`0` = page header, `1..=25` = display
274    /// rows, `26..=31` = non-displayable enhancement packets).
275    pub row: u8,
276}
277
278/// Decode the 2-byte packet address prefix (`txt_data_block[0..2]` of a
279/// [`dvb_vbi::TeletextDataField`] — EN 300 706 bytes 4-5, since
280/// `txt_data_block` starts after the clock-run-in/framing-code).
281///
282/// Returns `None` if either byte is an uncorrectable (double-bit-error)
283/// Hamming-8/4 byte; the packet is then silently ignored by
284/// `PageAssembler` (a robustness choice, not a spec requirement).
285#[must_use]
286pub fn decode_packet_address(b4: u8, b5: u8) -> Option<PacketAddress> {
287    let n4 = decode_hamming_8_4(b4)?;
288    let n5 = decode_hamming_8_4(b5)?;
289    let mag_field = n4 & 0x7;
290    let magazine = if mag_field == 0 { 8 } else { mag_field };
291    let y0 = (n4 >> 3) & 1;
292    let row = y0 | (n5 << 1);
293    Some(PacketAddress { magazine, row })
294}
295
296/// A decoded page header packet (`Y = 0`, ETSI EN 300 706 §9.3.1): page
297/// address, sub-code, and all eleven control bits (Table 2).
298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
299pub struct PageHeader {
300    /// Page number, `Pt << 4 | Pu` (§9.3.1.1; both nibbles `0x0`-`0xF`).
301    pub page: u8,
302    /// Page sub-code element S1 (§9.3.1.2, byte 8; `0x0`-`0xF`).
303    pub s1: u8,
304    /// Page sub-code element S2 (byte 9 bits 2/4/6; `0x0`-`0x7`).
305    pub s2: u8,
306    /// Page sub-code element S3 (byte 10; `0x0`-`0xF`).
307    pub s3: u8,
308    /// Page sub-code element S4 (byte 11 bits 2/4; `0x0`-`0x3`).
309    pub s4: u8,
310    /// C4 Erase Page.
311    pub erase_page: bool,
312    /// C5 Newsflash.
313    pub newsflash: bool,
314    /// C6 Subtitle.
315    pub subtitle: bool,
316    /// C7 Suppress Header (row 0 not displayed).
317    pub suppress_header: bool,
318    /// C8 Update Indicator.
319    pub update_indicator: bool,
320    /// C9 Interrupted Sequence.
321    pub interrupted_sequence: bool,
322    /// C10 Inhibit Display (rows 1-24 not displayed).
323    pub inhibit_display: bool,
324    /// C11 Magazine Serial (`true` = serial mode, `false` = parallel mode).
325    pub magazine_serial: bool,
326    /// C12/C13/C14 National Option Character Subset.
327    pub national_option: NationalOption,
328}
329
330impl PageHeader {
331    /// Decode a page header from the 8 Hamming-8/4 bytes at
332    /// `txt_data_block[2..10]` (EN 300 706 bytes 6-13 — the 2 bytes of
333    /// packet address precede these). Returns `None` if any of the 8 bytes
334    /// is an uncorrectable Hamming-8/4 byte.
335    #[must_use]
336    pub fn parse(txt_data_block: &[u8; 42]) -> Option<PageHeader> {
337        let page_units = decode_hamming_8_4(txt_data_block[2])?;
338        let page_tens = decode_hamming_8_4(txt_data_block[3])?;
339        let s1 = decode_hamming_8_4(txt_data_block[4])?;
340        let n_s2_c4 = decode_hamming_8_4(txt_data_block[5])?;
341        let s3 = decode_hamming_8_4(txt_data_block[6])?;
342        let n_s4_c5_c6 = decode_hamming_8_4(txt_data_block[7])?;
343        let n_c7_c10 = decode_hamming_8_4(txt_data_block[8])?;
344        let n_c11_c14 = decode_hamming_8_4(txt_data_block[9])?;
345
346        let s2 = n_s2_c4 & 0x7;
347        let c4 = (n_s2_c4 >> 3) & 1;
348        let s4 = n_s4_c5_c6 & 0x3;
349        let c5 = (n_s4_c5_c6 >> 2) & 1;
350        let c6 = (n_s4_c5_c6 >> 3) & 1;
351        let c7 = n_c7_c10 & 1;
352        let c8 = (n_c7_c10 >> 1) & 1;
353        let c9 = (n_c7_c10 >> 2) & 1;
354        let c10 = (n_c7_c10 >> 3) & 1;
355        let c11 = n_c11_c14 & 1;
356        let c12 = (n_c11_c14 >> 1) & 1;
357        let c13 = (n_c11_c14 >> 2) & 1;
358        let c14 = (n_c11_c14 >> 3) & 1;
359
360        Some(PageHeader {
361            page: (page_tens << 4) | page_units,
362            s1,
363            s2,
364            s3,
365            s4,
366            erase_page: c4 != 0,
367            newsflash: c5 != 0,
368            subtitle: c6 != 0,
369            suppress_header: c7 != 0,
370            update_indicator: c8 != 0,
371            interrupted_sequence: c9 != 0,
372            inhibit_display: c10 != 0,
373            magazine_serial: c11 != 0,
374            national_option: NationalOption::from_bits((c12 << 2) | (c13 << 1) | c14),
375        })
376    }
377}
378
379/// Decode a display row's 40 odd-parity payload bytes
380/// (`txt_data_block[2..42]`) to text, applying `option`'s character
381/// substitutions. A byte that fails its parity check (undetectable which bit
382/// is wrong — odd parity has no correction capability, §8.1) is rendered as
383/// `'\u{FFFD}'` (REPLACEMENT CHARACTER).
384fn decode_row_text(txt_data_block: &[u8; 42], option: NationalOption) -> String {
385    let mut s = String::with_capacity(40);
386    for &b in &txt_data_block[2..42] {
387        match decode_odd_parity(b) {
388            Some(code) => s.push(latin_g0_char(code, option)),
389            None => s.push('\u{FFFD}'),
390        }
391    }
392    s
393}
394
395/// Accumulates one tracked `(magazine, page)`'s row packets into display
396/// text (ETSI EN 300 706 §7.2: a page's body is its header packet plus all
397/// subsequent `Y=1..=24` packets in the same magazine, up to the next
398/// header). Crate-private: the public surface is
399/// [`crate::webvtt::TeletextCueExtractor`].
400pub(crate) struct PageAssembler {
401    magazine: u8,
402    page: u8,
403    /// Whether the magazine's most-recently-seen header packet matched
404    /// `(magazine, page)` — row packets in a magazine belong to whichever
405    /// page was last headed, per §7.2.1.
406    active: bool,
407    inhibited: bool,
408    national_option: NationalOption,
409    /// Index `0` = row 1 .. index `23` = row 24.
410    rows: [String; 24],
411}
412
413impl PageAssembler {
414    pub(crate) fn new(magazine: u8, page: u8) -> Self {
415        PageAssembler {
416            magazine,
417            page,
418            active: false,
419            inhibited: false,
420            national_option: NationalOption::English,
421            rows: core::array::from_fn(|_| String::new()),
422        }
423    }
424
425    pub(crate) fn push(&mut self, field: &dvb_vbi::TeletextDataField) {
426        // EN 300 706 transmits each byte of the magazine/packet address and
427        // data block LSB-first (§7.1.2/§8.1/§8.2's "bslbf" fields, EN 301 775
428        // §4.5) — `txt_data_block_logical()` undoes that wire order; run
429        // Hamming-8/4 / odd-parity decode (which assume the spec's bit order
430        // directly) against its output, not the raw `txt_data_block`.
431        let block: [u8; 42] = field.txt_data_block_logical();
432        let block = &block;
433        let Some(addr) = decode_packet_address(block[0], block[1]) else {
434            return;
435        };
436        if addr.magazine != self.magazine {
437            return;
438        }
439        if addr.row == 0 {
440            let Some(header) = PageHeader::parse(block) else {
441                return;
442            };
443            self.active = header.page == self.page;
444            if self.active {
445                if header.erase_page {
446                    for row in &mut self.rows {
447                        row.clear();
448                    }
449                }
450                self.inhibited = header.inhibit_display;
451                self.national_option = header.national_option;
452            }
453            return;
454        }
455        if !self.active || addr.row > 24 {
456            return;
457        }
458        self.rows[(addr.row - 1) as usize] = decode_row_text(block, self.national_option);
459    }
460
461    /// The currently displayed subtitle text: non-empty, trailing-space
462    /// trimmed rows 1-24, in row order, joined with `\n`. Empty if the page
463    /// is currently inhibited (C10) or no row is non-empty.
464    pub(crate) fn display_text(&self) -> String {
465        if self.inhibited {
466            return String::new();
467        }
468        let lines: Vec<&str> = self
469            .rows
470            .iter()
471            .map(|r| r.trim_end())
472            .filter(|r| !r.is_empty())
473            .collect();
474        lines.join("\n")
475    }
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481
482    #[test]
483    fn hamming_8_4_round_trips_all_16_nibbles() {
484        for nibble in 0u8..16 {
485            let byte = encode_hamming_8_4(nibble);
486            assert_eq!(
487                decode_hamming_8_4(byte),
488                Some(nibble),
489                "nibble {nibble:#X} round-trip"
490            );
491        }
492    }
493
494    #[test]
495    fn hamming_8_4_corrects_every_single_bit_error() {
496        for nibble in 0u8..16 {
497            let byte = encode_hamming_8_4(nibble);
498            for bit in 0..8u8 {
499                let corrupted = byte ^ (1 << bit);
500                assert_eq!(
501                    decode_hamming_8_4(corrupted),
502                    Some(nibble),
503                    "nibble {nibble:#X}, single-bit error at bit {bit} must be corrected"
504                );
505            }
506        }
507    }
508
509    #[test]
510    fn hamming_8_4_rejects_double_bit_errors() {
511        // Flip 2 bits of a known-good codeword: per §8.2, "double bit errors
512        // can be detected" (rejected, not silently accepted as some other
513        // nibble).
514        let byte = encode_hamming_8_4(0b0110);
515        let corrupted = byte ^ 0b0000_0011; // flip bits 0 and 1
516        assert_eq!(
517            decode_hamming_8_4(corrupted),
518            None,
519            "a double-bit error must be rejected, not miscorrected"
520        );
521    }
522
523    #[test]
524    fn hamming_manual_cross_check_against_spec_encoding_equations() {
525        // Manually compute nibble 0b0110 (D1=0,D2=1,D3=1,D4=0) by hand from
526        // §8.2's stated equations, cross-checking `encode_hamming_8_4`:
527        // P1 = 1^D1^D3^D4 = 1^0^1^0 = 0
528        // P2 = 1^D1^D2^D4 = 1^0^1^0 = 0
529        // P3 = 1^D1^D2^D3 = 1^0^1^1 = 1
530        // P4 = 1^P1^D1^P2^D2^P3^D3^D4 = 1^0^0^0^1^1^1^0 = 0
531        // wire bits (transmission order P1 D1 P2 D2 P3 D3 P4 D4) = 0 0 0 1 1 1 0 0
532        // packed LSB-first: bit1=P1=0,bit2=D1=0,bit3=P2=0,bit4=D2=1,
533        //                    bit5=P3=1,bit6=D3=1,bit7=P4=0,bit8=D4=0
534        // byte = 0b0011_1000 = 0x38
535        assert_eq!(encode_hamming_8_4(0b0110), 0x38);
536        assert_eq!(decode_hamming_8_4(0x38), Some(0b0110));
537    }
538
539    #[test]
540    fn odd_parity_round_trips_all_128_values() {
541        for data7 in 0u8..128 {
542            let byte = encode_odd_parity(data7);
543            assert_eq!(
544                byte.count_ones() % 2,
545                1,
546                "encoded byte must have odd parity"
547            );
548            assert_eq!(decode_odd_parity(byte), Some(data7));
549        }
550    }
551
552    #[test]
553    fn odd_parity_detects_but_does_not_correct() {
554        let byte = encode_odd_parity(b'H' & 0x7F);
555        let corrupted = byte ^ 0x01; // flip one data bit -> even parity
556        assert_eq!(
557            decode_odd_parity(corrupted),
558            None,
559            "odd parity only detects errors; a corrupted byte must not decode"
560        );
561    }
562
563    #[test]
564    fn latin_g0_base_matches_ascii_outside_reserved_positions() {
565        for code in 0x20u8..0x7F {
566            let is_reserved = matches!(
567                code,
568                0x23 | 0x24
569                    | 0x40
570                    | 0x5B
571                    | 0x5C
572                    | 0x5D
573                    | 0x5E
574                    | 0x5F
575                    | 0x60
576                    | 0x7B
577                    | 0x7C
578                    | 0x7D
579                    | 0x7E
580            );
581            if !is_reserved {
582                assert_eq!(
583                    latin_g0_char(code, NationalOption::English),
584                    code as char,
585                    "non-reserved position {code:#04X} must match base ASCII"
586                );
587            }
588        }
589    }
590
591    #[test]
592    fn latin_g0_english_substitutions_verified_against_table_36() {
593        // Values read directly from ETSI EN 300 706 Table 36's "English" row
594        // (bitmap glyph chart, visually verified — see docs/teletext-subtitles.md).
595        assert_eq!(latin_g0_char(0x23, NationalOption::English), '£');
596        assert_eq!(latin_g0_char(0x24, NationalOption::English), '$');
597        assert_eq!(latin_g0_char(0x40, NationalOption::English), '@');
598        assert_eq!(latin_g0_char(0x5B, NationalOption::English), '←');
599        assert_eq!(latin_g0_char(0x5C, NationalOption::English), '½');
600        assert_eq!(latin_g0_char(0x5D, NationalOption::English), '→');
601        assert_eq!(latin_g0_char(0x5E, NationalOption::English), '↑');
602        assert_eq!(latin_g0_char(0x5F, NationalOption::English), '#');
603        assert_eq!(latin_g0_char(0x7B, NationalOption::English), '¼');
604        assert_eq!(latin_g0_char(0x7C, NationalOption::English), '‖');
605        assert_eq!(latin_g0_char(0x7D, NationalOption::English), '¾');
606        assert_eq!(latin_g0_char(0x7E, NationalOption::English), '÷');
607    }
608
609    #[test]
610    fn latin_g0_non_english_falls_back_to_base_at_reserved_positions() {
611        // Documented gap: German substitutions are not implemented, so the
612        // base ASCII glyph is returned instead (not the German '§' etc).
613        assert_eq!(latin_g0_char(0x24, NationalOption::German), '$');
614    }
615
616    #[test]
617    fn control_codes_render_as_space_and_0x7f_as_full_block() {
618        assert_eq!(latin_g0_char(0x00, NationalOption::English), ' ');
619        assert_eq!(latin_g0_char(0x1F, NationalOption::English), ' ');
620        assert_eq!(latin_g0_char(0x7F, NationalOption::English), '\u{2588}');
621    }
622
623    #[test]
624    fn national_option_decodes_all_8_values() {
625        assert_eq!(NationalOption::from_bits(0), NationalOption::English);
626        assert_eq!(NationalOption::from_bits(1), NationalOption::German);
627        assert_eq!(
628            NationalOption::from_bits(2),
629            NationalOption::SwedishFinnishHungarian
630        );
631        assert_eq!(NationalOption::from_bits(3), NationalOption::Italian);
632        assert_eq!(NationalOption::from_bits(4), NationalOption::French);
633        assert_eq!(
634            NationalOption::from_bits(5),
635            NationalOption::PortugueseSpanish
636        );
637        assert_eq!(NationalOption::from_bits(6), NationalOption::CzechSlovak);
638        assert_eq!(NationalOption::from_bits(7), NationalOption::Reserved(7));
639    }
640
641    #[test]
642    fn packet_address_decodes_magazine_0_as_magazine_8() {
643        // magazine field = 0 (nibble low 3 bits = 0), row = 0.
644        let b4 = encode_hamming_8_4(0); // magazine field 0, Y bit0 = 0
645        let b5 = encode_hamming_8_4(0); // Y bits 1-4 = 0
646        let addr = decode_packet_address(b4, b5).unwrap();
647        assert_eq!(
648            addr.magazine, 8,
649            "magazine field 0 must decode as magazine 8"
650        );
651        assert_eq!(addr.row, 0);
652    }
653
654    #[test]
655    fn packet_address_decodes_magazine_and_row() {
656        // magazine field = 3, Y = 17 (0b10001): Y bit0=1 (goes in byte4 D4),
657        // Y bits1-4 = 0b1000 (goes in byte5 nibble).
658        let b4 = encode_hamming_8_4(0b1_011); // D1..D3=011(mag=3), D4=1(Y bit0)
659        let b5 = encode_hamming_8_4(0b1000); // Y bits1..4 = 1000
660        let addr = decode_packet_address(b4, b5).unwrap();
661        assert_eq!(addr.magazine, 3);
662        assert_eq!(addr.row, 17);
663    }
664
665    #[test]
666    fn page_assembler_tracks_target_page_and_ignores_others() {
667        let mut asm = PageAssembler::new(8, 0x88);
668
669        // Header for magazine 8, page 0x88, C6 subtitle set, C4 erase set.
670        let header_block = build_header_block(8, 0x88, true, true, false, NationalOption::English);
671        asm.push(&field_from_block(header_block, 0));
672        assert!(asm.active);
673
674        // Row 20: "HI"
675        let row_block = build_row_block(8, 20, "HI");
676        asm.push(&field_from_block(row_block, 20));
677        assert_eq!(asm.display_text(), "HI");
678
679        // A row for a DIFFERENT magazine must be ignored.
680        let other_mag_row = build_row_block(1, 21, "IGNORED");
681        asm.push(&field_from_block(other_mag_row, 21));
682        assert_eq!(
683            asm.display_text(),
684            "HI",
685            "other magazine's row must be ignored"
686        );
687
688        // A header for a different page in the same magazine deactivates us.
689        let other_page_header =
690            build_header_block(8, 0x01, true, false, false, NationalOption::English);
691        asm.push(&field_from_block(other_page_header, 0));
692        assert!(!asm.active);
693        let row_after_switch = build_row_block(8, 21, "SHOULD NOT APPEAR");
694        asm.push(&field_from_block(row_after_switch, 21));
695        assert_eq!(
696            asm.display_text(),
697            "HI",
698            "rows while another page is active must not be stored"
699        );
700
701        // Switch back with erase -> old row content is cleared.
702        let back_header = build_header_block(8, 0x88, true, true, false, NationalOption::English);
703        asm.push(&field_from_block(back_header, 0));
704        assert_eq!(asm.display_text(), "", "erase_page must clear old rows");
705    }
706
707    #[test]
708    fn page_assembler_inhibit_display_blanks_text() {
709        let mut asm = PageAssembler::new(8, 0x88);
710        asm.push(&field_from_block(
711            build_header_block(8, 0x88, true, true, false, NationalOption::English),
712            0,
713        ));
714        asm.push(&field_from_block(build_row_block(8, 20, "HELLO"), 20));
715        assert_eq!(asm.display_text(), "HELLO");
716
717        // A header with C10 (inhibit_display) set, but C4 (erase) NOT set,
718        // must blank the display while leaving the row buffer itself
719        // populated (proves inhibit is a display-time gate, not a clear).
720        asm.push(&field_from_block(
721            build_header_block(8, 0x88, false, false, true, NationalOption::English),
722            0,
723        ));
724        assert_eq!(
725            asm.display_text(),
726            "",
727            "inhibit_display must blank the text"
728        );
729        assert_eq!(
730            asm.rows[19].trim_end(),
731            "HELLO",
732            "inhibit_display must not clear the underlying row buffer"
733        );
734    }
735
736    /// Test-only helper: build a 42-byte `txt_data_block` for a page header
737    /// packet (`Y=0`) at `(magazine, page)` with the given C4/C6/C10 bits.
738    /// Uses [`encode_hamming_8_4`] — the same function proven correct by the
739    /// round-trip and manual-cross-check tests above — to build spec-valid
740    /// wire bytes (this project's established "construct from verified spec
741    /// encode rules" fixture fallback; see `docs/teletext-subtitles.md`).
742    pub(super) fn build_header_block(
743        magazine: u8,
744        page: u8,
745        erase_page: bool,
746        subtitle: bool,
747        inhibit_display: bool,
748        option: NationalOption,
749    ) -> [u8; 42] {
750        let mut b = [0u8; 42];
751        let mag_field = if magazine == 8 { 0 } else { magazine };
752        b[0] = encode_hamming_8_4(mag_field); // Y bit0 = 0 (row 0)
753        b[1] = encode_hamming_8_4(0); // Y bits1..4 = 0
754        b[2] = encode_hamming_8_4(page & 0xF); // page units
755        b[3] = encode_hamming_8_4((page >> 4) & 0xF); // page tens
756        b[4] = encode_hamming_8_4(0); // S1 = 0
757        let c4 = u8::from(erase_page);
758        b[5] = encode_hamming_8_4(c4 << 3); // S2=0, C4
759        b[6] = encode_hamming_8_4(0); // S3 = 0
760        let c6 = u8::from(subtitle);
761        b[7] = encode_hamming_8_4(c6 << 3); // S4=0, C5=0, C6
762        let c10 = u8::from(inhibit_display);
763        b[8] = encode_hamming_8_4(c10 << 3); // C7=C8=C9=0, C10
764        let opt_bits = match option {
765            NationalOption::English => 0u8,
766            NationalOption::German => 1,
767            NationalOption::SwedishFinnishHungarian => 2,
768            NationalOption::Italian => 3,
769            NationalOption::French => 4,
770            NationalOption::PortugueseSpanish => 5,
771            NationalOption::CzechSlovak => 6,
772            NationalOption::Reserved(v) => v,
773        };
774        let c12 = (opt_bits >> 2) & 1;
775        let c13 = (opt_bits >> 1) & 1;
776        let c14 = opt_bits & 1;
777        b[9] = encode_hamming_8_4((c14 << 3) | (c13 << 2) | (c12 << 1)); // C11=0
778        for byte in b.iter_mut().skip(10) {
779            *byte = encode_odd_parity(0x20); // row-0 text: spaces
780        }
781        b
782    }
783
784    /// Test-only helper: build a 42-byte `txt_data_block` for a display row
785    /// packet (`Y=1..=24`) carrying `text` (ASCII only, right-padded with
786    /// spaces to 40 columns), odd-parity encoded per §8.1.
787    pub(super) fn build_row_block(magazine: u8, row: u8, text: &str) -> [u8; 42] {
788        assert!((1..=24).contains(&row));
789        let mut b = [0u8; 42];
790        let mag_field = if magazine == 8 { 0 } else { magazine };
791        let y0 = row & 1;
792        b[0] = encode_hamming_8_4(mag_field | (y0 << 3));
793        b[1] = encode_hamming_8_4(row >> 1);
794        let bytes = text.as_bytes();
795        for i in 0..40usize {
796            let ch = bytes.get(i).copied().unwrap_or(b' ');
797            b[2 + i] = encode_odd_parity(ch & 0x7F);
798        }
799        b
800    }
801
802    pub(super) fn field_from_block(block: [u8; 42], line: u8) -> dvb_vbi::TeletextDataField {
803        // `build_header_block`/`build_row_block` produce the spec's own
804        // (canonical) byte values via `encode_hamming_8_4`/`encode_odd_parity`;
805        // reverse each bit to emulate the LSB-first wire bytes `push` now
806        // un-reverses, so these tests exercise the real wire path.
807        dvb_vbi::TeletextDataField {
808            header: dvb_vbi::LineHeader::new(true, line % 24),
809            framing_code: dvb_vbi::FRAMING_CODE_EBU,
810            txt_data_block: block.map(u8::reverse_bits),
811        }
812    }
813}