1use super::descriptor_body;
10use crate::error::{Error, Result};
11use alloc::vec::Vec;
12use dvb_common::{Parse, Serialize};
13
14pub const TAG: u8 = 0x75;
16const HEADER_LEN: usize = 2;
17const ENTRY_LEN: usize = 3;
18
19const RUNNING_STATUS_MAX: u8 = 0x07;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize))]
28#[non_exhaustive]
29pub enum TvaRunningStatus {
30 Reserved,
32 NotYetRunning,
34 StartsShortly,
36 Paused,
38 Running,
40 Cancelled,
42 Completed,
44 Unallocated(u8),
46}
47
48impl TvaRunningStatus {
49 #[must_use]
50 pub fn from_u8(v: u8) -> Self {
53 match v {
54 0 => Self::Reserved,
55 1 => Self::NotYetRunning,
56 2 => Self::StartsShortly,
57 3 => Self::Paused,
58 4 => Self::Running,
59 5 => Self::Cancelled,
60 6 => Self::Completed,
61 v => Self::Unallocated(v),
62 }
63 }
64
65 #[must_use]
66 pub const fn to_u8(self) -> u8 {
68 match self {
69 Self::Reserved => 0,
70 Self::NotYetRunning => 1,
71 Self::StartsShortly => 2,
72 Self::Paused => 3,
73 Self::Running => 4,
74 Self::Cancelled => 5,
75 Self::Completed => 6,
76 Self::Unallocated(v) => v,
77 }
78 }
79
80 #[must_use]
81 pub fn name(self) -> &'static str {
83 match self {
84 Self::Reserved => "reserved",
85 Self::NotYetRunning => "not yet running",
86 Self::StartsShortly => "starts shortly",
87 Self::Paused => "paused",
88 Self::Running => "running",
89 Self::Cancelled => "cancelled",
90 Self::Completed => "completed",
91 Self::Unallocated(_) => "unallocated",
92 }
93 }
94}
95dvb_common::impl_spec_display!(TvaRunningStatus, Unallocated);
96
97#[derive(Debug, Clone, PartialEq, Eq)]
99#[cfg_attr(feature = "serde", derive(serde::Serialize))]
100pub struct TvaIdEntry {
101 pub tva_id: u16,
103 pub running_status: TvaRunningStatus,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
109#[cfg_attr(feature = "serde", derive(serde::Serialize))]
110pub struct TvaIdDescriptor {
111 pub entries: Vec<TvaIdEntry>,
113}
114
115impl<'a> Parse<'a> for TvaIdDescriptor {
116 type Error = crate::error::Error;
117 fn parse(bytes: &'a [u8]) -> Result<Self> {
118 let body = descriptor_body(
119 bytes,
120 TAG,
121 "TvaIdDescriptor",
122 "unexpected tag for TVA_id_descriptor",
123 )?;
124 if body.len() % ENTRY_LEN != 0 {
125 return Err(Error::InvalidDescriptor {
126 tag: TAG,
127 reason: "TVA_id_descriptor length must be a multiple of 3",
128 });
129 }
130 let mut entries = Vec::with_capacity(body.len() / ENTRY_LEN);
131 for chunk in body.chunks_exact(ENTRY_LEN) {
132 let (id_bytes, rest) = chunk.split_first_chunk::<2>().unwrap();
133 let tva_id = u16::from_be_bytes(*id_bytes);
134 let running_status = TvaRunningStatus::from_u8(rest[0] & RUNNING_STATUS_MAX);
135 entries.push(TvaIdEntry {
136 tva_id,
137 running_status,
138 });
139 }
140 Ok(Self { entries })
141 }
142}
143
144impl Serialize for TvaIdDescriptor {
145 type Error = crate::error::Error;
146 fn serialized_len(&self) -> usize {
147 HEADER_LEN + self.entries.len() * ENTRY_LEN
148 }
149
150 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
151 for e in &self.entries {
152 if e.running_status.to_u8() > RUNNING_STATUS_MAX {
153 return Err(Error::InvalidDescriptor {
154 tag: TAG,
155 reason: "running_status exceeds 3 bits",
156 });
157 }
158 }
159 if self.entries.len() * ENTRY_LEN > u8::MAX as usize {
160 return Err(Error::InvalidDescriptor {
161 tag: TAG,
162 reason: "TVA_id_descriptor body exceeds 255 bytes",
163 });
164 }
165 let len = self.serialized_len();
166 if buf.len() < len {
167 return Err(Error::OutputBufferTooSmall {
168 need: len,
169 have: buf.len(),
170 });
171 }
172 buf[0] = TAG;
173 buf[1] = (self.entries.len() * ENTRY_LEN) as u8;
174 let mut pos = HEADER_LEN;
175 for e in &self.entries {
176 buf[pos..pos + 2].copy_from_slice(&e.tva_id.to_be_bytes());
177 buf[pos + 2] = 0xF8 | (e.running_status.to_u8() & RUNNING_STATUS_MAX);
179 pos += ENTRY_LEN;
180 }
181 Ok(len)
182 }
183}
184impl<'a> crate::traits::DescriptorDef<'a> for TvaIdDescriptor {
185 const TAG: u8 = TAG;
186 const NAME: &'static str = "TVA_ID";
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 #[test]
194 fn parse_single_entry() {
195 let bytes = [TAG, 3, 0x12, 0x34, 0xFC];
197 let d = TvaIdDescriptor::parse(&bytes).unwrap();
198 assert_eq!(d.entries.len(), 1);
199 assert_eq!(d.entries[0].tva_id, 0x1234);
200 assert_eq!(d.entries[0].running_status, TvaRunningStatus::Running);
201 }
202
203 #[test]
204 fn parse_multiple_entries() {
205 let bytes = [TAG, 6, 0x00, 0x01, 0x01, 0xAB, 0xCD, 0x06];
206 let d = TvaIdDescriptor::parse(&bytes).unwrap();
207 assert_eq!(d.entries.len(), 2);
208 assert_eq!(d.entries[0].tva_id, 0x0001);
209 assert_eq!(d.entries[0].running_status, TvaRunningStatus::NotYetRunning);
210 assert_eq!(d.entries[1].tva_id, 0xABCD);
211 assert_eq!(d.entries[1].running_status, TvaRunningStatus::Completed);
212 }
213
214 #[test]
215 fn parse_ignores_reserved_bits() {
216 let bytes = [TAG, 3, 0x00, 0x00, 0xFF];
217 let d = TvaIdDescriptor::parse(&bytes).unwrap();
218 assert_eq!(
219 d.entries[0].running_status,
220 TvaRunningStatus::Unallocated(0x07)
221 );
222 }
223
224 #[test]
225 fn parse_rejects_wrong_tag() {
226 assert!(matches!(
227 TvaIdDescriptor::parse(&[0x74, 0]).unwrap_err(),
228 Error::InvalidDescriptor { tag: 0x74, .. }
229 ));
230 }
231
232 #[test]
233 fn parse_rejects_length_not_multiple_of_3() {
234 let bytes = [TAG, 2, 0, 0];
235 assert!(matches!(
236 TvaIdDescriptor::parse(&bytes).unwrap_err(),
237 Error::InvalidDescriptor { .. }
238 ));
239 }
240
241 #[test]
242 fn empty_descriptor_valid() {
243 let bytes = [TAG, 0];
244 let d = TvaIdDescriptor::parse(&bytes).unwrap();
245 assert!(d.entries.is_empty());
246 }
247
248 #[test]
249 fn serialize_round_trip() {
250 let d = TvaIdDescriptor {
251 entries: vec![
252 TvaIdEntry {
253 tva_id: 0x1000,
254 running_status: TvaRunningStatus::StartsShortly,
255 },
256 TvaIdEntry {
257 tva_id: 0xFFFF,
258 running_status: TvaRunningStatus::Reserved,
259 },
260 ],
261 };
262 let mut buf = vec![0u8; d.serialized_len()];
263 d.serialize_into(&mut buf).unwrap();
264 assert_eq!(TvaIdDescriptor::parse(&buf).unwrap(), d);
265 }
266
267 #[test]
268 fn serialize_rejects_running_status_over_range() {
269 let d = TvaIdDescriptor {
270 entries: vec![TvaIdEntry {
271 tva_id: 0,
272 running_status: TvaRunningStatus::Unallocated(0x08),
273 }],
274 };
275 let mut buf = vec![0u8; d.serialized_len()];
276 assert!(matches!(
277 d.serialize_into(&mut buf).unwrap_err(),
278 Error::InvalidDescriptor { .. }
279 ));
280 }
281
282 #[cfg(feature = "serde")]
283 #[test]
284 fn serde_round_trip() {
285 let d = TvaIdDescriptor {
286 entries: vec![TvaIdEntry {
287 tva_id: 0x4242,
288 running_status: TvaRunningStatus::Running,
289 }],
290 };
291 let j = serde_json::to_string(&d).unwrap();
292 let _v: serde_json::Value = serde_json::from_str(&j).unwrap();
294 }
295
296 #[test]
297 fn tva_running_status_full_range_round_trip() {
298 for b in 0..=0xFF_u8 {
299 let rs = TvaRunningStatus::from_u8(b);
300 assert_eq!(rs.to_u8(), b, "round-trip failed for byte 0x{b:02X}");
301 }
302 }
303
304 #[test]
305 fn tva_running_status_name_for_known() {
306 assert_eq!(TvaRunningStatus::NotYetRunning.name(), "not yet running");
307 assert_eq!(TvaRunningStatus::Running.name(), "running");
308 assert_eq!(TvaRunningStatus::Completed.name(), "completed");
309 assert_eq!(TvaRunningStatus::Unallocated(0x07).name(), "unallocated");
310 }
311}