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))]
122pub struct MpeIfec<'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 MpeIfec<'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: "MpeIfec",
154            });
155        }
156
157        if bytes[0] != TABLE_ID {
158            return Err(Error::UnexpectedTableId {
159                table_id: bytes[0],
160                what: "MpeIfec",
161                expected: &[TABLE_ID],
162            });
163        }
164
165        let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
166        let total = HEADER_LEN + section_length;
167        if bytes.len() < total {
168            return Err(Error::SectionLengthOverflow {
169                declared: section_length,
170                available: bytes.len() - HEADER_LEN,
171            });
172        }
173
174        let private_indicator = (bytes[1] & 0x40) != 0;
175        let burst_number = bytes[3];
176        let ifec_burst_size = bytes[4];
177        // byte 5: reserved(2) | version(5) | current_next_indicator(1)
178        let version = (bytes[5] >> 1) & 0x1F;
179        let current_next_indicator = (bytes[5] & 0x01) != 0;
180        let section_number = bytes[6];
181        let last_section_number = bytes[7];
182
183        let rtp_start = HEADER_LEN + EXTENSION_HEADER_LEN;
184        let real_time_parameters = RealTimeParameters::from_bytes([
185            bytes[rtp_start],
186            bytes[rtp_start + 1],
187            bytes[rtp_start + 2],
188            bytes[rtp_start + 3],
189        ]);
190
191        let data_start = rtp_start + RTP_LEN;
192        let data_end = total - CRC_LEN;
193        let ifec_data = &bytes[data_start..data_end];
194
195        Ok(MpeIfec {
196            private_indicator,
197            burst_number,
198            ifec_burst_size,
199            version,
200            current_next_indicator,
201            section_number,
202            last_section_number,
203            real_time_parameters,
204            ifec_data,
205        })
206    }
207}
208
209impl Serialize for MpeIfec<'_> {
210    type Error = crate::error::Error;
211
212    fn serialized_len(&self) -> usize {
213        HEADER_LEN + EXTENSION_HEADER_LEN + RTP_LEN + self.ifec_data.len() + CRC_LEN
214    }
215
216    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
217        let len = self.serialized_len();
218        if buf.len() < len {
219            return Err(Error::OutputBufferTooSmall {
220                need: len,
221                have: buf.len(),
222            });
223        }
224
225        let section_length = (len - HEADER_LEN) as u16;
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}
261
262impl<'a> Table<'a> for MpeIfec<'a> {
263    const TABLE_ID: u8 = TABLE_ID;
264    const PID: u16 = PID;
265}
266
267impl<'a> crate::traits::TableDef<'a> for MpeIfec<'a> {
268    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
269    const NAME: &'static str = "MPE_IFEC";
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[allow(clippy::too_many_arguments)]
277    fn build_mpe_ifec(
278        burst_number: u8,
279        ifec_burst_size: u8,
280        version: u8,
281        current_next: bool,
282        section_number: u8,
283        last_section_number: u8,
284        rtp: RealTimeParameters,
285        ifec_data: &[u8],
286    ) -> Vec<u8> {
287        let s = MpeIfec {
288            private_indicator: true,
289            burst_number,
290            ifec_burst_size,
291            version,
292            current_next_indicator: current_next,
293            section_number,
294            last_section_number,
295            real_time_parameters: rtp,
296            ifec_data,
297        };
298        let mut buf = vec![0u8; s.serialized_len()];
299        s.serialize_into(&mut buf).unwrap();
300        buf
301    }
302
303    fn sample_rtp() -> RealTimeParameters {
304        RealTimeParameters {
305            delta_t: 0x0ABC,
306            mpe_boundary: true,
307            frame_boundary: false,
308            prev_burst_size: 0x0001_2345,
309        }
310    }
311
312    #[test]
313    fn parse_happy_path() {
314        let ifec = [0x11u8, 0x22, 0x33, 0x44];
315        let bytes = build_mpe_ifec(5, 16, 9, true, 1, 3, sample_rtp(), &ifec);
316        let s = MpeIfec::parse(&bytes).unwrap();
317        assert!(s.private_indicator);
318        assert_eq!(s.burst_number, 5);
319        assert_eq!(s.ifec_burst_size, 16);
320        assert_eq!(s.version, 9);
321        assert!(s.current_next_indicator);
322        assert_eq!(s.section_number, 1);
323        assert_eq!(s.last_section_number, 3);
324        assert_eq!(s.real_time_parameters, sample_rtp());
325        assert_eq!(s.ifec_data, &ifec[..]);
326    }
327
328    #[test]
329    fn parse_empty_ifec_data() {
330        let bytes = build_mpe_ifec(0, 0, 0, false, 0, 0, sample_rtp(), &[]);
331        let s = MpeIfec::parse(&bytes).unwrap();
332        assert_eq!(s.burst_number, 0);
333        assert_eq!(s.version, 0);
334        assert!(!s.current_next_indicator);
335        assert!(s.ifec_data.is_empty());
336        assert_eq!(s.real_time_parameters, sample_rtp());
337    }
338
339    #[test]
340    fn rtp_bit_packing_round_trips_extremes() {
341        let rtp = RealTimeParameters {
342            delta_t: 0x0FFF,
343            mpe_boundary: false,
344            frame_boundary: true,
345            prev_burst_size: 0x0003_FFFF,
346        };
347        assert_eq!(RealTimeParameters::from_bytes(rtp.to_bytes()), rtp);
348    }
349
350    #[test]
351    fn parse_rejects_wrong_tag() {
352        let mut bytes = build_mpe_ifec(0, 0, 0, true, 0, 0, sample_rtp(), &[]);
353        bytes[0] = 0x70; // not 0x7A
354        assert!(matches!(
355            MpeIfec::parse(&bytes).unwrap_err(),
356            Error::UnexpectedTableId { table_id: 0x70, .. }
357        ));
358    }
359
360    #[test]
361    fn parse_rejects_short_buffer() {
362        assert!(matches!(
363            MpeIfec::parse(&[0x7A, 0x80]).unwrap_err(),
364            Error::BufferTooShort { .. }
365        ));
366    }
367
368    #[test]
369    fn parse_rejects_section_length_overflow() {
370        let mut bytes = build_mpe_ifec(0, 0, 0, true, 0, 0, sample_rtp(), &[]);
371        let fake_sl: u16 = (bytes.len() as u16) + 100 - HEADER_LEN as u16;
372        bytes[1] = (bytes[1] & 0xF0) | ((fake_sl >> 8) as u8 & 0x0F);
373        bytes[2] = (fake_sl & 0xFF) as u8;
374        assert!(matches!(
375            MpeIfec::parse(&bytes).unwrap_err(),
376            Error::SectionLengthOverflow { .. }
377        ));
378    }
379
380    #[test]
381    fn serialize_round_trip() {
382        let ifec = [0xDEu8, 0xAD, 0xBE, 0xEF, 0x00];
383        let original = MpeIfec {
384            private_indicator: false,
385            burst_number: 200,
386            ifec_burst_size: 32,
387            version: 31,
388            current_next_indicator: false,
389            section_number: 2,
390            last_section_number: 4,
391            real_time_parameters: sample_rtp(),
392            ifec_data: &ifec,
393        };
394        let mut buf = vec![0u8; original.serialized_len()];
395        original.serialize_into(&mut buf).unwrap();
396        assert_eq!(MpeIfec::parse(&buf).unwrap(), original);
397    }
398
399    #[test]
400    fn serialize_rejects_output_buffer_too_small() {
401        let s = MpeIfec {
402            private_indicator: false,
403            burst_number: 0,
404            ifec_burst_size: 0,
405            version: 0,
406            current_next_indicator: true,
407            section_number: 0,
408            last_section_number: 0,
409            real_time_parameters: sample_rtp(),
410            ifec_data: &[],
411        };
412        let mut buf = vec![0u8; 2];
413        assert!(matches!(
414            s.serialize_into(&mut buf).unwrap_err(),
415            Error::OutputBufferTooSmall { .. }
416        ));
417    }
418
419    #[test]
420    fn table_trait_constants() {
421        assert_eq!(<MpeIfec as Table>::TABLE_ID, 0x7A);
422        assert_eq!(<MpeIfec as Table>::PID, 0x0000);
423    }
424
425    #[cfg(feature = "serde")]
426    #[test]
427    fn serde_json_serializes_fields() {
428        // Serialize-only: assert serialization yields valid, field-bearing JSON.
429        let ifec = [0x01u8, 0x02];
430        let bytes = build_mpe_ifec(7, 8, 3, true, 0, 0, sample_rtp(), &ifec);
431        let s = MpeIfec::parse(&bytes).unwrap();
432        let v: serde_json::Value = serde_json::to_value(&s).unwrap();
433        assert_eq!(v["burst_number"], 7);
434        assert_eq!(v["ifec_burst_size"], 8);
435        assert_eq!(v["version"], 3);
436        assert_eq!(v["ifec_data"], serde_json::json!([0x01, 0x02]));
437        assert_eq!(v["real_time_parameters"]["prev_burst_size"], 0x0001_2345);
438        assert_eq!(v["real_time_parameters"]["mpe_boundary"], true);
439    }
440}