Skip to main content

dvb_si/tables/
tot.rs

1//! Time Offset Table — ETSI EN 300 468 §5.2.6.
2//!
3//! Carried on PID 0x0014 with table_id 0x73. Structure:
4//!   5-byte UTC time + descriptor loop + 4-byte CRC32.
5//!
6//! The TOT is the spec's framing exception: `section_syntax_indicator` SHALL
7//! be `0b0` (§5.2.6: "This 1-bit field shall be set to 0b0") yet the section
8//! still ends with a CRC_32. Do not route TOT bytes through the generic
9//! [`crate::section::Section`] short-form path — it would fold the CRC into
10//! the payload. Parse with [`TotSection::parse`] directly.
11
12use crate::descriptors::DescriptorLoop;
13use crate::error::{Error, Result};
14use crate::traits::Table;
15use dvb_common::{Parse, Serialize};
16
17/// table_id for Time Offset Table.
18pub const TABLE_ID: u8 = 0x73;
19/// Well-known PID on which TOT is carried (same as TDT).
20pub const PID: u16 = 0x0014;
21
22const HEADER_LEN: usize = 3;
23const UTC_TIME_LEN: usize = 5;
24const DESC_LOOP_LEN_FIELD: usize = 2;
25const CRC_LEN: usize = 4;
26
27/// Time Offset Table.
28#[derive(Debug, Clone, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize))]
30#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
31pub struct TotSection<'a> {
32    /// Raw 5-byte UTC time (16-bit MJD + 24-bit BCD HHMMSS).
33    pub utc_time_raw: [u8; 5],
34    /// Raw descriptor bytes (typically local_time_offset_descriptor tag 0x58).
35    /// Descriptor loop. Serializes as the typed descriptor sequence;
36    /// `.raw()` yields the wire bytes.
37    pub descriptors: DescriptorLoop<'a>,
38}
39
40#[cfg(feature = "chrono")]
41impl TotSection<'_> {
42    /// Decode `utc_time_raw` (16-bit MJD + 24-bit BCD UTC) to a UTC datetime.
43    ///
44    /// Returns `None` if the date/time fields are out of range. MJD→calendar
45    /// conversion per ETSI EN 300 468 Annex C.
46    #[must_use]
47    pub fn utc_time(&self) -> Option<chrono::DateTime<chrono::Utc>> {
48        dvb_common::time::decode_mjd_bcd_utc(self.utc_time_raw)
49    }
50
51    /// Set the UTC time, encoding it into the 40-bit `utc_time` field.
52    ///
53    /// # Errors
54    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if the date is
55    /// outside the representable 16-bit MJD range.
56    pub fn set_utc_time(&mut self, utc_time: chrono::DateTime<chrono::Utc>) -> Result<()> {
57        self.utc_time_raw =
58            dvb_common::time::encode_mjd_bcd_utc(utc_time).ok_or(Error::ValueOutOfRange {
59                field: "TotSection::utc_time",
60                reason: "date not representable in 16-bit MJD",
61            })?;
62        Ok(())
63    }
64}
65
66impl<'a> Parse<'a> for TotSection<'a> {
67    type Error = crate::error::Error;
68    fn parse(bytes: &'a [u8]) -> Result<Self> {
69        let min_len = HEADER_LEN + UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + CRC_LEN;
70        if bytes.len() < min_len {
71            return Err(Error::BufferTooShort {
72                need: min_len,
73                have: bytes.len(),
74                what: "TotSection",
75            });
76        }
77        if bytes[0] != TABLE_ID {
78            return Err(Error::UnexpectedTableId {
79                table_id: bytes[0],
80                what: "TotSection",
81                expected: &[TABLE_ID],
82            });
83        }
84        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
85        let total = HEADER_LEN + section_length as usize;
86        if bytes.len() < total {
87            return Err(Error::SectionLengthOverflow {
88                declared: section_length as usize,
89                available: bytes.len() - HEADER_LEN,
90            });
91        }
92        let utc_time_raw = [bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
93        let dl_pos = HEADER_LEN + UTC_TIME_LEN;
94        let dl = (((bytes[dl_pos] & 0x0F) as usize) << 8) | bytes[dl_pos + 1] as usize;
95        let d_start = dl_pos + DESC_LOOP_LEN_FIELD;
96        let d_end = d_start + dl;
97        if d_end > total - CRC_LEN {
98            return Err(Error::SectionLengthOverflow {
99                declared: dl,
100                available: total - CRC_LEN - d_start,
101            });
102        }
103        Ok(TotSection {
104            utc_time_raw,
105            descriptors: DescriptorLoop::new(&bytes[d_start..d_end]),
106        })
107    }
108}
109
110impl Serialize for TotSection<'_> {
111    type Error = crate::error::Error;
112    fn serialized_len(&self) -> usize {
113        HEADER_LEN + UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + self.descriptors.len() + CRC_LEN
114    }
115    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
116        let len = self.serialized_len();
117        if buf.len() < len {
118            return Err(Error::OutputBufferTooSmall {
119                need: len,
120                have: buf.len(),
121            });
122        }
123        let section_length = (len - HEADER_LEN) as u16;
124        buf[0] = TABLE_ID;
125        // §5.2.6: section_syntax_indicator SHALL be 0 for the TOT (despite the
126        // trailing CRC_32). 0x70 = SSI(0) | reserved_future_use(1) | reserved(11).
127        buf[1] = 0x70 | ((section_length >> 8) as u8 & 0x0F);
128        buf[2] = (section_length & 0xFF) as u8;
129        buf[3..8].copy_from_slice(&self.utc_time_raw);
130        let dl = self.descriptors.len() as u16;
131        buf[8] = 0xF0 | ((dl >> 8) as u8 & 0x0F);
132        buf[9] = (dl & 0xFF) as u8;
133        let d_end = 10 + self.descriptors.len();
134        buf[10..d_end].copy_from_slice(self.descriptors.raw());
135        let crc_pos = len - CRC_LEN;
136        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
137        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
138        Ok(len)
139    }
140}
141
142impl<'a> Table<'a> for TotSection<'a> {
143    const TABLE_ID: u8 = TABLE_ID;
144    const PID: u16 = PID;
145}
146
147impl<'a> crate::traits::TableDef<'a> for TotSection<'a> {
148    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
149    const NAME: &'static str = "TIME_OFFSET";
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    fn build_tot(desc: &[u8]) -> Vec<u8> {
157        let section_length = (UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + desc.len() + CRC_LEN) as u16;
158        let mut v = Vec::new();
159        v.push(TABLE_ID);
160        // SSI=0 per §5.2.6 (the TOT exception: SSI=0 but CRC present).
161        v.push(0x70 | ((section_length >> 8) as u8 & 0x0F));
162        v.push((section_length & 0xFF) as u8);
163        v.extend_from_slice(&[0xE4, 0x09, 0x12, 0x34, 0x56]);
164        let dl = desc.len() as u16;
165        v.push(0xF0 | ((dl >> 8) as u8 & 0x0F));
166        v.push((dl & 0xFF) as u8);
167        v.extend_from_slice(desc);
168        v.extend_from_slice(&[0, 0, 0, 0]);
169        v
170    }
171
172    #[test]
173    fn parse_with_no_descriptors() {
174        let bytes = build_tot(&[]);
175        let tot = TotSection::parse(&bytes).unwrap();
176        assert_eq!(tot.utc_time_raw, [0xE4, 0x09, 0x12, 0x34, 0x56]);
177        assert_eq!(tot.descriptors.raw(), &[] as &[u8]);
178    }
179
180    #[test]
181    fn parse_with_local_time_offset_descriptor() {
182        let lto = [
183            0x58u8, 13, b'G', b'B', b'R', 0x02, 0x00, 0x00, 0xE4, 0x09, 0x12, 0x34, 0x56, 0x01,
184            0x00,
185        ];
186        let bytes = build_tot(&lto);
187        let tot = TotSection::parse(&bytes).unwrap();
188        assert_eq!(tot.descriptors.raw(), &lto[..]);
189    }
190
191    #[test]
192    fn parse_rejects_wrong_tag() {
193        let mut bytes = build_tot(&[]);
194        bytes[0] = 0x70;
195        assert!(matches!(
196            TotSection::parse(&bytes).unwrap_err(),
197            Error::UnexpectedTableId { table_id: 0x70, .. }
198        ));
199    }
200
201    #[test]
202    fn serialize_round_trip() {
203        let lto = [0x58u8, 0];
204        let bytes = build_tot(&lto);
205        let tot = TotSection::parse(&bytes).unwrap();
206        let mut buf = vec![0u8; tot.serialized_len()];
207        tot.serialize_into(&mut buf).unwrap();
208        let re = TotSection::parse(&buf).unwrap();
209        assert_eq!(tot, re);
210    }
211}