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 mut pos = 0;
66        let data_broadcast_id = u16::from_be_bytes([body[pos], body[pos + 1]]);
67        pos += ID_LEN;
68        let component_tag = body[pos];
69        pos += COMPONENT_TAG_LEN;
70
71        let selector_length = body[pos] as usize;
72        pos += SELECTOR_LEN_FIELD;
73        let selector_end = pos + selector_length;
74        // Need selector + lang(3) + text_length(1) to still fit.
75        if selector_end + LANG_LEN + TEXT_LEN_FIELD > body.len() {
76            return Err(Error::InvalidDescriptor {
77                tag: TAG,
78                reason: "selector_length runs past descriptor end",
79            });
80        }
81        let selector = &body[pos..selector_end];
82        pos = selector_end;
83
84        let language_code = LangCode([body[pos], body[pos + 1], body[pos + 2]]);
85        pos += LANG_LEN;
86
87        let text_length = body[pos] as usize;
88        pos += TEXT_LEN_FIELD;
89        let text_end = pos + text_length;
90        if text_end > body.len() {
91            return Err(Error::InvalidDescriptor {
92                tag: TAG,
93                reason: "text_length runs past descriptor end",
94            });
95        }
96        let text = DvbText::new(&body[pos..text_end]);
97
98        Ok(Self {
99            data_broadcast_id,
100            component_tag,
101            selector,
102            language_code,
103            text,
104        })
105    }
106}
107
108impl Serialize for DataBroadcastDescriptor<'_> {
109    type Error = crate::error::Error;
110    fn serialized_len(&self) -> usize {
111        HEADER_LEN
112            + ID_LEN
113            + COMPONENT_TAG_LEN
114            + SELECTOR_LEN_FIELD
115            + self.selector.len()
116            + LANG_LEN
117            + TEXT_LEN_FIELD
118            + self.text.len()
119    }
120
121    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
122        if self.selector.len() > u8::MAX as usize {
123            return Err(Error::InvalidDescriptor {
124                tag: TAG,
125                reason: "selector exceeds 255 bytes (selector_length is 8-bit)",
126            });
127        }
128        if self.text.len() > u8::MAX as usize {
129            return Err(Error::InvalidDescriptor {
130                tag: TAG,
131                reason: "text exceeds 255 bytes (text_length is 8-bit)",
132            });
133        }
134        let len = self.serialized_len();
135        let body = len - HEADER_LEN;
136        if body > u8::MAX as usize {
137            return Err(Error::InvalidDescriptor {
138                tag: TAG,
139                reason: "data_broadcast_descriptor body exceeds 255 bytes",
140            });
141        }
142        if buf.len() < len {
143            return Err(Error::OutputBufferTooSmall {
144                need: len,
145                have: buf.len(),
146            });
147        }
148        buf[0] = TAG;
149        buf[1] = body as u8;
150        let mut pos = HEADER_LEN;
151        buf[pos..pos + ID_LEN].copy_from_slice(&self.data_broadcast_id.to_be_bytes());
152        pos += ID_LEN;
153        buf[pos] = self.component_tag;
154        pos += COMPONENT_TAG_LEN;
155        buf[pos] = self.selector.len() as u8;
156        pos += SELECTOR_LEN_FIELD;
157        buf[pos..pos + self.selector.len()].copy_from_slice(self.selector);
158        pos += self.selector.len();
159        buf[pos..pos + LANG_LEN].copy_from_slice(&self.language_code.0);
160        pos += LANG_LEN;
161        buf[pos] = self.text.len() as u8;
162        pos += TEXT_LEN_FIELD;
163        buf[pos..pos + self.text.len()].copy_from_slice(self.text.raw());
164        Ok(len)
165    }
166}
167impl<'a> crate::traits::DescriptorDef<'a> for DataBroadcastDescriptor<'a> {
168    const TAG: u8 = TAG;
169    const NAME: &'static str = "DATA_BROADCAST";
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn build(id: u16, ctag: u8, selector: &[u8], lang: [u8; 3], text: &[u8]) -> Vec<u8> {
177        let body = ID_LEN
178            + COMPONENT_TAG_LEN
179            + SELECTOR_LEN_FIELD
180            + selector.len()
181            + LANG_LEN
182            + TEXT_LEN_FIELD
183            + text.len();
184        let mut v = Vec::with_capacity(HEADER_LEN + body);
185        v.push(TAG);
186        v.push(body as u8);
187        v.extend_from_slice(&id.to_be_bytes());
188        v.push(ctag);
189        v.push(selector.len() as u8);
190        v.extend_from_slice(selector);
191        v.extend_from_slice(&lang);
192        v.push(text.len() as u8);
193        v.extend_from_slice(text);
194        v
195    }
196
197    #[test]
198    fn parse_extracts_all_fields() {
199        let bytes = build(0x000B, 0x12, &[0xAA, 0xBB], *b"eng", b"Hello");
200        let d = DataBroadcastDescriptor::parse(&bytes).unwrap();
201        assert_eq!(d.data_broadcast_id, 0x000B);
202        assert_eq!(d.component_tag, 0x12);
203        assert_eq!(d.selector, &[0xAA, 0xBB]);
204        assert_eq!(d.language_code, LangCode(*b"eng"));
205        assert_eq!(d.text.raw(), b"Hello");
206    }
207
208    #[test]
209    fn data_broadcast_id_name_verified() {
210        assert_eq!(data_broadcast_id_name(0x0006), Some("Data Carousel"));
211        assert_eq!(data_broadcast_id_name(0x0123), Some("HbbTV"));
212        assert_eq!(
213            data_broadcast_id_name(0x000B),
214            Some("IP/MAC Notification (INT)")
215        );
216    }
217
218    #[test]
219    fn data_broadcast_id_name_removed_entries_return_none() {
220        assert_eq!(data_broadcast_id_name(0x00F2), None);
221    }
222
223    #[test]
224    fn data_broadcast_id_name_unknown() {
225        assert_eq!(data_broadcast_id_name(0x0000), None);
226    }
227
228    #[test]
229    fn parse_accepts_empty_selector_and_text() {
230        let bytes = build(0x0001, 0x00, &[], *b"fra", b"");
231        let d = DataBroadcastDescriptor::parse(&bytes).unwrap();
232        assert!(d.selector.is_empty());
233        assert!(d.text.raw().is_empty());
234        assert_eq!(d.language_code, LangCode(*b"fra"));
235    }
236
237    #[test]
238    fn parse_rejects_wrong_tag() {
239        let mut bytes = build(0x0001, 0x00, &[], *b"eng", b"");
240        bytes[0] = 0x65;
241        let err = DataBroadcastDescriptor::parse(&bytes).unwrap_err();
242        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x65, .. }));
243    }
244
245    #[test]
246    fn parse_rejects_short_buffer() {
247        let err = DataBroadcastDescriptor::parse(&[TAG]).unwrap_err();
248        assert!(matches!(err, Error::BufferTooShort { .. }));
249    }
250
251    #[test]
252    fn parse_rejects_body_too_short() {
253        // length=4: cannot hold the 8-byte minimum.
254        let err = DataBroadcastDescriptor::parse(&[TAG, 4, 0, 0, 0, 0]).unwrap_err();
255        assert!(matches!(err, Error::InvalidDescriptor { .. }));
256    }
257
258    #[test]
259    fn parse_rejects_selector_length_overrun() {
260        // selector_length=200 but body is tiny.
261        let bytes = [TAG, 8, 0x00, 0x0B, 0x12, 200, b'e', b'n', b'g', 0];
262        let err = DataBroadcastDescriptor::parse(&bytes).unwrap_err();
263        assert!(matches!(err, Error::InvalidDescriptor { .. }));
264    }
265
266    #[test]
267    fn parse_rejects_text_length_overrun() {
268        // selector_length=0, lang present, text_length=5 but no text bytes.
269        let bytes = [TAG, 8, 0x00, 0x0B, 0x12, 0, b'e', b'n', b'g', 5];
270        let err = DataBroadcastDescriptor::parse(&bytes).unwrap_err();
271        assert!(matches!(err, Error::InvalidDescriptor { .. }));
272    }
273
274    #[test]
275    fn serialize_round_trip() {
276        let bytes = build(0x0123, 0x45, &[0xDE, 0xAD], *b"deu", b"Daten");
277        let parsed = DataBroadcastDescriptor::parse(&bytes).unwrap();
278        let mut buf = vec![0u8; parsed.serialized_len()];
279        parsed.serialize_into(&mut buf).unwrap();
280        assert_eq!(buf, bytes);
281        let re = DataBroadcastDescriptor::parse(&buf).unwrap();
282        assert_eq!(parsed, re);
283    }
284
285    #[test]
286    fn serialize_rejects_too_small_buffer() {
287        let d = DataBroadcastDescriptor {
288            data_broadcast_id: 0x0001,
289            component_tag: 0x00,
290            selector: &[],
291            language_code: LangCode(*b"eng"),
292            text: DvbText::new(&[]),
293        };
294        let mut tiny = [0u8; 4];
295        let err = d.serialize_into(&mut tiny).unwrap_err();
296        assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
297    }
298
299    #[test]
300    fn serialize_rejects_over_range_selector() {
301        let sel = vec![0u8; 256];
302        let d = DataBroadcastDescriptor {
303            data_broadcast_id: 0x0001,
304            component_tag: 0x00,
305            selector: &sel,
306            language_code: LangCode(*b"eng"),
307            text: DvbText::new(&[]),
308        };
309        let mut buf = vec![0u8; d.serialized_len()];
310        let err = d.serialize_into(&mut buf).unwrap_err();
311        assert!(matches!(err, Error::InvalidDescriptor { tag: TAG, .. }));
312    }
313
314    #[test]
315    fn serialize_rejects_over_range_body() {
316        // selector 250 + text 10 + fixed 7 = 267 > 255, both sub-fields in range.
317        let sel = vec![0u8; 250];
318        let txt = vec![0u8; 10];
319        let d = DataBroadcastDescriptor {
320            data_broadcast_id: 0x0001,
321            component_tag: 0x00,
322            selector: &sel,
323            language_code: LangCode(*b"eng"),
324            text: DvbText::new(&txt),
325        };
326        let mut buf = vec![0u8; d.serialized_len()];
327        let err = d.serialize_into(&mut buf).unwrap_err();
328        assert!(matches!(err, Error::InvalidDescriptor { tag: TAG, .. }));
329    }
330
331    #[cfg(feature = "serde")]
332    #[test]
333    fn serde_serialize_is_stable() {
334        let d = DataBroadcastDescriptor {
335            data_broadcast_id: 0x000B,
336            component_tag: 0x09,
337            selector: &[0x01, 0x02],
338            language_code: LangCode(*b"eng"),
339            text: DvbText::new(b"Text"),
340        };
341        let json = serde_json::to_string(&d).unwrap();
342        assert!(json.contains("\"data_broadcast_id\""));
343        assert!(json.contains("\"component_tag\""));
344        assert!(json.contains("\"eng\""));
345        assert!(json.contains("\"Text\""));
346    }
347}