Skip to main content

dvb_si/tables/
downloadable_font_info.rs

1//! Downloadable Font Information Section (DFIS) — ETSI EN 303 560 v1.1.1
2//! §5.3.2.3.1 (table_id 0x7C).
3//!
4//! The DFIS conveys download location and font metadata for a single font or
5//! font family. Sections of a Downloadable Font Information Table (DFIT) are
6//! carried together on one PID, signalled in the PMT by a `data_broadcast_id`
7//! descriptor with `data_broadcast_id` 0x000D (§5.3.2.3.1) — there is no
8//! well-known PID, so [`PID`] follows the `dsmcc.rs` "no fixed PID" convention.
9//!
10//! ## table_id
11//!
12//! EN 303 560 v1.1.1 §5.3.2.3.1 says `table_id` 0x4C — an acknowledged
13//! allocation accident: 0x4C was already the INT. EN 300 468 V1.19.1 Table 2
14//! NOTE 2 ("table_id 0x4C was previously accidentally assigned to both of
15//! these two DVB specifications, this has now been corrected") reassigns the
16//! DFIS to **0x7C**, which is what [`TABLE_ID`] and the crate registry use.
17//!
18//! ## The 0x02 conditional (resolved against the PDF, pp. 30-31)
19//!
20//! Table 22's syntax has two consecutive conditionals that both fire for
21//! `font_info_type == 0x02`:
22//!
23//! ```text
24//! if (font_info_type == 0x02) { font_size (16) }
25//! if (font_info_type >= 0x02) { font_info_length (8) + text_char ... }
26//! ```
27//!
28//! This is **not** a typo and **not** double-handling: a type-0x02 entry
29//! carries the 16-bit `font_size` *followed by* the length-prefixed string
30//! block. Every `font_info_type >= 0x02` is length-delimited by
31//! `font_info_length` (the 0x02 case additionally prefixes the 2-byte
32//! `font_size`). This makes types 0x03 (`font_family`) and all reserved types
33//! 0x04..=0xFF safely skippable, so they round-trip as
34//! [`FontInfo::LengthDelimited`]. Verified against EN 303 560 v1.1.1 PDF
35//! pp. 30-31 (Table 22) and p. 32 (Table 23 type allocation).
36//!
37//! Per crate contract this parser does NOT verify CRC_32 (use
38//! `Section::validate_crc`). Reserved bits are ignored on parse; spec-mandated
39//! zero fields (`font_id_extension`, `reserved_zero_future_use`) are emitted 0.
40
41use crate::error::{Error, Result};
42use alloc::vec::Vec;
43use dvb_common::{Parse, Serialize};
44
45/// table_id for the DFIS — the crate registry value (see module docs re. spec 0x4C).
46pub const TABLE_ID: u8 = 0x7C;
47/// DFIS has no well-known PID; carried on the PID signalled by the
48/// `data_broadcast_id` (0x000D) descriptor in the PMT (§5.3.2.3.1).
49pub const PID: u16 = 0x0000;
50
51/// `font_info_type` for style/weight (§5.3.2.3.2.1 Table 23).
52pub const FONT_INFO_TYPE_STYLE_WEIGHT: u8 = 0x00;
53/// `font_info_type` for a font file URI (Table 23).
54pub const FONT_INFO_TYPE_FILE_URI: u8 = 0x01;
55/// `font_info_type` for font size in pixels (Table 23).
56pub const FONT_INFO_TYPE_FONT_SIZE: u8 = 0x02;
57
58/// table_id(1) + section_length(2) + font_id_extension/font_id(2)
59/// + version/cni(1) + section_number(1) + last_section_number(1) = 8-byte header.
60const HEADER_LEN: usize = 8;
61/// `section_length` counts from just after the field (byte 3) to end of section.
62const SECTION_LENGTH_PREFIX: usize = 3;
63/// CRC_32 trailer.
64const CRC_LEN: usize = 4;
65
66/// One entry in the DFIS font_info loop (§5.3.2.3.1 Table 22).
67///
68/// Variant is selected by `font_info_type` (Table 23). Reserved types
69/// (0x04..=0xFF) are length-delimited and round-trip via [`FontInfo::LengthDelimited`].
70#[derive(Debug, Clone, PartialEq, Eq)]
71#[cfg_attr(feature = "serde", derive(serde::Serialize))]
72#[non_exhaustive]
73pub enum FontInfo<'a> {
74    /// `font_info_type == 0x00`: style(3) + weight(4) + reserved(1).
75    StyleWeight {
76        /// `font_style` (§5.3.2.3.2.2 Table 24): 0 undefined, 1 normal, 2 italic, 3 oblique.
77        style: u8,
78        /// `font_weight` (Table 25): 0 undefined, 1 normal, 2 bold.
79        weight: u8,
80    },
81    /// `font_info_type == 0x01`: reserved(4) + font_file_format(4) + uri_length(8) + uri.
82    FileUri {
83        /// `font_file_format` (§5.3.2.3.2.3 Table 26): 0 = OFF, 1 = WOFF.
84        format: u8,
85        /// DVB URI string (UTF-8), `uri_length` bytes.
86        uri: &'a [u8],
87    },
88    /// `font_info_type == 0x02`: font_size(16) followed by the length-delimited block.
89    FontSize {
90        /// `font_size` — font height in pixels.
91        size: u16,
92        /// `text_char` block following `font_info_length` (UTF-8).
93        info: &'a [u8],
94    },
95    /// `font_info_type >= 0x03` (incl. reserved): font_info_length(8) + text_char block.
96    LengthDelimited {
97        /// The `font_info_type` byte as parsed (0x03 = font_family, else reserved).
98        font_info_type: u8,
99        /// `text_char` block, `font_info_length` bytes (UTF-8 for defined types).
100        info: &'a [u8],
101    },
102}
103
104/// Downloadable Font Information Section (EN 303 560 §5.3.2.3.1, Table 22).
105#[derive(Debug, Clone, PartialEq, Eq)]
106#[cfg_attr(feature = "serde", derive(serde::Serialize))]
107#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
108pub struct DownloadableFontInfoSection<'a> {
109    /// 9-bit `font_id_extension` — spec-mandated all-zero; together with
110    /// `font_id` forms the 16-bit table_id_extension.
111    pub font_id_extension: u16,
112    /// 7-bit `font_id` identifying the sub_table (one font/family).
113    pub font_id: u8,
114    /// 5-bit version_number.
115    pub version_number: u8,
116    /// current_next_indicator bit.
117    pub current_next_indicator: bool,
118    /// section_number.
119    pub section_number: u8,
120    /// last_section_number.
121    pub last_section_number: u8,
122    /// font_info loop entries in wire order.
123    pub font_info: Vec<FontInfo<'a>>,
124}
125
126impl<'a> Parse<'a> for DownloadableFontInfoSection<'a> {
127    type Error = crate::error::Error;
128    fn parse(bytes: &'a [u8]) -> Result<Self> {
129        let min_len = HEADER_LEN + CRC_LEN;
130        if bytes.len() < min_len {
131            return Err(Error::BufferTooShort {
132                need: min_len,
133                have: bytes.len(),
134                what: "DownloadableFontInfoSection",
135            });
136        }
137        if bytes[0] != TABLE_ID {
138            return Err(Error::UnexpectedTableId {
139                table_id: bytes[0],
140                what: "DownloadableFontInfoSection",
141                expected: &[TABLE_ID],
142            });
143        }
144        let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
145        let total = super::check_section_length(
146            bytes.len(),
147            SECTION_LENGTH_PREFIX,
148            section_length,
149            HEADER_LEN + CRC_LEN,
150        )?;
151
152        // bytes[3..5] = font_id_extension(9) | font_id(7).
153        let id_word = u16::from_be_bytes(*bytes[3..].first_chunk::<2>().unwrap());
154        let font_id_extension = id_word >> 7;
155        let font_id = (id_word & 0x7F) as u8;
156        let version_number = (bytes[5] >> 1) & 0x1F;
157        let current_next_indicator = bytes[5] & 0x01 != 0;
158        let section_number = bytes[6];
159        let last_section_number = bytes[7];
160
161        let loop_end = total - CRC_LEN;
162        let mut font_info = Vec::new();
163        let mut pos = HEADER_LEN;
164        while pos < loop_end {
165            let font_info_type = bytes[pos];
166            pos += 1;
167            match font_info_type {
168                FONT_INFO_TYPE_STYLE_WEIGHT => {
169                    if pos + 1 > loop_end {
170                        return Err(Error::SectionLengthOverflow {
171                            declared: 1,
172                            available: loop_end - pos,
173                        });
174                    }
175                    let b = bytes[pos];
176                    pos += 1;
177                    font_info.push(FontInfo::StyleWeight {
178                        style: b >> 5,
179                        weight: (b >> 1) & 0x0F,
180                    });
181                }
182                FONT_INFO_TYPE_FILE_URI => {
183                    if pos + 2 > loop_end {
184                        return Err(Error::SectionLengthOverflow {
185                            declared: 2,
186                            available: loop_end - pos,
187                        });
188                    }
189                    let format = bytes[pos] & 0x0F;
190                    let uri_length = bytes[pos + 1] as usize;
191                    let uri_start = pos + 2;
192                    let uri_end = uri_start + uri_length;
193                    if uri_end > loop_end {
194                        return Err(Error::SectionLengthOverflow {
195                            declared: uri_length,
196                            available: loop_end - uri_start,
197                        });
198                    }
199                    font_info.push(FontInfo::FileUri {
200                        format,
201                        uri: &bytes[uri_start..uri_end],
202                    });
203                    pos = uri_end;
204                }
205                FONT_INFO_TYPE_FONT_SIZE => {
206                    // font_size(16) then font_info_length(8) + block (Table 22, type >= 0x02).
207                    if pos + 3 > loop_end {
208                        return Err(Error::SectionLengthOverflow {
209                            declared: 3,
210                            available: loop_end - pos,
211                        });
212                    }
213                    let (b2, _) = bytes[pos..].split_first_chunk::<2>().ok_or(
214                        Error::SectionLengthOverflow {
215                            declared: 3,
216                            available: loop_end - pos,
217                        },
218                    )?;
219                    let size = u16::from_be_bytes(*b2);
220                    let info_length = bytes[pos + 2] as usize;
221                    let info_start = pos + 3;
222                    let info_end = info_start + info_length;
223                    if info_end > loop_end {
224                        return Err(Error::SectionLengthOverflow {
225                            declared: info_length,
226                            available: loop_end - info_start,
227                        });
228                    }
229                    font_info.push(FontInfo::FontSize {
230                        size,
231                        info: &bytes[info_start..info_end],
232                    });
233                    pos = info_end;
234                }
235                _ => {
236                    // font_info_type >= 0x03: font_info_length(8) + text_char block.
237                    if pos + 1 > loop_end {
238                        return Err(Error::SectionLengthOverflow {
239                            declared: 1,
240                            available: loop_end - pos,
241                        });
242                    }
243                    let info_length = bytes[pos] as usize;
244                    let info_start = pos + 1;
245                    let info_end = info_start + info_length;
246                    if info_end > loop_end {
247                        return Err(Error::SectionLengthOverflow {
248                            declared: info_length,
249                            available: loop_end - info_start,
250                        });
251                    }
252                    font_info.push(FontInfo::LengthDelimited {
253                        font_info_type,
254                        info: &bytes[info_start..info_end],
255                    });
256                    pos = info_end;
257                }
258            }
259        }
260
261        Ok(DownloadableFontInfoSection {
262            font_id_extension,
263            font_id,
264            version_number,
265            current_next_indicator,
266            section_number,
267            last_section_number,
268            font_info,
269        })
270    }
271}
272
273impl Serialize for DownloadableFontInfoSection<'_> {
274    type Error = crate::error::Error;
275    fn serialized_len(&self) -> usize {
276        let loop_bytes: usize = self
277            .font_info
278            .iter()
279            .map(|f| match f {
280                FontInfo::StyleWeight { .. } => 2, // type + 1 packed byte
281                FontInfo::FileUri { uri, .. } => 1 + 2 + uri.len(), // type + (fmt|len) + uri
282                FontInfo::FontSize { info, .. } => 1 + 2 + 1 + info.len(), // type + size + len + info
283                FontInfo::LengthDelimited { info, .. } => 1 + 1 + info.len(), // type + len + info
284            })
285            .sum();
286        HEADER_LEN + loop_bytes + CRC_LEN
287    }
288    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
289        let len = self.serialized_len();
290        if buf.len() < len {
291            return Err(Error::OutputBufferTooSmall {
292                need: len,
293                have: buf.len(),
294            });
295        }
296        let section_length = (len - SECTION_LENGTH_PREFIX) as u16;
297        buf[0] = TABLE_ID;
298        buf[1] = super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F);
299        buf[2] = (section_length & 0xFF) as u8;
300        // font_id_extension(9) | font_id(7); spec mandates extension all-zero.
301        let id_word = ((self.font_id_extension & 0x01FF) << 7) | (self.font_id as u16 & 0x7F);
302        buf[3..5].copy_from_slice(&id_word.to_be_bytes());
303        // reserved(2)=11, version_number(5), current_next_indicator(1).
304        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
305        buf[6] = self.section_number;
306        buf[7] = self.last_section_number;
307
308        // 8-bit length prefixes error on over-range payloads rather than
309        // silently truncating (the crate's strict serialize idiom).
310        let guard_u8 = |len: usize| -> Result<()> {
311            if len > u8::MAX as usize {
312                return Err(Error::SectionLengthOverflow {
313                    declared: len,
314                    available: u8::MAX as usize,
315                });
316            }
317            Ok(())
318        };
319
320        let mut pos = HEADER_LEN;
321        for f in &self.font_info {
322            match f {
323                FontInfo::StyleWeight { style, weight } => {
324                    buf[pos] = FONT_INFO_TYPE_STYLE_WEIGHT;
325                    // style(3) | weight(4) | reserved_zero_future_use(1)=0.
326                    buf[pos + 1] = ((style & 0x07) << 5) | ((weight & 0x0F) << 1);
327                    pos += 2;
328                }
329                FontInfo::FileUri { format, uri } => {
330                    guard_u8(uri.len())?;
331                    buf[pos] = FONT_INFO_TYPE_FILE_URI;
332                    // reserved_zero_future_use(4)=0 | font_file_format(4).
333                    buf[pos + 1] = format & 0x0F;
334                    buf[pos + 2] = uri.len() as u8;
335                    let s = pos + 3;
336                    buf[s..s + uri.len()].copy_from_slice(uri);
337                    pos = s + uri.len();
338                }
339                FontInfo::FontSize { size, info } => {
340                    guard_u8(info.len())?;
341                    buf[pos] = FONT_INFO_TYPE_FONT_SIZE;
342                    buf[pos + 1..pos + 3].copy_from_slice(&size.to_be_bytes());
343                    buf[pos + 3] = info.len() as u8;
344                    let s = pos + 4;
345                    buf[s..s + info.len()].copy_from_slice(info);
346                    pos = s + info.len();
347                }
348                FontInfo::LengthDelimited {
349                    font_info_type,
350                    info,
351                } => {
352                    guard_u8(info.len())?;
353                    buf[pos] = *font_info_type;
354                    buf[pos + 1] = info.len() as u8;
355                    let s = pos + 2;
356                    buf[s..s + info.len()].copy_from_slice(info);
357                    pos = s + info.len();
358                }
359            }
360        }
361
362        let crc = dvb_common::crc32_mpeg2::compute(&buf[..pos]);
363        buf[pos..len].copy_from_slice(&crc.to_be_bytes());
364        Ok(len)
365    }
366}
367impl<'a> crate::traits::TableDef<'a> for DownloadableFontInfoSection<'a> {
368    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
369    const NAME: &'static str = "DOWNLOADABLE_FONT_INFO";
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    /// Wrap a font_info loop body in the 8-byte common header + placeholder CRC.
377    fn build_section(font_id: u8, version: u8, loop_body: &[u8]) -> Vec<u8> {
378        let section_length =
379            (HEADER_LEN - SECTION_LENGTH_PREFIX + loop_body.len() + CRC_LEN) as u16;
380        // font_id_extension = 0 (spec-mandated), font_id in low 7 bits.
381        let id_word = (font_id as u16) & 0x7F;
382        let mut v = vec![
383            TABLE_ID,
384            super::super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F),
385            (section_length & 0xFF) as u8,
386            (id_word >> 8) as u8,
387            (id_word & 0xFF) as u8,
388            0xC0 | (version << 1) | 0x01,
389            0x00,
390            0x00,
391        ];
392        v.extend_from_slice(loop_body);
393        v.extend_from_slice(&[0, 0, 0, 0]);
394        v
395    }
396
397    /// Build a font_info loop with one of each variant.
398    fn mixed_loop() -> Vec<u8> {
399        let uri = b"https://f.example/Droid.otf";
400        let family = b"Droid Sans";
401        let mut b = vec![
402            FONT_INFO_TYPE_STYLE_WEIGHT, // type 0x00
403            (2u8 << 5) | (2u8 << 1),     // style=2 (italic), weight=2 (bold)
404            FONT_INFO_TYPE_FILE_URI,     // type 0x01
405            0x01,                        // format=1 (WOFF)
406            uri.len() as u8,             // uri_length
407        ];
408        b.extend_from_slice(uri);
409        // type 0x02 — font_size=24, info block "px"
410        b.push(FONT_INFO_TYPE_FONT_SIZE);
411        b.extend_from_slice(&24u16.to_be_bytes());
412        b.push(2);
413        b.extend_from_slice(b"px");
414        // type 0x03 — font_family
415        b.push(0x03);
416        b.push(family.len() as u8);
417        b.extend_from_slice(family);
418        b
419    }
420
421    #[test]
422    fn parse_header_fields() {
423        let bytes = build_section(0x42, 9, &[]);
424        let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
425        assert_eq!(sec.font_id, 0x42);
426        assert_eq!(sec.font_id_extension, 0);
427        assert_eq!(sec.version_number, 9);
428        assert!(sec.current_next_indicator);
429        assert!(sec.font_info.is_empty());
430    }
431
432    #[test]
433    fn parse_all_variants() {
434        let bytes = build_section(1, 0, &mixed_loop());
435        let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
436        assert_eq!(sec.font_info.len(), 4);
437        assert_eq!(
438            sec.font_info[0],
439            FontInfo::StyleWeight {
440                style: 2,
441                weight: 2
442            }
443        );
444        match &sec.font_info[1] {
445            FontInfo::FileUri { format, uri } => {
446                assert_eq!(*format, 1);
447                assert_eq!(*uri, b"https://f.example/Droid.otf");
448            }
449            other => panic!("expected FileUri, got {other:?}"),
450        }
451        match &sec.font_info[2] {
452            FontInfo::FontSize { size, info } => {
453                assert_eq!(*size, 24);
454                assert_eq!(*info, b"px");
455            }
456            other => panic!("expected FontSize, got {other:?}"),
457        }
458        match &sec.font_info[3] {
459            FontInfo::LengthDelimited {
460                font_info_type,
461                info,
462            } => {
463                assert_eq!(*font_info_type, 0x03);
464                assert_eq!(*info, b"Droid Sans");
465            }
466            other => panic!("expected LengthDelimited, got {other:?}"),
467        }
468    }
469
470    #[test]
471    fn reserved_type_round_trips_as_length_delimited() {
472        // type 0x77 (reserved) is length-delimited and skippable.
473        let mut body = vec![0x77u8, 0x03];
474        body.extend_from_slice(&[0xAA, 0xBB, 0xCC]);
475        let bytes = build_section(1, 0, &body);
476        let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
477        assert_eq!(
478            sec.font_info[0],
479            FontInfo::LengthDelimited {
480                font_info_type: 0x77,
481                info: &[0xAA, 0xBB, 0xCC]
482            }
483        );
484    }
485
486    #[test]
487    fn parse_rejects_wrong_tag() {
488        let mut bytes = build_section(1, 0, &mixed_loop());
489        bytes[0] = 0x4C; // INT table_id
490        assert!(matches!(
491            DownloadableFontInfoSection::parse(&bytes).unwrap_err(),
492            Error::UnexpectedTableId { table_id: 0x4C, .. }
493        ));
494    }
495
496    #[test]
497    fn rejects_short_buffer() {
498        assert!(matches!(
499            DownloadableFontInfoSection::parse(&[0x7C, 0xB0]).unwrap_err(),
500            Error::BufferTooShort {
501                what: "DownloadableFontInfoSection",
502                ..
503            }
504        ));
505    }
506
507    #[test]
508    fn uri_length_overflow_rejected() {
509        // type 0x01, uri_length 0x20 but no uri bytes present.
510        let body = vec![FONT_INFO_TYPE_FILE_URI, 0x01, 0x20];
511        let bytes = build_section(1, 0, &body);
512        assert!(matches!(
513            DownloadableFontInfoSection::parse(&bytes).unwrap_err(),
514            Error::SectionLengthOverflow { .. }
515        ));
516    }
517
518    #[test]
519    fn round_trip_all_variants() {
520        let bytes = build_section(0x33, 4, &mixed_loop());
521        let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
522        let mut buf = vec![0u8; sec.serialized_len()];
523        sec.serialize_into(&mut buf).unwrap();
524        let re = DownloadableFontInfoSection::parse(&buf).unwrap();
525        assert_eq!(sec, re);
526    }
527
528    #[test]
529    fn table_trait_constants() {
530        assert_eq!(TABLE_ID, 0x7C);
531        assert_eq!(PID, 0x0000);
532    }
533
534    #[test]
535    #[cfg(feature = "serde")]
536    fn serde_json_round_trip() {
537        let bytes = build_section(1, 0, &mixed_loop());
538        let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
539        let j = serde_json::to_string(&sec).unwrap();
540        // The borrowed `uri`/`info` `&[u8]` fields cannot be JSON-deserialized
541        // zero-copy (serde_json renders them as number sequences, not borrowed
542        // byte arrays) — the crate-wide constraint affecting every
543        // borrowed-slice table (cf. mpe.rs). Exercise the derive through the
544        // WIRE form: a re-parse must serialize to byte-identical JSON.
545        let reparsed = DownloadableFontInfoSection::parse(&bytes).unwrap();
546        assert_eq!(serde_json::to_string(&reparsed).unwrap(), j);
547        assert!(j.contains("\"font_id\":1"));
548    }
549
550    #[test]
551    fn parse_rejects_zero_section_length() {
552        let mut buf = vec![0u8; 64];
553        buf[0] = TABLE_ID;
554        buf[1] = 0xF0;
555        buf[2] = 0x00;
556        for b in &mut buf[3..] {
557            *b = 0xFF;
558        }
559        assert!(matches!(
560            DownloadableFontInfoSection::parse(&buf).unwrap_err(),
561            Error::SectionLengthOverflow { .. }
562        ));
563    }
564}