Skip to main content

dvb_si/descriptors/
data_broadcast.rs

1//! Data Broadcast Descriptor — ETSI EN 300 468 §6.2.12 (tag 0x64).
2//!
3//! Table 31 (PDF p. 71). Identifies a data broadcast component: its
4//! data_broadcast_id, the component_tag tying it to a stream_identifier, a raw
5//! selector tail, plus a localised text description in one language.
6
7use super::descriptor_body;
8use crate::error::{Error, Result};
9use crate::text::{DvbText, LangCode};
10use dvb_common::{Parse, Serialize};
11
12/// Descriptor tag for data_broadcast_descriptor.
13pub const TAG: u8 = 0x64;
14const HEADER_LEN: usize = 2;
15const ID_LEN: usize = 2;
16const COMPONENT_TAG_LEN: usize = 1;
17const SELECTOR_LEN_FIELD: usize = 1;
18const LANG_LEN: usize = 3;
19const TEXT_LEN_FIELD: usize = 1;
20
21/// Returns the well-known name for a `data_broadcast_id`, or `None` if the
22/// ID is not recognised.
23///
24/// Delegates to [`super::data_broadcast_id::data_broadcast_id_name`] as the
25/// single source of truth.
26#[must_use]
27pub fn data_broadcast_id_name(id: u16) -> Option<&'static str> {
28    super::data_broadcast_id::data_broadcast_id_name(id)
29}
30
31/// Data Broadcast Descriptor (tag 0x64).
32#[derive(Debug, Clone, PartialEq, Eq)]
33#[cfg_attr(feature = "serde", derive(serde::Serialize))]
34#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
35pub struct DataBroadcastDescriptor<'a> {
36    /// 16-bit data_broadcast_id (ETSI TS 101 162 registration).
37    pub data_broadcast_id: u16,
38    /// component_tag linking this entry to a stream_identifier_descriptor.
39    pub component_tag: u8,
40    /// Raw selector_byte tail — interpretation depends on data_broadcast_id.
41    /// Kept raw deliberately; decode via id-specific parsers per TS 101 162.
42    pub selector: &'a [u8],
43    /// ISO 639-2 language code of the text description.
44    pub language_code: LangCode,
45    /// DVB Annex-A encoded text description.
46    pub text: DvbText<'a>,
47}
48
49impl<'a> Parse<'a> for DataBroadcastDescriptor<'a> {
50    type Error = crate::error::Error;
51    fn parse(bytes: &'a [u8]) -> Result<Self> {
52        let min_body = ID_LEN + COMPONENT_TAG_LEN + SELECTOR_LEN_FIELD + LANG_LEN + TEXT_LEN_FIELD;
53        let body = descriptor_body(
54            bytes,
55            TAG,
56            "DataBroadcastDescriptor",
57            "unexpected tag for data_broadcast_descriptor",
58        )?;
59        if body.len() < min_body {
60            return Err(Error::InvalidDescriptor {
61                tag: TAG,
62                reason: "data_broadcast_descriptor body shorter than minimum 8 bytes",
63            });
64        }
65        let (id_bytes, _) = body
66            .split_first_chunk::<ID_LEN>()
67            .ok_or(Error::InvalidDescriptor {
68                tag: TAG,
69                reason: "data_broadcast_descriptor body shorter than minimum 8 bytes",
70            })?;
71        let data_broadcast_id = u16::from_be_bytes(*id_bytes);
72        let mut pos = ID_LEN;
73        let component_tag = body[pos];
74        pos += COMPONENT_TAG_LEN;
75
76        let selector_length = body[pos] as usize;
77        pos += SELECTOR_LEN_FIELD;
78        let selector_end = pos + selector_length;
79        // Need selector + lang(3) + text_length(1) to still fit.
80        if selector_end + LANG_LEN + TEXT_LEN_FIELD > body.len() {
81            return Err(Error::InvalidDescriptor {
82                tag: TAG,
83                reason: "selector_length runs past descriptor end",
84            });
85        }
86        let selector = &body[pos..selector_end];
87        pos = selector_end;
88
89        let language_code = LangCode([body[pos], body[pos + 1], body[pos + 2]]);
90        pos += LANG_LEN;
91
92        let text_length = body[pos] as usize;
93        pos += TEXT_LEN_FIELD;
94        let text_end = pos + text_length;
95        if text_end > body.len() {
96            return Err(Error::InvalidDescriptor {
97                tag: TAG,
98                reason: "text_length runs past descriptor end",
99            });
100        }
101        let text = DvbText::new(&body[pos..text_end]);
102
103        Ok(Self {
104            data_broadcast_id,
105            component_tag,
106            selector,
107            language_code,
108            text,
109        })
110    }
111}
112
113impl Serialize for DataBroadcastDescriptor<'_> {
114    type Error = crate::error::Error;
115    fn serialized_len(&self) -> usize {
116        HEADER_LEN
117            + ID_LEN
118            + COMPONENT_TAG_LEN
119            + SELECTOR_LEN_FIELD
120            + self.selector.len()
121            + LANG_LEN
122            + TEXT_LEN_FIELD
123            + self.text.len()
124    }
125
126    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
127        if self.selector.len() > u8::MAX as usize {
128            return Err(Error::InvalidDescriptor {
129                tag: TAG,
130                reason: "selector exceeds 255 bytes (selector_length is 8-bit)",
131            });
132        }
133        if self.text.len() > u8::MAX as usize {
134            return Err(Error::InvalidDescriptor {
135                tag: TAG,
136                reason: "text exceeds 255 bytes (text_length is 8-bit)",
137            });
138        }
139        let len = self.serialized_len();
140        let body = len - HEADER_LEN;
141        if body > u8::MAX as usize {
142            return Err(Error::InvalidDescriptor {
143                tag: TAG,
144                reason: "data_broadcast_descriptor body exceeds 255 bytes",
145            });
146        }
147        if buf.len() < len {
148            return Err(Error::OutputBufferTooSmall {
149                need: len,
150                have: buf.len(),
151            });
152        }
153        buf[0] = TAG;
154        buf[1] = body as u8;
155        let mut pos = HEADER_LEN;
156        buf[pos..pos + ID_LEN].copy_from_slice(&self.data_broadcast_id.to_be_bytes());
157        pos += ID_LEN;
158        buf[pos] = self.component_tag;
159        pos += COMPONENT_TAG_LEN;
160        buf[pos] = self.selector.len() as u8;
161        pos += SELECTOR_LEN_FIELD;
162        buf[pos..pos + self.selector.len()].copy_from_slice(self.selector);
163        pos += self.selector.len();
164        buf[pos..pos + LANG_LEN].copy_from_slice(&self.language_code.0);
165        pos += LANG_LEN;
166        buf[pos] = self.text.len() as u8;
167        pos += TEXT_LEN_FIELD;
168        buf[pos..pos + self.text.len()].copy_from_slice(self.text.raw());
169        Ok(len)
170    }
171}
172impl<'a> crate::traits::DescriptorDef<'a> for DataBroadcastDescriptor<'a> {
173    const TAG: u8 = TAG;
174    const NAME: &'static str = "DATA_BROADCAST";
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    fn build(id: u16, ctag: u8, selector: &[u8], lang: [u8; 3], text: &[u8]) -> Vec<u8> {
182        let body = ID_LEN
183            + COMPONENT_TAG_LEN
184            + SELECTOR_LEN_FIELD
185            + selector.len()
186            + LANG_LEN
187            + TEXT_LEN_FIELD
188            + text.len();
189        let mut v = Vec::with_capacity(HEADER_LEN + body);
190        v.push(TAG);
191        v.push(body as u8);
192        v.extend_from_slice(&id.to_be_bytes());
193        v.push(ctag);
194        v.push(selector.len() as u8);
195        v.extend_from_slice(selector);
196        v.extend_from_slice(&lang);
197        v.push(text.len() as u8);
198        v.extend_from_slice(text);
199        v
200    }
201
202    #[test]
203    fn parse_extracts_all_fields() {
204        let bytes = build(0x000B, 0x12, &[0xAA, 0xBB], *b"eng", b"Hello");
205        let d = DataBroadcastDescriptor::parse(&bytes).unwrap();
206        assert_eq!(d.data_broadcast_id, 0x000B);
207        assert_eq!(d.component_tag, 0x12);
208        assert_eq!(d.selector, &[0xAA, 0xBB]);
209        assert_eq!(d.language_code, LangCode(*b"eng"));
210        assert_eq!(d.text.raw(), b"Hello");
211    }
212
213    #[test]
214    fn data_broadcast_id_name_verified() {
215        assert_eq!(data_broadcast_id_name(0x0006), Some("Data Carousel"));
216        assert_eq!(data_broadcast_id_name(0x0123), Some("HbbTV"));
217        assert_eq!(
218            data_broadcast_id_name(0x000B),
219            Some("IP/MAC Notification (INT)")
220        );
221    }
222
223    #[test]
224    fn data_broadcast_id_name_removed_entries_return_none() {
225        assert_eq!(data_broadcast_id_name(0x00F2), None);
226    }
227
228    #[test]
229    fn data_broadcast_id_name_unknown() {
230        assert_eq!(data_broadcast_id_name(0x0000), None);
231    }
232
233    #[test]
234    fn parse_accepts_empty_selector_and_text() {
235        let bytes = build(0x0001, 0x00, &[], *b"fra", b"");
236        let d = DataBroadcastDescriptor::parse(&bytes).unwrap();
237        assert!(d.selector.is_empty());
238        assert!(d.text.raw().is_empty());
239        assert_eq!(d.language_code, LangCode(*b"fra"));
240    }
241
242    #[test]
243    fn parse_rejects_wrong_tag() {
244        let mut bytes = build(0x0001, 0x00, &[], *b"eng", b"");
245        bytes[0] = 0x65;
246        let err = DataBroadcastDescriptor::parse(&bytes).unwrap_err();
247        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x65, .. }));
248    }
249
250    #[test]
251    fn parse_rejects_short_buffer() {
252        let err = DataBroadcastDescriptor::parse(&[TAG]).unwrap_err();
253        assert!(matches!(err, Error::BufferTooShort { .. }));
254    }
255
256    #[test]
257    fn parse_rejects_body_too_short() {
258        // length=4: cannot hold the 8-byte minimum.
259        let err = DataBroadcastDescriptor::parse(&[TAG, 4, 0, 0, 0, 0]).unwrap_err();
260        assert!(matches!(err, Error::InvalidDescriptor { .. }));
261    }
262
263    #[test]
264    fn parse_rejects_selector_length_overrun() {
265        // selector_length=200 but body is tiny.
266        let bytes = [TAG, 8, 0x00, 0x0B, 0x12, 200, b'e', b'n', b'g', 0];
267        let err = DataBroadcastDescriptor::parse(&bytes).unwrap_err();
268        assert!(matches!(err, Error::InvalidDescriptor { .. }));
269    }
270
271    #[test]
272    fn parse_rejects_text_length_overrun() {
273        // selector_length=0, lang present, text_length=5 but no text bytes.
274        let bytes = [TAG, 8, 0x00, 0x0B, 0x12, 0, b'e', b'n', b'g', 5];
275        let err = DataBroadcastDescriptor::parse(&bytes).unwrap_err();
276        assert!(matches!(err, Error::InvalidDescriptor { .. }));
277    }
278
279    #[test]
280    fn serialize_round_trip() {
281        let bytes = build(0x0123, 0x45, &[0xDE, 0xAD], *b"deu", b"Daten");
282        let parsed = DataBroadcastDescriptor::parse(&bytes).unwrap();
283        let mut buf = vec![0u8; parsed.serialized_len()];
284        parsed.serialize_into(&mut buf).unwrap();
285        assert_eq!(buf, bytes);
286        let re = DataBroadcastDescriptor::parse(&buf).unwrap();
287        assert_eq!(parsed, re);
288    }
289
290    #[test]
291    fn serialize_rejects_too_small_buffer() {
292        let d = DataBroadcastDescriptor {
293            data_broadcast_id: 0x0001,
294            component_tag: 0x00,
295            selector: &[],
296            language_code: LangCode(*b"eng"),
297            text: DvbText::new(&[]),
298        };
299        let mut tiny = [0u8; 4];
300        let err = d.serialize_into(&mut tiny).unwrap_err();
301        assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
302    }
303
304    #[test]
305    fn serialize_rejects_over_range_selector() {
306        let sel = vec![0u8; 256];
307        let d = DataBroadcastDescriptor {
308            data_broadcast_id: 0x0001,
309            component_tag: 0x00,
310            selector: &sel,
311            language_code: LangCode(*b"eng"),
312            text: DvbText::new(&[]),
313        };
314        let mut buf = vec![0u8; d.serialized_len()];
315        let err = d.serialize_into(&mut buf).unwrap_err();
316        assert!(matches!(err, Error::InvalidDescriptor { tag: TAG, .. }));
317    }
318
319    #[test]
320    fn serialize_rejects_over_range_body() {
321        // selector 250 + text 10 + fixed 7 = 267 > 255, both sub-fields in range.
322        let sel = vec![0u8; 250];
323        let txt = vec![0u8; 10];
324        let d = DataBroadcastDescriptor {
325            data_broadcast_id: 0x0001,
326            component_tag: 0x00,
327            selector: &sel,
328            language_code: LangCode(*b"eng"),
329            text: DvbText::new(&txt),
330        };
331        let mut buf = vec![0u8; d.serialized_len()];
332        let err = d.serialize_into(&mut buf).unwrap_err();
333        assert!(matches!(err, Error::InvalidDescriptor { tag: TAG, .. }));
334    }
335
336    #[cfg(feature = "serde")]
337    #[test]
338    fn serde_serialize_is_stable() {
339        let d = DataBroadcastDescriptor {
340            data_broadcast_id: 0x000B,
341            component_tag: 0x09,
342            selector: &[0x01, 0x02],
343            language_code: LangCode(*b"eng"),
344            text: DvbText::new(b"Text"),
345        };
346        let json = serde_json::to_string(&d).unwrap();
347        assert!(json.contains("\"data_broadcast_id\""));
348        assert!(json.contains("\"component_tag\""));
349        assert!(json.contains("\"eng\""));
350        assert!(json.contains("\"Text\""));
351    }
352}