dvb-si 17.0.0

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Virtual filesystem view of a DVB object carousel.
//!
//! [`CarouselFs`] is built from a set of `(module_id, &[u8])` pairs (the
//! reassembled module data from [`crate::carousel::ModuleReassembler`]).
//! It walks each module's BIOP messages, indexes by `(module_id, object_key)`,
//! and exposes a path-based resolver so callers can retrieve file content
//! without understanding the IOR chain.
//!
//! Spec: `private/specs-verified/dvb/dvb-si/text/iso_13818_6/` (ETSI TR 101 202 §4.7.4).

use super::message::{BiopMessage, DirectoryMessage, biop_frame_len};
use alloc::collections::BTreeMap;
use alloc::vec;
use alloc::vec::Vec;
use broadcast_core::ParsePrefix;
use broadcast_core::damage::{Damage, DamageKind, DamageLocation, Severity};
use broadcast_core::range::ByteRange;

// ── CarouselObject ────────────────────────────────────────────────────────────

/// One object parsed from a carousel module.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CarouselObject {
    /// A Directory or ServiceGateway object.
    Directory(DirectoryObjectData),
    /// A File object.
    File(FileObjectData),
}

/// Owned data extracted from a `DirectoryMessage`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectoryObjectData {
    /// Bindings in this directory.
    pub entries: Vec<DirectoryEntry>,
    /// True if this is a ServiceGateway (the carousel root).
    pub is_service_gateway: bool,
}

/// One binding in a directory: a name resolving to an object elsewhere in
/// the carousel (r02-W12 — was an untyped `(Vec<u8>, u16, Vec<u8>)` tuple).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectoryEntry {
    /// Binding name as carried on the wire (a trailing NUL byte, if any, is
    /// stripped only when matching against a path segment, not here).
    pub name: Vec<u8>,
    /// `moduleId` of the target object's `ObjectLocation`.
    pub module_id: u16,
    /// `objectKey_data` of the target object's `ObjectLocation`.
    pub object_key: Vec<u8>,
}

/// Owned data extracted from a `FileMessage`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileObjectData {
    /// File content bytes.
    pub content: Vec<u8>,
}

// ── Key type ──────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct ObjectKey {
    module_id: u16,
    object_key: Vec<u8>,
}

// ── CarouselFs ────────────────────────────────────────────────────────────────

/// A virtual filesystem built from a set of reassembled carousel modules.
///
/// # Construction
///
/// ```text
/// // collect (module_id, data) pairs from ModuleReassembler:
/// let fs = CarouselFs::from_modules(&[(1, data_bytes)]);
/// ```
///
/// # Path resolution
///
/// Paths are `&[&str]` slices (e.g. `&["images", "logo.png"]`).
/// The root is the ServiceGateway object; each step follows a binding name.
/// Binding names that end in `\0` have the trailing NUL stripped before matching.
#[derive(Debug, Clone)]
pub struct CarouselFs {
    objects: BTreeMap<ObjectKey, CarouselObject>,
    /// Key of the ServiceGateway (root) object, if found.
    root_key: Option<ObjectKey>,
    damage: Vec<Damage>,
}

impl CarouselFs {
    /// Build a `CarouselFs` from module `(module_id, data)` pairs.
    ///
    /// Each module's bytes are walked via `BiopMessage::parse_prefix`. A
    /// message that cannot be parsed (a damaged body, a kind this crate does
    /// not model) is skipped by its declared size and reported by
    /// [`damage`](Self::damage), and the walk continues with the next
    /// message; a module whose next message cannot even be framed ends there,
    /// with the rest reported as one [`Damage`].
    pub fn from_modules(modules: &[(u16, &[u8])]) -> Self {
        let mut objects: BTreeMap<ObjectKey, CarouselObject> = BTreeMap::new();
        let mut root_key: Option<ObjectKey> = None;
        let mut damage_list: Vec<Damage> = Vec::new();

        for &(module_id, data) in modules {
            let mut pos = 0;
            while pos < data.len() {
                let remaining = &data[pos..];
                match BiopMessage::parse_prefix(remaining) {
                    Ok((msg, consumed)) => {
                        let (obj_key_bytes, obj) = extract_object(module_id, &msg);
                        if let Some(obj) = obj {
                            let is_sg = matches!(&msg, BiopMessage::ServiceGateway(_));
                            let key = ObjectKey {
                                module_id,
                                object_key: obj_key_bytes,
                            };
                            if is_sg && root_key.is_none() {
                                root_key = Some(key.clone());
                            }
                            objects.insert(key, obj);
                        }
                        pos += consumed;
                    }
                    Err(_) => {
                        let at = ByteRange::new(pos as u64, (data.len() - pos) as u64);
                        let location = DamageLocation::new()
                            .with_byte_range(at)
                            .with_ordinal(u64::from(module_id));
                        let damage = Damage::new(
                            DamageKind::MetadataSkipped,
                            Severity::Degraded,
                            "BIOP message",
                        )
                        .with_location(location);
                        match biop_frame_len(remaining) {
                            Ok(frame) => {
                                let skipped = ByteRange::new(pos as u64, frame as u64);
                                damage_list
                                    .push(damage.with_location(location.with_byte_range(skipped)));
                                pos += frame;
                            }
                            Err(_) => {
                                damage_list.push(
                                    Damage::new(
                                        DamageKind::Resynchronised,
                                        Severity::Degraded,
                                        "BIOP module tail",
                                    )
                                    .with_location(location),
                                );
                                break;
                            }
                        }
                    }
                }
            }
        }

        CarouselFs {
            objects,
            root_key,
            damage: damage_list,
        }
    }

