Skip to main content

dvb_si/tables/
mpe_ifec.rs

1//! MPE-IFEC section — ETSI TS 102 772 v1.1.1 §5.2 (table_id 0x7A).
2//!
3//! Carries Inter-burst FEC (IFEC) data for DVB-SH / IP datacast. Syntax per
4//! "Table 2 — MPE-IFEC section" (`dvb-si/docs/ts_102_772_mpe_ifec.md`, §5.2,
5//! PDF p. 17):
6//!
7//! ```text
8//! MPE-IFEC_section() {
9//!   table_id                  8   (0x7A)
10//!   section_syntax_indicator  1
11//!   private_indicator         1
12//!   reserved                  2
13//!   section_length           12
14//!   burst_number              8
15//!   IFEC_burst_size           8
16//!   reserved                  2
17//!   version                   5
18//!   current_next_indicator    1
19//!   section_number            8
20//!   last_section_number       8
21//!   real_time_parameters()   32
22//!   for (i=0; i<Nmax; i++) { IFEC_data_byte 8 }
23//!   CRC_32                   32
24//! }
25//! ```
26//!
27//! Unlike MPE-FEC, this section DOES carry a 5-bit `version` (byte 5), and the
28//! byte-3/4 slot is `burst_number(8)` + `IFEC_burst_size(8)` rather than a
29//! 16-bit identifier. The `real_time_parameters()` block (32 bits) has the SAME
30//! bit-packing as MPE-FEC's but DIFFERENT field semantics per "Table 3"
31//! (§5.3, PDF p. 18): `delta_t(12)` | `mpe_boundary(1)` | `frame_boundary(1)`
32//! | `prev_burst_size(18)`. The doc deliberately keeps a local copy of the
33//! struct (no shared module) — a coordinator may dedup later if warranted.
34//!
35//! MPE-IFEC is a private section (byte-1 bit 6 = `private_indicator`), handled
36//! with the [`crate::tables::cit`] idiom. `ifec_data` is a borrowed raw slice.
37//! No well-known PID — carriage is descriptor-signalled, so `PID = 0x0000`
38//! follows the [`crate::tables::dsmcc`] precedent.
39
40use crate::error::{Error, Result};
41use dvb_common::{Parse, Serialize};
42
43/// table_id for the MPE-IFEC section.
44pub const TABLE_ID: u8 = 0x7A;
45
46/// MPE-IFEC has no well-known PID — its carriage is signalled via descriptors.
47/// `0x0000` follows the DSM-CC precedent.
48pub const PID: u16 = 0x0000;
49
50/// Bytes 0-2: table_id (1) + flags + section_length (2).
51const HEADER_LEN: usize = 3;
52
53/// Bytes 3-7: burst_number(1) + IFEC_burst_size(1) + reserved/version/cni(1)
54/// + section_number(1) + last_section_number(1).
55const EXTENSION_HEADER_LEN: usize = 5;
56
57/// Bytes 8-11: the 32-bit `real_time_parameters()`.
58const RTP_LEN: usize = 4;
59
60/// Bytes occupied by the trailing CRC-32 field.
61const CRC_LEN: usize = 4;
62
63/// Minimum total encoded length: header + extension + RTP + CRC.
64const MIN_LEN: usize = HEADER_LEN + EXTENSION_HEADER_LEN + RTP_LEN + CRC_LEN;
65
66/// Time-slicing / MPE-IFEC real-time parameters (TS 102 772 §5.3, Table 3).
67///
68/// 32 bits: `delta_t(12)` | `mpe_boundary(1)` | `frame_boundary(1)`
69/// | `prev_burst_size(18)`. Same bit layout as the MPE-FEC variant but the
70/// final two fields are `mpe_boundary` / `prev_burst_size`, not
71/// `table_boundary` / `address`.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73#[cfg_attr(feature = "serde", derive(serde::Serialize))]
74pub struct RealTimeParameters {
75    /// 12-bit `delta_t` — time until the start of the next burst.
76    pub delta_t: u16,
77    /// `mpe_boundary` flag.
78    pub mpe_boundary: bool,
79    /// `frame_boundary` flag.
80    pub frame_boundary: bool,
81    /// 18-bit `prev_burst_size`.
82    pub prev_burst_size: u32,
83}
84
85impl RealTimeParameters {
86    /// Decode the 4-byte real_time_parameters block.
87    fn from_bytes(b: [u8; RTP_LEN]) -> Self {
88        // delta_t(12) = b[0] | top 4 bits of b[1]
89        let delta_t = ((b[0] as u16) << 4) | ((b[1] >> 4) as u16);
90        let mpe_boundary = (b[1] & 0x08) != 0;
91        let frame_boundary = (b[1] & 0x04) != 0;
92        // prev_burst_size(18) = bottom 2 bits of b[1] | b[2] | b[3]
93        let prev_burst_size = (((b[1] & 0x03) as u32) << 16) | ((b[2] as u32) << 8) | (b[3] as u32);
94        RealTimeParameters {
95            delta_t,
96            mpe_boundary,
97            frame_boundary,
98            prev_burst_size,
99        }
100    }
101
102    /// Encode into the 4-byte real_time_parameters block.
103    fn to_bytes(self) -> [u8; RTP_LEN] {
104        let dt = self.delta_t & 0x0FFF;
105        let pbs = self.prev_burst_size & 0x0003_FFFF;
106        [
107            (dt >> 4) as u8,
108            (((dt & 0x0F) as u8) << 4)
109                | (u8::from(self.mpe_boundary) << 3)
110                | (u8::from(self.frame_boundary) << 2)
111                | ((pbs >> 16) as u8 & 0x03),
112            ((pbs >> 8) & 0xFF) as u8,
113            (pbs & 0xFF) as u8,
114        ]
115    }
116}
117
118/// MPE-IFEC section (ETSI TS 102 772 v1.1.1 §5.2).
119#[derive(Debug, Clone, PartialEq, Eq)]
120#[cfg_attr(feature = "serde", derive(serde::Serialize))]
121#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
122pub struct MpeIfecSection<'a> {
123    /// `private_indicator` bit from byte 1 (MPE-IFEC is a private section).
124    pub private_indicator: bool,
125    /// `burst_number` (byte 3) — the IFEC burst this section belongs to.
126    pub burst_number: u8,
127    /// `IFEC_burst_size` (byte 4) — number of application data tables in the
128    /// burst.
129    pub ifec_burst_size: u8,
130    /// 5-bit `version` (byte 5).
131    pub version: u8,
132    /// `current_next_indicator` bit.
133    pub current_next_indicator: bool,
134    /// section_number in the sub-table sequence.
135    pub section_number: u8,
136    /// last_section_number in the sub-table sequence.
137    pub last_section_number: u8,
138    /// The decoded real-time parameters block.
139    pub real_time_parameters: RealTimeParameters,
140    /// Raw IFEC data bytes (everything between the real_time_parameters block
141    /// and the CRC-32 trailer).
142    pub ifec_data: &'a [u8],
143}
144
145impl<'a> Parse<'a> for MpeIfecSection<'a> {
146    type Error = crate::error::Error;
147
148    fn parse(bytes: &'a [u8]) -> Result<Self> {
149        if bytes.len() < MIN_LEN {
150            return Err(Error::BufferTooShort {
151                need: MIN_LEN,
152                have: bytes.len(),
153                what: "MpeIfecSection",
154            });
155        }
156
157        if bytes[0] != TABLE_ID {
158            return Err(Error::UnexpectedTableId {
159                table_id: bytes[0],
160                what: "MpeIfecSection",
161                expected: &[TABLE_ID],
162            });
163        }
164
165        let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
166        let total = super::check_section_length(bytes.len(), HEADER_LEN, section_length, MIN_LEN)?;
167
168        let private_indicator = (bytes[1] & 0x40) != 0;
169        let burst_number = bytes[3];
170        let ifec_burst_size = bytes[4];
171        // byte 5: reserved(2) | version(5) | current_next_indicator(1)
172        let version = (bytes[5] >> 1) & 0x1F;
173        let current_next_indicator = (bytes[5] & 0x01) != 0;
174        let section_number = bytes[6];
175        let last_section_number = bytes[7];
176
177        let rtp_start = HEADER_LEN + EXTENSION_HEADER_LEN;
178        let real_time_parameters = RealTimeParameters::from_bytes([
179            bytes[rtp_start],
180            bytes[rtp_start + 1],
181            bytes[rtp_start + 2],
182            bytes[rtp_start + 3],
183        ]);
184
185        let data_start = rtp_start + RTP_LEN;
186        let data_end = total - CRC_LEN;
187        let ifec_data = &bytes[data_start..data_end];
188
189        Ok(MpeIfecSection {
190            private_indicator,
191            burst_number,
192            ifec_burst_size,
193            version,
194            current_next_indicator,
195            section_number,
196            last_section_number,
197            real_time_parameters,
198            ifec_data,
199        })
200    }
201}
202
203impl Serialize for MpeIfecSection<'_> {
204    type Error = crate::error::Error;
205
206    fn serialized_len(&self) -> usize {
207        HEADER_LEN + EXTENSION_HEADER_LEN + RTP_LEN + self.ifec_data.len() + CRC_LEN
208    }
209
210    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
211        let len = self.serialized_len();
212        if buf.len() < len {
213            return Err(Error::OutputBufferTooSmall {
214                need: len,
215                have: buf.len(),
216            });
217        }
218
219        let section_length = (len - HEADER_LEN) as u16;
220        if section_length > 0x0FFF {
221            return Err(Error::SectionLengthOverflow {
222                declared: section_length as usize,
223                available: 0x0FFF,
224            });
225        }
226
227        // Byte 0: table_id.
228        buf[0] = TABLE_ID;
229        // Byte 1: section_syntax_indicator(1)=1 | private_indicator(1)
230        //         | reserved(2)=11 | section_length[11:8](4).
231        buf[1] = 0x80
232            | (u8::from(self.private_indicator) << 6)
233            | 0x30
234            | ((section_length >> 8) as u8 & 0x0F);
235        buf[2] = (section_length & 0xFF) as u8;
236
237        // Extension header.
238        buf[3] = self.burst_number;
239        buf[4] = self.ifec_burst_size;
240        // reserved(2)=11 | version(5) | current_next_indicator(1)
241        buf[5] = 0xC0 | ((self.version & 0x1F) << 1) | u8::from(self.current_next_indicator);
242        buf[6] = self.section_number;
243        buf[7] = self.last_section_number;
244
245        // real_time_parameters.
246        let rtp_start = HEADER_LEN + EXTENSION_HEADER_LEN;
247        buf[rtp_start..rtp_start + RTP_LEN].copy_from_slice(&self.real_time_parameters.to_bytes());
248
249        // ifec_data.
250        let data_start = rtp_start + RTP_LEN;
251        let data_end = data_start + self.ifec_data.len();
252        buf[data_start..data_end].copy_from_slice(self.ifec_data);
253
254        // CRC-32 over everything up to (but not including) the CRC slot.
255        let crc = dvb_common::crc32_mpeg2::compute(&buf[..data_end]);
256        buf[data_end..len].copy_from_slice(&crc.to_be_bytes());
257
258        Ok(len)
259    }
260}
261impl<'a> crate::traits::TableDef<'a> for MpeIfecSection<'a> {
262    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
263    const NAME: &'static str = "MPE_IFEC";
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[allow(clippy::too_many_arguments)]
271    fn build_mpe_ifec(
272        burst_number: u8,
273        ifec_burst_size: u8,
274        version: u8,
275        current_next: bool,
276        section_number: u8,
277        last_section_number: u8,
278        rtp: RealTimeParameters,
279        ifec_data: &[u8],
280    ) -> Vec<u8> {
281        let s = MpeIfecSection {
282            private_indicator: true,
283            burst_number,
284            ifec_burst_size,
285            version,
286            current_next_indicator: current_next,
287            section_number,
288            last_section_number,
289            real_time_parameters: rtp,
290            ifec_data,
291        };
292        let mut buf = vec![0u8; s.serialized_len()];
293        s.serialize_into(&mut buf).unwrap();
294        buf
295    }
296
297    fn sample_rtp() -> RealTimeParameters {
298        RealTimeParameters {
299            delta_t: 0x0ABC,
300            mpe_boundary: true,
301            frame_boundary: false,
302            prev_burst_size: 0x0001_2345,
303        }
304    }
305
306    #[test]
307    fn parse_happy_path() {
308        let ifec = [0x11u8, 0x22, 0x33, 0x44];
309        let bytes = build_mpe_ifec(5, 16, 9, true, 1, 3, sample_rtp(), &ifec);
310        let s = MpeIfecSection::parse(&bytes).unwrap();
311        assert!(s.private_indicator);
312        assert_eq!(s.burst_number, 5);
313        assert_eq!(s.ifec_burst_size, 16);
314        assert_eq!(s.version, 9);
315        assert!(s.current_next_indicator);
316        assert_eq!(s.section_number, 1);
317        assert_eq!(s.last_section_number, 3);
318        assert_eq!(s.real_time_parameters, sample_rtp());
319        assert_eq!(s.ifec_data, &ifec[..]);
320    }
321
322    #[test]
323    fn parse_empty_ifec_data() {
324        let bytes = build_mpe_ifec(0, 0, 0, false, 0, 0, sample_rtp(), &[]);
325        let s = MpeIfecSection::parse(&bytes).unwrap();
326        assert_eq!(s.burst_number, 0);
327        assert_eq!(s.version, 0);
328        assert!(!s.current_next_indicator);
329        assert!(s.ifec_data.is_empty());
330        assert_eq!(s.real_time_parameters, sample_rtp());
331    }
332
333    #[test]
334    fn rtp_bit_packing_round_trips_extremes() {
335        let rtp = RealTimeParameters {
336            delta_t: 0x0FFF,
337            mpe_boundary: false,
338            frame_boundary: true,
339            prev_burst_size: 0x0003_FFFF,
340        };
341        assert_eq!(RealTimeParameters::from_bytes(rtp.to_bytes()), rtp);
342    }
343
344    #[test]
345    fn parse_rejects_wrong_tag() {
346        let mut bytes = build_mpe_ifec(0, 0, 0, true, 0, 0, sample_rtp(), &[]);
347        bytes[0] = 0x70; // not 0x7A
348        assert!(matches!(
349            MpeIfecSection::parse(&bytes).unwrap_err(),
350            Error::UnexpectedTableId { table_id: 0x70, .. }
351        ));
352    }
353
354    #[test]
355    fn parse_rejects_short_buffer() {
356        assert!(matches!(
357            MpeIfecSection::parse(&[0x7A, 0x80]).unwrap_err(),
358            Error::BufferTooShort { .. }
359        ));
360    }
361
362    #[test]
363    fn parse_rejects_section_length_overflow() {
364        let mut bytes = build_mpe_ifec(0, 0, 0, true, 0, 0, sample_rtp(), &[]);
365        let fake_sl: u16 = (bytes.len() as u16) + 100 - HEADER_LEN as u16;
366        bytes[1] = (bytes[1] & 0xF0) | ((fake_sl >> 8) as u8 & 0x0F);
367        bytes[2] = (fake_sl & 0xFF) as u8;
368        assert!(matches!(
369            MpeIfecSection::parse(&bytes).unwrap_err(),
370            Error::SectionLengthOverflow { .. }
371        ));
372    }
373
374    #[test]
375    fn serialize_round_trip() {
376        let ifec = [0xDEu8, 0xAD, 0xBE, 0xEF, 0x00];
377        let original = MpeIfecSection {
378            private_indicator: false,
379            burst_number: 200,
380            ifec_burst_size: 32,
381            version: 31,
382            current_next_indicator: false,
383            section_number: 2,
384            last_section_number: 4,
385            real_time_parameters: sample_rtp(),
386            ifec_data: &ifec,
387        };
388        let mut buf = vec![0u8; original.serialized_len()];
389        original.serialize_into(&mut buf).unwrap();
390        assert_eq!(MpeIfecSection::parse(&buf).unwrap(), original);
391    }
392
393    #[test]
394    fn serialize_rejects_output_buffer_too_small() {
395        let s = MpeIfecSection {
396            private_indicator: false,
397            burst_number: 0,
398            ifec_burst_size: 0,
399            version: 0,
400            current_next_indicator: true,
401            section_number: 0,
402            last_section_number: 0,
403            real_time_parameters: sample_rtp(),
404            ifec_data: &[],
405        };
406        let mut buf = vec![0u8; 2];
407        assert!(matches!(
408            s.serialize_into(&mut buf).unwrap_err(),
409            Error::OutputBufferTooSmall { .. }
410        ));
411    }
412
413    #[test]
414    fn table_trait_constants() {
415        assert_eq!(TABLE_ID, 0x7A);
416        assert_eq!(PID, 0x0000);
417    }
418
419    #[test]
420    fn parse_rejects_zero_section_length() {
421        let mut buf = vec![0u8; 64];
422        buf[0] = TABLE_ID;
423        buf[1] = 0xF0;
424        buf[2] = 0x00;
425        for b in &mut buf[3..] {
426            *b = 0xFF;
427        }
428        assert!(matches!(
429            MpeIfecSection::parse(&buf).unwrap_err(),
430            Error::SectionLengthOverflow { .. }
431        ));
432    }
433
434    #[cfg(feature = "serde")]
435    #[test]
436    fn serde_json_serializes_fields() {
437        // Serialize-only: assert serialization yields valid, field-bearing JSON.
438        let ifec = [0x01u8, 0x02];
439        let bytes = build_mpe_ifec(7, 8, 3, true, 0, 0, sample_rtp(), &ifec);
440        let s = MpeIfecSection::parse(&bytes).unwrap();
441        let v: serde_json::Value = serde_json::to_value(&s).unwrap();
442        assert_eq!(v["burst_number"], 7);
443        assert_eq!(v["ifec_burst_size"], 8);
444        assert_eq!(v["version"], 3);
445        assert_eq!(v["ifec_data"], serde_json::json!([0x01, 0x02]));
446        assert_eq!(v["real_time_parameters"]["prev_burst_size"], 0x0001_2345);
447        assert_eq!(v["real_time_parameters"]["mpe_boundary"], true);
448    }
449}