1use crate::error::{Error, Result};
7use crate::traits::Table;
8use dvb_common::{Parse, Serialize};
9
10pub const TABLE_ID: u8 = 0x70;
12pub const PID: u16 = 0x0014;
14
15const HEADER_LEN: usize = 3;
16const UTC_TIME_LEN: usize = 5;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21pub struct Tdt {
22 pub utc_time_raw: [u8; 5],
25}
26
27impl Tdt {
28 #[cfg(feature = "chrono")]
30 #[must_use]
31 pub fn utc_time(&self) -> Option<chrono::DateTime<chrono::Utc>> {
32 use chrono::{NaiveDate, NaiveDateTime, TimeZone};
33 let mjd = u16::from_be_bytes([self.utc_time_raw[0], self.utc_time_raw[1]]);
34 let (y, m, d) = mjd_to_ymd(mjd);
35 let h = bcd(self.utc_time_raw[2])?;
36 let mi = bcd(self.utc_time_raw[3])?;
37 let s = bcd(self.utc_time_raw[4])?;
38 let date = NaiveDate::from_ymd_opt(y, m, d)?;
39 let time = chrono::NaiveTime::from_hms_opt(h.into(), mi.into(), s.into())?;
40 chrono::Utc
41 .from_local_datetime(&NaiveDateTime::new(date, time))
42 .single()
43 }
44}
45
46#[cfg(feature = "chrono")]
47fn bcd(b: u8) -> Option<u8> {
48 let hi = b >> 4;
49 let lo = b & 0x0F;
50 if hi > 9 || lo > 9 {
51 return None;
52 }
53 Some(hi * 10 + lo)
54}
55
56#[cfg(feature = "chrono")]
57fn mjd_to_ymd(mjd: u16) -> (i32, u32, u32) {
58 let mjd = i64::from(mjd);
59 let y_prime = ((mjd as f64 - 15_078.2) / 365.25) as i64;
60 let m_prime = ((mjd as f64 - 14_956.1 - (y_prime as f64 * 365.25).floor()) / 30.6001) as i64;
61 let d = mjd
62 - 14_956
63 - (y_prime as f64 * 365.25).floor() as i64
64 - (m_prime as f64 * 30.6001).floor() as i64;
65 let k = if m_prime == 14 || m_prime == 15 { 1 } else { 0 };
66 let y = y_prime + k + 1900;
67 let m = m_prime - 1 - k * 12;
68 (y as i32, m as u32, d as u32)
69}
70
71impl<'a> Parse<'a> for Tdt {
72 type Error = crate::error::Error;
73 fn parse(bytes: &'a [u8]) -> Result<Self> {
74 let min_len = HEADER_LEN + UTC_TIME_LEN;
75 if bytes.len() < min_len {
76 return Err(Error::BufferTooShort {
77 need: min_len,
78 have: bytes.len(),
79 what: "Tdt",
80 });
81 }
82 if bytes[0] != TABLE_ID {
83 return Err(Error::UnexpectedTableId {
84 table_id: bytes[0],
85 what: "Tdt",
86 expected: &[TABLE_ID],
87 });
88 }
89 let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
90 if section_length as usize != UTC_TIME_LEN {
91 return Err(Error::SectionLengthOverflow {
92 declared: section_length as usize,
93 available: UTC_TIME_LEN,
94 });
95 }
96 let utc_time_raw = [bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
97 Ok(Tdt { utc_time_raw })
98 }
99}
100
101impl Serialize for Tdt {
102 type Error = crate::error::Error;
103 fn serialized_len(&self) -> usize {
104 HEADER_LEN + UTC_TIME_LEN
105 }
106 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
107 let len = self.serialized_len();
108 if buf.len() < len {
109 return Err(Error::OutputBufferTooSmall {
110 need: len,
111 have: buf.len(),
112 });
113 }
114 buf[0] = TABLE_ID;
115 buf[1] = 0x70 | ((UTC_TIME_LEN as u16 >> 8) as u8 & 0x0F);
116 buf[2] = UTC_TIME_LEN as u8;
117 buf[3..8].copy_from_slice(&self.utc_time_raw);
118 Ok(len)
119 }
120}
121
122impl<'a> Table<'a> for Tdt {
123 const TABLE_ID: u8 = TABLE_ID;
124 const PID: u16 = PID;
125}
126
127impl<'a> crate::traits::TableDef<'a> for Tdt {
128 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
129 const NAME: &'static str = "TIME_AND_DATE";
130}
131
132#[cfg(test)]
133mod tests {
134 use super::*;
135
136 #[test]
137 fn parse_extracts_utc_time_raw() {
138 let bytes = [TABLE_ID, 0x70, 0x05, 0xE4, 0x09, 0x12, 0x34, 0x56];
139 let tdt = Tdt::parse(&bytes).unwrap();
140 assert_eq!(tdt.utc_time_raw, [0xE4, 0x09, 0x12, 0x34, 0x56]);
141 }
142
143 #[test]
144 fn parse_rejects_wrong_tag() {
145 let bytes = [0x71, 0x70, 0x05, 0, 0, 0, 0, 0];
146 assert!(matches!(
147 Tdt::parse(&bytes).unwrap_err(),
148 Error::UnexpectedTableId { table_id: 0x71, .. }
149 ));
150 }
151
152 #[test]
153 fn parse_rejects_wrong_section_length() {
154 let bytes = [TABLE_ID, 0x70, 0x04, 0, 0, 0, 0, 0];
155 assert!(matches!(
156 Tdt::parse(&bytes).unwrap_err(),
157 Error::SectionLengthOverflow { .. }
158 ));
159 }
160
161 #[test]
162 fn serialize_round_trip() {
163 let tdt = Tdt {
164 utc_time_raw: [0xE4, 0x09, 0x12, 0x34, 0x56],
165 };
166 let mut buf = vec![0u8; tdt.serialized_len()];
167 tdt.serialize_into(&mut buf).unwrap();
168 let re = Tdt::parse(&buf).unwrap();
169 assert_eq!(tdt, re);
170 }
171
172 #[test]
173 fn utc_time_decodes_to_chrono() {
174 let tdt = Tdt {
175 utc_time_raw: [0xEA, 0x19, 0x12, 0x34, 0x56],
176 };
177 let dt = tdt.utc_time();
178 assert!(dt.is_some());
179 }
180}