1use crate::descriptors::DescriptorLoop;
13use crate::error::{Error, Result};
14use crate::traits::Table;
15use dvb_common::{Parse, Serialize};
16
17pub const TABLE_ID: u8 = 0x73;
19pub 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#[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 = 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 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 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(<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 let re = TotSection::parse(&buf).unwrap();
209 assert_eq!(tot, re);
210 }
211}