    /// What [`from_modules`](Self::from_modules) skipped, in module order: a
    /// file that then fails to resolve is absent for this reason, not because
    /// the carousel never carried it.
    #[must_use]
    pub fn damage(&self) -> &[Damage] {
        &self.damage
    }

    /// Return the ServiceGateway (root) object, if present.
    pub fn service_gateway(&self) -> Option<&CarouselObject> {
        self.root_key.as_ref().and_then(|k| self.objects.get(k))
    }

    /// Resolve a path `&[&str]` starting from the ServiceGateway root.
    /// Returns the `CarouselObject` at that path, or `None`.
    pub fn resolve(&self, path: &[&str]) -> Option<&CarouselObject> {
        let mut cur_key = self.root_key.clone()?;
        for &segment in path {
            let dir = match self.objects.get(&cur_key)? {
                CarouselObject::Directory(d) => d,
                CarouselObject::File(_) => return None,
            };
            // Find binding with name matching `segment` (strip trailing NUL).
            let entry = dir.entries.iter().find(|e| {
                let n = strip_nul(&e.name);
                n == segment.as_bytes()
            })?;
            cur_key = ObjectKey {
                module_id: entry.module_id,
                object_key: entry.object_key.clone(),
            };
        }
        self.objects.get(&cur_key)
    }

    /// Resolve a path and return the file content bytes, if the target is a File.
    pub fn file_bytes(&self, path: &[&str]) -> Option<&[u8]> {
        match self.resolve(path)? {
            CarouselObject::File(f) => Some(&f.content),
            CarouselObject::Directory(_) => None,
        }
    }
}

/// Strip a trailing NUL byte from a name slice.
fn strip_nul(name: &[u8]) -> &[u8] {
    if name.last() == Some(&0) {
        &name[..name.len() - 1]
    } else {
        name
    }
}

/// Extract the object key bytes and a `CarouselObject` from a parsed message.
/// Returns `(object_key_bytes, Some(obj))` or `(vec![], None)` if not indexable.
fn extract_object(module_id: u16, msg: &BiopMessage<'_>) -> (Vec<u8>, Option<CarouselObject>) {
    match msg {
        BiopMessage::Directory(dm) | BiopMessage::ServiceGateway(dm) => {
            let key_bytes = dm.object_key.to_vec();
            let entries = extract_dir_entries(module_id, dm);
            let is_sg = matches!(msg, BiopMessage::ServiceGateway(_));
            (
                key_bytes,
                Some(CarouselObject::Directory(DirectoryObjectData {
                    entries,
                    is_service_gateway: is_sg,
                })),
            )
        }
        BiopMessage::File(fm) => {
            let key_bytes = fm.object_key.to_vec();
            let content = fm.content.to_vec();
            (
                key_bytes,
                Some(CarouselObject::File(FileObjectData { content })),
            )
        }
        BiopMessage::Stream(_) | BiopMessage::StreamEvent(_) => (vec![], None),
    }
}

