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 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 tva_id = u16::from_be_bytes([chunk[0], chunk[1]]);
133 let running_status = TvaRunningStatus::from_u8(chunk[2] & RUNNING_STATUS_MAX);
134 entries.push(TvaIdEntry {
135 tva_id,
136 running_status,
137 });
138 }
139 Ok(Self { entries })
140 }
141}
142
143impl Serialize for TvaIdDescriptor {
144 type Error = crate::error::Error;
145 fn serialized_len(&self) -> usize {
146 HEADER_LEN + self.entries.len() * ENTRY_LEN
147 }
148
149 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
150 for e in &self.entries {
151 if e.running_status.to_u8() > RUNNING_STATUS_MAX {
152 return Err(Error::InvalidDescriptor {
153 tag: TAG,
154 reason: "running_status exceeds 3 bits",
155 });
156 }
157 }
158 if self.entries.len() * ENTRY_LEN > u8::MAX as usize {
159 return Err(Error::InvalidDescriptor {
160 tag: TAG,
161 reason: "TVA_id_descriptor body exceeds 255 bytes",
162 });
163 }
164 let len = self.serialized_len();
165 if buf.len() < len {
166 return Err(Error::OutputBufferTooSmall {
167 need: len,
168 have: buf.len(),
169 });
170 }
171 buf[0] = TAG;
172 buf[1] = (self.entries.len() * ENTRY_LEN) as u8;
173 let mut pos = HEADER_LEN;
174 for e in &self.entries {
175 buf[pos..pos + 2].copy_from_slice(&e.tva_id.to_be_bytes());
176 buf[pos + 2] = 0xF8 | (e.running_status.to_u8() & RUNNING_STATUS_MAX);
178 pos += ENTRY_LEN;
179 }
180 Ok(len)
181 }
182}
183impl<'a> crate::traits::DescriptorDef<'a> for TvaIdDescriptor {
184 const TAG: u8 = TAG;
185 const NAME: &'static str = "TVA_ID";
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 #[test]
193 fn parse_single_entry() {
194 let bytes = [TAG, 3, 0x12, 0x34, 0xFC];
196 let d = TvaIdDescriptor::parse(&bytes).unwrap();
197 assert_eq!(d.entries.len(), 1);
198 assert_eq!(d.entries[0].tva_id, 0x1234);
199 assert_eq!(d.entries[0].running_status, TvaRunningStatus::Running);
200 }
201
202 #[test]
203 fn parse_multiple_entries() {
204 let bytes = [TAG, 6, 0x00, 0x01, 0x01, 0xAB, 0xCD, 0x06];
205 let d = TvaIdDescriptor::parse(&bytes).unwrap();
206 assert_eq!(d.entries.len(), 2);
207 assert_eq!(d.entries[0].tva_id, 0x0001);
208 assert_eq!(d.entries[0].running_status, TvaRunningStatus::NotYetRunning);
209 assert_eq!(d.entries[1].tva_id, 0xABCD);
210 assert_eq!(d.entries[1].running_status, TvaRunningStatus::Completed);
211 }
212
213 #[test]
214 fn parse_ignores_reserved_bits() {
215 let bytes = [TAG, 3, 0x00, 0x00, 0xFF];
216 let d = TvaIdDescriptor::parse(&bytes).unwrap();
217 assert_eq!(
218 d.entries[0].running_status,
219 TvaRunningStatus::Unallocated(0x07)
220 );
221 }
222
223 #[test]
224 fn parse_rejects_wrong_tag() {
225 assert!(matches!(
226 TvaIdDescriptor::parse(&[0x74, 0]).unwrap_err(),
227 Error::InvalidDescriptor { tag: 0x74, .. }
228 ));
229 }
230
231 #[test]
232 fn parse_rejects_length_not_multiple_of_3() {
233 let bytes = [TAG, 2, 0, 0];
234 assert!(matches!(
235 TvaIdDescriptor::parse(&bytes).unwrap_err(),
236 Error::InvalidDescriptor { .. }
237 ));
238 }
239
240 #[test]
241 fn empty_descriptor_valid() {
242 let bytes = [TAG, 0];
243 let d = TvaIdDescriptor::parse(&bytes).unwrap();
244 assert!(d.entries.is_empty());
245 }
246
247 #[test]
248 fn serialize_round_trip() {
249 let d = TvaIdDescriptor {
250 entries: vec![
251 TvaIdEntry {
252 tva_id: 0x1000,
253 running_status: TvaRunningStatus::StartsShortly,
254 },
255 TvaIdEntry {
256 tva_id: 0xFFFF,
257 running_status: TvaRunningStatus::Reserved,
258 },
259 ],
260 };
261 let mut buf = vec![0u8; d.serialized_len()];
262 d.serialize_into(&mut buf).unwrap();
263 assert_eq!(TvaIdDescriptor::parse(&buf).unwrap(), d);
264 }
265
266 #[test]
267 fn serialize_rejects_running_status_over_range() {
268 let d = TvaIdDescriptor {
269 entries: vec![TvaIdEntry {
270 tva_id: 0,
271 running_status: TvaRunningStatus::Unallocated(0x08),
272 }],
273 };
274 let mut buf = vec![0u8; d.serialized_len()];
275 assert!(matches!(
276 d.serialize_into(&mut buf).unwrap_err(),
277 Error::InvalidDescriptor { .. }
278 ));
279 }
280
281 #[cfg(feature = "serde")]
282 #[test]
283 fn serde_round_trip() {
284 let d = TvaIdDescriptor {
285 entries: vec![TvaIdEntry {
286 tva_id: 0x4242,
287 running_status: TvaRunningStatus::Running,
288 }],
289 };
290 let j = serde_json::to_string(&d).unwrap();
291 let _v: serde_json::Value = serde_json::from_str(&j).unwrap();
293 }
294
295 #[test]
296 fn tva_running_status_full_range_round_trip() {
297 for b in 0..=0xFF_u8 {
298 let rs = TvaRunningStatus::from_u8(b);
299 assert_eq!(rs.to_u8(), b, "round-trip failed for byte 0x{b:02X}");
300 }
301 }
302
303 #[test]
304 fn tva_running_status_name_for_known() {
305 assert_eq!(TvaRunningStatus::NotYetRunning.name(), "not yet running");
306 assert_eq!(TvaRunningStatus::Running.name(), "running");
307 assert_eq!(TvaRunningStatus::Completed.name(), "completed");
308 assert_eq!(TvaRunningStatus::Unallocated(0x07).name(), "unallocated");
309 }
310}