1use crate::descriptors::DescriptorLoop;
13use crate::error::{Error, Result};
14use dvb_common::{Parse, Serialize};
15
16pub const TABLE_ID: u8 = 0x73;
18pub const PID: u16 = 0x0014;
20
21const HEADER_LEN: usize = 3;
22const UTC_TIME_LEN: usize = 5;
23const DESC_LOOP_LEN_FIELD: usize = 2;
24const CRC_LEN: usize = 4;
25const MIN_SECTION_LEN: usize = HEADER_LEN + UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + CRC_LEN;
26
27#[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 pub utc_time_raw: [u8; 5],
34 pub descriptors: DescriptorLoop<'a>,
38}
39
40#[cfg(feature = "chrono")]
41impl TotSection<'_> {
42 #[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 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 = super::check_section_length(
86 bytes.len(),
87 HEADER_LEN,
88 section_length as usize,
89 MIN_SECTION_LEN,
90 )?;
91 let utc_time_raw = [bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
92 let dl_pos = HEADER_LEN + UTC_TIME_LEN;
93 let dl = (((bytes[dl_pos] & 0x0F) as usize) << 8) | bytes[dl_pos + 1] as usize;
94 let d_start = dl_pos + DESC_LOOP_LEN_FIELD;
95 let d_end = d_start + dl;
96 if d_end > total - CRC_LEN {
97 return Err(Error::SectionLengthOverflow {
98 declared: dl,
99 available: (total - CRC_LEN).saturating_sub(d_start),
100 });
101 }
102 Ok(TotSection {
103 utc_time_raw,
104 descriptors: DescriptorLoop::new(&bytes[d_start..d_end]),
105 })
106 }
107}
108
109impl Serialize for TotSection<'_> {
110 type Error = crate::error::Error;
111 fn serialized_len(&self) -> usize {
112 HEADER_LEN + UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + self.descriptors.len() + CRC_LEN
113 }
114 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
115 let len = self.serialized_len();
116 if buf.len() < len {
117 return Err(Error::OutputBufferTooSmall {
118 need: len,
119 have: buf.len(),
120 });
121 }
122 let section_length = (len - HEADER_LEN) as u16;
123 if section_length > 0x0FFF {
124 return Err(Error::SectionLengthOverflow {
125 declared: section_length as usize,
126 available: 0x0FFF,
127 });
128 }
129 buf[0] = TABLE_ID;
130 buf[1] = 0x70 | ((section_length >> 8) as u8 & 0x0F);
133 buf[2] = (section_length & 0xFF) as u8;
134 buf[3..8].copy_from_slice(&self.utc_time_raw);
135 let dl = self.descriptors.len() as u16;
136 buf[8] = 0xF0 | ((dl >> 8) as u8 & 0x0F);
137 buf[9] = (dl & 0xFF) as u8;
138 let d_end = 10 + self.descriptors.len();
139 buf[10..d_end].copy_from_slice(self.descriptors.raw());
140 let crc_pos = len - CRC_LEN;
141 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
142 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
143 Ok(len)
144 }
145}
146impl<'a> crate::traits::TableDef<'a> for TotSection<'a> {
147 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
148 const NAME: &'static str = "TIME_OFFSET";
149}
150
151#[cfg(test)]
152mod tests {
153 use super::*;
154
155 fn build_tot(desc: &[u8]) -> Vec<u8> {
156 let section_length = (UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + desc.len() + CRC_LEN) as u16;
157 let mut v = Vec::new();
158 v.push(TABLE_ID);
159 v.push(0x70 | ((section_length >> 8) as u8 & 0x0F));
161 v.push((section_length & 0xFF) as u8);
162 v.extend_from_slice(&[0xE4, 0x09, 0x12, 0x34, 0x56]);
163 let dl = desc.len() as u16;
164 v.push(0xF0 | ((dl >> 8) as u8 & 0x0F));
165 v.push((dl & 0xFF) as u8);
166 v.extend_from_slice(desc);
167 let crc = dvb_common::crc32_mpeg2::compute(&v);
168 v.extend_from_slice(&crc.to_be_bytes());
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(<o);
187 let tot = TotSection::parse(&bytes).unwrap();
188 assert_eq!(tot.descriptors.raw(), <o[..]);
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(<o);
205 let tot = TotSection::parse(&bytes).unwrap();
206 let mut buf = vec![0u8; tot.serialized_len()];
207 tot.serialize_into(&mut buf).unwrap();
208 assert_eq!(buf, bytes, "TOT byte-identity against hand-built input");
209 let re = TotSection::parse(&buf).unwrap();
210 assert_eq!(tot, re);
211 }
212
213 #[test]
214 fn parse_rejects_zero_section_length() {
215 let mut buf = vec![0u8; 64];
216 buf[0] = TABLE_ID;
217 buf[1] = 0xF0;
218 buf[2] = 0x00;
219 for b in &mut buf[3..] {
220 *b = 0xFF;
221 }
222 assert!(matches!(
223 TotSection::parse(&buf).unwrap_err(),
224 Error::SectionLengthOverflow { .. }
225 ));
226 }
227}