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(crate) utc_time_raw: [u8; 5],
36 pub descriptors: DescriptorLoop<'a>,
40}
41
42impl<'a> TotSection<'a> {
43 #[must_use]
49 pub fn utc_time_decoded(&self) -> Option<dvb_common::time::MjdBcdDateTime> {
50 dvb_common::time::decode_mjd_bcd(self.utc_time_raw)
51 }
52
53 pub fn set_utc_time_decoded(&mut self, dt: dvb_common::time::MjdBcdDateTime) -> Result<()> {
59 self.utc_time_raw = dvb_common::time::encode_mjd_bcd(dt).ok_or(Error::ValueOutOfRange {
60 field: "TotSection::utc_time",
61 reason: "date not representable in 16-bit MJD",
62 })?;
63 Ok(())
64 }
65
66 #[must_use]
68 pub fn utc_time_raw(&self) -> [u8; 5] {
69 self.utc_time_raw
70 }
71
72 #[must_use]
74 pub fn new(utc_time_raw: [u8; 5], descriptors: DescriptorLoop<'a>) -> Self {
75 Self {
76 utc_time_raw,
77 descriptors,
78 }
79 }
80}
81
82#[cfg(feature = "chrono")]
83impl TotSection<'_> {
84 #[must_use]
89 pub fn utc_time(&self) -> Option<chrono::DateTime<chrono::Utc>> {
90 dvb_common::time::decode_mjd_bcd_utc(self.utc_time_raw)
91 }
92
93 pub fn set_utc_time(&mut self, utc_time: chrono::DateTime<chrono::Utc>) -> Result<()> {
99 self.utc_time_raw =
100 dvb_common::time::encode_mjd_bcd_utc(utc_time).ok_or(Error::ValueOutOfRange {
101 field: "TotSection::utc_time",
102 reason: "date not representable in 16-bit MJD",
103 })?;
104 Ok(())
105 }
106}
107
108impl<'a> Parse<'a> for TotSection<'a> {
109 type Error = crate::error::Error;
110 fn parse(bytes: &'a [u8]) -> Result<Self> {
111 let min_len = HEADER_LEN + UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + CRC_LEN;
112 if bytes.len() < min_len {
113 return Err(Error::BufferTooShort {
114 need: min_len,
115 have: bytes.len(),
116 what: "TotSection",
117 });
118 }
119 if bytes[0] != TABLE_ID {
120 return Err(Error::UnexpectedTableId {
121 table_id: bytes[0],
122 what: "TotSection",
123 expected: &[TABLE_ID],
124 });
125 }
126 let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
127 let total = super::check_section_length(
128 bytes.len(),
129 HEADER_LEN,
130 section_length as usize,
131 MIN_SECTION_LEN,
132 )?;
133 let utc_time_raw = [bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
134 let dl_pos = HEADER_LEN + UTC_TIME_LEN;
135 let dl = (((bytes[dl_pos] & 0x0F) as usize) << 8) | bytes[dl_pos + 1] as usize;
136 let d_start = dl_pos + DESC_LOOP_LEN_FIELD;
137 let d_end = d_start + dl;
138 if d_end > total - CRC_LEN {
139 return Err(Error::SectionLengthOverflow {
140 declared: dl,
141 available: (total - CRC_LEN).saturating_sub(d_start),
142 });
143 }
144 Ok(TotSection {
145 utc_time_raw,
146 descriptors: DescriptorLoop::new(&bytes[d_start..d_end]),
147 })
148 }
149}
150
151impl Serialize for TotSection<'_> {
152 type Error = crate::error::Error;
153 fn serialized_len(&self) -> usize {
154 HEADER_LEN + UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + self.descriptors.len() + CRC_LEN
155 }
156 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
157 let len = self.serialized_len();
158 if buf.len() < len {
159 return Err(Error::OutputBufferTooSmall {
160 need: len,
161 have: buf.len(),
162 });
163 }
164 let section_length = (len - HEADER_LEN) as u16;
165 if section_length > 0x0FFF {
166 return Err(Error::SectionLengthOverflow {
167 declared: section_length as usize,
168 available: 0x0FFF,
169 });
170 }
171 buf[0] = TABLE_ID;
172 buf[1] = super::SECTION_B1_FLAGS_SHORT | ((section_length >> 8) as u8 & 0x0F);
175 buf[2] = (section_length & 0xFF) as u8;
176 buf[3..8].copy_from_slice(&self.utc_time_raw);
177 let dl = self.descriptors.len() as u16;
178 buf[8] = 0xF0 | ((dl >> 8) as u8 & 0x0F);
179 buf[9] = (dl & 0xFF) as u8;
180 let d_end = 10 + self.descriptors.len();
181 buf[10..d_end].copy_from_slice(self.descriptors.raw());
182 let crc_pos = len - CRC_LEN;
183 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
184 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
185 Ok(len)
186 }
187}
188impl<'a> crate::traits::TableDef<'a> for TotSection<'a> {
189 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
190 const NAME: &'static str = "TIME_OFFSET";
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 fn build_tot(desc: &[u8]) -> Vec<u8> {
198 let section_length = (UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + desc.len() + CRC_LEN) as u16;
199 let mut v = Vec::new();
200 v.push(TABLE_ID);
201 v.push(0x70 | ((section_length >> 8) as u8 & 0x0F));
203 v.push((section_length & 0xFF) as u8);
204 v.extend_from_slice(&[0xE4, 0x09, 0x12, 0x34, 0x56]);
205 let dl = desc.len() as u16;
206 v.push(0xF0 | ((dl >> 8) as u8 & 0x0F));
207 v.push((dl & 0xFF) as u8);
208 v.extend_from_slice(desc);
209 let crc = dvb_common::crc32_mpeg2::compute(&v);
210 v.extend_from_slice(&crc.to_be_bytes());
211 v
212 }
213
214 #[test]
215 fn parse_with_no_descriptors() {
216 let bytes = build_tot(&[]);
217 let tot = TotSection::parse(&bytes).unwrap();
218 assert_eq!(tot.utc_time_raw(), [0xE4, 0x09, 0x12, 0x34, 0x56]);
219 assert_eq!(tot.descriptors.raw(), &[] as &[u8]);
220 }
221
222 #[test]
223 fn parse_with_local_time_offset_descriptor() {
224 let lto = [
225 0x58u8, 13, b'G', b'B', b'R', 0x02, 0x00, 0x00, 0xE4, 0x09, 0x12, 0x34, 0x56, 0x01,
226 0x00,
227 ];
228 let bytes = build_tot(<o);
229 let tot = TotSection::parse(&bytes).unwrap();
230 assert_eq!(tot.descriptors.raw(), <o[..]);
231 }
232
233 #[test]
234 fn parse_rejects_wrong_tag() {
235 let mut bytes = build_tot(&[]);
236 bytes[0] = 0x70;
237 assert!(matches!(
238 TotSection::parse(&bytes).unwrap_err(),
239 Error::UnexpectedTableId { table_id: 0x70, .. }
240 ));
241 }
242
243 #[test]
244 fn serialize_round_trip() {
245 let lto = [0x58u8, 0];
246 let bytes = build_tot(<o);
247 let tot = TotSection::parse(&bytes).unwrap();
248 let mut buf = vec![0u8; tot.serialized_len()];
249 tot.serialize_into(&mut buf).unwrap();
250 assert_eq!(buf, bytes, "TOT byte-identity against hand-built input");
251 let re = TotSection::parse(&buf).unwrap();
252 assert_eq!(tot, re);
253 }
254
255 #[test]
256 fn parse_rejects_zero_section_length() {
257 let mut buf = vec![0u8; 64];
258 buf[0] = TABLE_ID;
259 buf[1] = 0xF0;
260 buf[2] = 0x00;
261 for b in &mut buf[3..] {
262 *b = 0xFF;
263 }
264 assert!(matches!(
265 TotSection::parse(&buf).unwrap_err(),
266 Error::SectionLengthOverflow { .. }
267 ));
268 }
269}