/// Extract binding entries from a DirectoryMessage.
fn extract_dir_entries(_self_module_id: u16, dm: &DirectoryMessage<'_>) -> Vec<DirectoryEntry> {
    let mut entries = Vec::with_capacity(dm.bindings.len());
    for binding in &dm.bindings {
        // DVB: nameComponents_count == 1 per binding.
        let name = binding
            .name
            .first()
            .map(|nc| nc.id.to_vec())
            .unwrap_or_default();
        if let Some(bp) = binding.ior.biop_profile() {
            let module_id = bp.object_location.module_id;
            let object_key = bp.object_location.object_key.to_vec();
            entries.push(DirectoryEntry {
                name,
                module_id,
                object_key,
            });
        }
    }
    entries
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::carousel::biop::ior::NameComponent;
    use crate::carousel::biop::{
        ior::{BiopProfileBody, ConnBinder, Ior, ObjectLocation, TaggedProfile},
        message::{Binding, BindingType, BiopMessage, DirectoryMessage, FileMessage},
    };
    use broadcast_core::Serialize;

    /// Build a simple carousel in memory:
    ///   Module 1: ServiceGateway dir with one binding "index.html" → module 2, key [2]
    ///   Module 2: File with content b"hello world"
    fn build_test_carousel() -> Vec<(u16, Vec<u8>)> {
        // Build the IOR pointing to module 2, key [0x02]
        let file_ior = Ior {
            type_id: b"fil\0",
            profiles: vec![TaggedProfile::Biop(BiopProfileBody {
                object_location: ObjectLocation {
                    carousel_id: 0xAB,
                    module_id: 2,
                    version_major: 1,
                    version_minor: 0,
                    object_key: &[0x02],
                },
                conn_binder: ConnBinder { taps: vec![] },
                extra: vec![],
            })],
        };

        let sgw = BiopMessage::ServiceGateway(DirectoryMessage {
            object_kind: *b"srg\0",
            object_key: &[0x01],
            object_info: &[],
            service_context: vec![],
            bindings: vec![Binding {
                name: vec![NameComponent {
                    id: b"index.html",
                    kind: b"fil\0",
                }],
                binding_type: BindingType::NObject,
                ior: file_ior,
                object_info: &[],
            }],
        });

        let file = BiopMessage::File(FileMessage {
            object_key: &[0x02],
            content_size: 11,
            object_info_extra: &[],
            service_context: vec![],
            content: b"hello world",
        });

        let mut mod1 = vec![0u8; sgw.serialized_len()];
        sgw.serialize_into(&mut mod1).unwrap();

        let mut mod2 = vec![0u8; file.serialized_len()];
        file.serialize_into(&mut mod2).unwrap();

        vec![(1u16, mod1), (2u16, mod2)]
    }

    #[test]
    fn carousel_fs_resolve_file() {
        let modules = build_test_carousel();
        let refs: Vec<(u16, &[u8])> = modules
            .iter()
            .map(|(id, data)| (*id, data.as_slice()))
            .collect();
        let fs = CarouselFs::from_modules(&refs);

        // Service gateway should be present
        assert!(fs.service_gateway().is_some());

        // File lookup
        let content = fs.file_bytes(&["index.html"]);
        assert_eq!(content, Some(b"hello world".as_slice()));
    }

    /// R11-l (#4711): a message of a kind the walker cannot parse is skipped
    /// by its declared size and reported; the message after it still lands.
    #[test]
    fn a_damaged_message_is_reported_and_the_rest_of_the_module_is_kept() {
        let mut modules = build_test_carousel();
        let good = modules[1].1.clone();
        let mut bad = good.clone();
        let kind_at = bad
            .windows(4)
            .position(|w| w == b"fil\0")
            .expect("the object kind");
        bad[kind_at..kind_at + 4].copy_from_slice(b"zzz\0");
        modules[1].1 = [bad.clone(), good].concat();
        let refs: Vec<(u16, &[u8])> = modules
            .iter()
            .map(|(id, data)| (*id, data.as_slice()))
            .collect();
        let fs = CarouselFs::from_modules(&refs);
        assert_eq!(
            fs.file_bytes(&["index.html"]),
            Some(b"hello world".as_slice())
        );
        assert_eq!(fs.damage().len(), 1);
        let range = fs.damage()[0].location().byte_range().expect("a range");
        assert_eq!((range.offset(), range.len()), (0, bad.len() as u64));

        modules[1].1.truncate(bad.len() + 5);
        let refs: Vec<(u16, &[u8])> = modules
            .iter()
            .map(|(id, data)| (*id, data.as_slice()))
            .collect();
        assert_eq!(CarouselFs::from_modules(&refs).damage().len(), 2);
    }

    #[test]
    fn carousel_fs_resolve_missing_returns_none() {
        let modules = build_test_carousel();
        let refs: Vec<(u16, &[u8])> = modules
            .iter()
            .map(|(id, data)| (*id, data.as_slice()))
            .collect();
        let fs = CarouselFs::from_modules(&refs);
        assert!(fs.file_bytes(&["does-not-exist.html"]).is_none());
    }

    /// Regression for r02-W12: `DirectoryObjectData::entries` used to be an
    /// untyped `Vec<(Vec<u8>, u16, Vec<u8>)>` — a caller had to know the tuple
    /// order (name, module_id, object_key) from documentation alone. This
    /// exercises the typed `DirectoryEntry` fields directly, which would not
    /// compile against the old tuple shape (a positional `entry.1` still
    /// would).
    #[test]
    fn directory_entry_fields_are_typed_not_positional() {
        let modules = build_test_carousel();
        let refs: Vec<(u16, &[u8])> = modules
            .iter()
            .map(|(id, data)| (*id, data.as_slice()))
            .collect();
        let fs = CarouselFs::from_modules(&refs);
        let CarouselObject::Directory(dir) = fs.service_gateway().unwrap() else {
            panic!("expected Directory");
        };
        assert_eq!(dir.entries.len(), 1);
        let entry = &dir.entries[0];
        assert_eq!(entry.name, b"index.html");
        assert_eq!(entry.module_id, 2);
        assert_eq!(entry.object_key, vec![0x02]);
    }
}