use super::descriptor_body;
use crate::error::{Error, Result};
use dvb_common::{Parse, Serialize};
pub const TAG: u8 = 0x45;
const HEADER_LEN: usize = 2;
const ENTRY_HEADER_LEN: usize = 2;
const MAX_BODY_LEN: usize = u8::MAX as usize;
const MAX_SERVICE_LEN: usize = u8::MAX as usize;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub enum VbiService<'a> {
Lines(Vec<VbiLine>),
Reserved(&'a [u8]),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct VbiLine {
pub field_parity: bool,
pub line_offset: u8,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct VbiDataEntry<'a> {
pub data_service_id: u8,
pub service_descriptor: VbiService<'a>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct VbiDataDescriptor<'a> {
pub entries: Vec<VbiDataEntry<'a>>,
}
impl<'a> Parse<'a> for VbiDataDescriptor<'a> {
type Error = crate::error::Error;
fn parse(bytes: &'a [u8]) -> Result<Self> {
let body = descriptor_body(
bytes,
TAG,
"VbiDataDescriptor",
"unexpected tag for VBI_data_descriptor",
)?;
let mut entries = Vec::new();
let mut pos = 0;
while pos < body.len() {
if pos + ENTRY_HEADER_LEN > body.len() {
return Err(Error::InvalidDescriptor {
tag: TAG,
reason: "truncated VBI data entry header",
});
}
let data_service_id = body[pos];
let svc_len = body[pos + 1] as usize;
pos += ENTRY_HEADER_LEN;
if pos + svc_len > body.len() {
return Err(Error::InvalidDescriptor {
tag: TAG,
reason: "data_service_descriptor_length exceeds descriptor body",
});
}
let svc_bytes = &body[pos..pos + svc_len];
pos += svc_len;
let service_descriptor = if matches!(data_service_id, 0x01 | 0x02 | 0x04..=0x07) {
let lines = svc_bytes
.iter()
.map(|&b| VbiLine {
field_parity: (b & 0x20) != 0,
line_offset: b & 0x1F,
})
.collect();
VbiService::Lines(lines)
} else {
VbiService::Reserved(svc_bytes)
};
entries.push(VbiDataEntry {
data_service_id,
service_descriptor,
});
}
Ok(Self { entries })
}
}
impl Serialize for VbiDataDescriptor<'_> {
type Error = crate::error::Error;
fn serialized_len(&self) -> usize {
HEADER_LEN
+ self
.entries
.iter()
.map(|e| {
ENTRY_HEADER_LEN
+ match &e.service_descriptor {
VbiService::Lines(lines) => lines.len(),
VbiService::Reserved(b) => b.len(),
}
})
.sum::<usize>()
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
let len = self.serialized_len();
if buf.len() < len {
return Err(Error::OutputBufferTooSmall {
need: len,
have: buf.len(),
});
}
let body_len = len - HEADER_LEN;
if body_len > MAX_BODY_LEN {
return Err(Error::InvalidDescriptor {
tag: TAG,
reason: "VBI_data_descriptor body exceeds 255 bytes",
});
}
buf[0] = TAG;
buf[1] = body_len as u8;
let mut pos = HEADER_LEN;
for e in &self.entries {
let svc_len = match &e.service_descriptor {
VbiService::Lines(lines) => lines.len(),
VbiService::Reserved(b) => b.len(),
};
if svc_len > MAX_SERVICE_LEN {
return Err(Error::InvalidDescriptor {
tag: TAG,
reason: "service_descriptor exceeds 255 bytes (8-bit length field)",
});
}
buf[pos] = e.data_service_id;
buf[pos + 1] = svc_len as u8;
pos += ENTRY_HEADER_LEN;
match &e.service_descriptor {
VbiService::Lines(lines) => {
for line in lines {
buf[pos] =
0xC0 | (u8::from(line.field_parity) << 5) | (line.line_offset & 0x1F);
pos += 1;
}
}
VbiService::Reserved(b) => {
buf[pos..pos + b.len()].copy_from_slice(b);
pos += b.len();
}
}
}
Ok(len)
}
}
impl<'a> crate::traits::DescriptorDef<'a> for VbiDataDescriptor<'a> {
const TAG: u8 = TAG;
const NAME: &'static str = "VBI_DATA";
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_single_entry() {
let bytes = [TAG, 4, 0x01, 0x02, 0xC1, 0xC2];
let d = VbiDataDescriptor::parse(&bytes).unwrap();
assert_eq!(d.entries.len(), 1);
assert_eq!(d.entries[0].data_service_id, 0x01);
match &d.entries[0].service_descriptor {
VbiService::Lines(lines) => {
assert_eq!(lines.len(), 2);
assert!(!lines[0].field_parity);
assert_eq!(lines[0].line_offset, 0x01);
assert!(!lines[1].field_parity);
assert_eq!(lines[1].line_offset, 0x02);
}
other => panic!("expected Lines, got {other:?}"),
}
}
#[test]
fn parse_multiple_entries() {
let bytes = [TAG, 7, 0x04, 0x01, 0xAA, 0x05, 0x02, 0xBB, 0xCC];
let d = VbiDataDescriptor::parse(&bytes).unwrap();
assert_eq!(d.entries.len(), 2);
assert_eq!(d.entries[0].data_service_id, 0x04);
match &d.entries[0].service_descriptor {
VbiService::Lines(lines) => {
assert_eq!(lines.len(), 1);
assert!(lines[0].field_parity);
assert_eq!(lines[0].line_offset, 0x0A);
}
other => panic!("expected Lines, got {other:?}"),
}
assert_eq!(d.entries[1].data_service_id, 0x05);
match &d.entries[1].service_descriptor {
VbiService::Lines(lines) => {
assert_eq!(lines.len(), 2);
assert!(lines[0].field_parity);
assert_eq!(lines[0].line_offset, 0x1B);
assert!(!lines[1].field_parity);
assert_eq!(lines[1].line_offset, 0x0C);
}
other => panic!("expected Lines, got {other:?}"),
}
}
#[test]
fn parse_entry_with_empty_service_block() {
let bytes = [TAG, 2, 0x06, 0x00];
let d = VbiDataDescriptor::parse(&bytes).unwrap();
assert_eq!(d.entries.len(), 1);
match &d.entries[0].service_descriptor {
VbiService::Lines(lines) => assert!(lines.is_empty()),
other => panic!("expected Lines, got {other:?}"),
}
}
#[test]
fn parse_reserved_data_service_id() {
let bytes = [TAG, 4, 0x00, 0x02, 0xDE, 0xAD];
let d = VbiDataDescriptor::parse(&bytes).unwrap();
assert_eq!(d.entries.len(), 1);
assert_eq!(d.entries[0].data_service_id, 0x00);
match &d.entries[0].service_descriptor {
VbiService::Reserved(b) => assert_eq!(*b, &[0xDE, 0xAD]),
other => panic!("expected Reserved, got {other:?}"),
}
}
#[test]
fn parse_rejects_wrong_tag() {
assert!(matches!(
VbiDataDescriptor::parse(&[0x46, 0]).unwrap_err(),
Error::InvalidDescriptor { tag: 0x46, .. }
));
}
#[test]
fn parse_rejects_short_buffer() {
let bytes = [TAG, 4, 0x01, 0x02];
assert!(matches!(
VbiDataDescriptor::parse(&bytes).unwrap_err(),
Error::BufferTooShort { .. }
));
}
#[test]
fn parse_rejects_inner_length_overrun() {
let bytes = [TAG, 3, 0x01, 0x05, 0xAA];
assert!(matches!(
VbiDataDescriptor::parse(&bytes).unwrap_err(),
Error::InvalidDescriptor { tag: TAG, .. }
));
}
#[test]
fn empty_descriptor_valid() {
let d = VbiDataDescriptor::parse(&[TAG, 0]).unwrap();
assert!(d.entries.is_empty());
}
#[test]
fn serialize_round_trip() {
let d = VbiDataDescriptor {
entries: vec![
VbiDataEntry {
data_service_id: 0x01,
service_descriptor: VbiService::Lines(vec![
VbiLine {
field_parity: false,
line_offset: 0x01,
},
VbiLine {
field_parity: false,
line_offset: 0x02,
},
VbiLine {
field_parity: false,
line_offset: 0x03,
},
]),
},
VbiDataEntry {
data_service_id: 0x04,
service_descriptor: VbiService::Lines(vec![]),
},
],
};
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(VbiDataDescriptor::parse(&buf).unwrap(), d);
}
#[test]
fn serialize_round_trip_reserved() {
let d = VbiDataDescriptor {
entries: vec![VbiDataEntry {
data_service_id: 0x80,
service_descriptor: VbiService::Reserved(&[0xDE, 0xAD]),
}],
};
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(VbiDataDescriptor::parse(&buf).unwrap(), d);
}
#[test]
fn byte_identity_with_reserved_bits() {
let bytes = [TAG, 4, 0x01, 0x02, 0xC1, 0xC2];
let d = VbiDataDescriptor::parse(&bytes).unwrap();
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(buf, bytes);
}
#[test]
fn data_service_id_0x03_is_reserved() {
let bytes = [TAG, 3, 0x03, 0x01, 0xAA];
let d = VbiDataDescriptor::parse(&bytes).unwrap();
assert_eq!(d.entries[0].data_service_id, 0x03);
match &d.entries[0].service_descriptor {
VbiService::Reserved(b) => assert_eq!(*b, &[0xAA]),
other => panic!("expected Reserved for id 0x03, got {other:?}"),
}
}
#[test]
fn serialize_rejects_small_buffer() {
let d = VbiDataDescriptor {
entries: vec![VbiDataEntry {
data_service_id: 0x01,
service_descriptor: VbiService::Lines(vec![VbiLine {
field_parity: false,
line_offset: 0x0A,
}]),
}],
};
let mut tiny = [0u8; 3];
assert!(matches!(
d.serialize_into(&mut tiny).unwrap_err(),
Error::OutputBufferTooSmall { .. }
));
}
#[cfg(feature = "serde")]
#[test]
fn serde_serialize_stable() {
let make = || VbiDataDescriptor {
entries: vec![VbiDataEntry {
data_service_id: 0x01,
service_descriptor: VbiService::Lines(vec![
VbiLine {
field_parity: false,
line_offset: 0x01,
},
VbiLine {
field_parity: false,
line_offset: 0x02,
},
]),
}],
};
let json = serde_json::to_string(&make()).unwrap();
assert!(json.contains("data_service_id"));
assert_eq!(json, serde_json::to_string(&make()).unwrap());
}
}