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