use super::*;
use broadcast_core::len::{need_in, need_out};
use broadcast_core::reserved::ReservedOnes;
const DESCRIPTOR_NUMBER_MASK: u8 = 0x0F;
const ICON_ID_MASK: u8 = 0x07;
const TRANSPORT_MODE_VALUE_MASK: u8 = 0x03;
const COORDINATE_SYSTEM_MASK: u8 = 0x07;
pub const IMAGE_ICON_RESERVED_FUTURE_USE_5_DEFAULT: ReservedOnes<RESERVED_FUTURE_USE_REGION_BITS> =
ReservedOnes::<RESERVED_FUTURE_USE_REGION_BITS>::FILL;
pub const IMAGE_ICON_RESERVED_FUTURE_USE_2_DEFAULT: ReservedOnes<
RESERVED_FUTURE_USE_AFTER_COORDINATE_BITS,
> = ReservedOnes::<RESERVED_FUTURE_USE_AFTER_COORDINATE_BITS>::FILL;
pub const RESERVED_FUTURE_USE_REGION_BITS: u32 = 5;
pub const RESERVED_FUTURE_USE_AFTER_COORDINATE_BITS: u32 = 2;
const IMAGE_ICON_PREFIX_LEN: usize = 2;
const PACKED_BYTE_OFFSET: usize = 2;
const SEGMENT_DATA_OFFSET: usize = 3;
const ORIGIN_LEN: usize = 3;
const ORIGIN_THIRD_OFFSET: usize = 2;
const ORIGIN_MASK: u16 = 0x0FFF;
const ORIGIN_HIGH_SHIFT: u16 = 4;
const ORIGIN_NIBBLE_MASK: u16 = 0x000F;
const ORIGIN_SECOND_SHIFT: u16 = 8;
const DESCRIPTOR_NUMBER_SHIFT: u32 = 4;
const ICON_RESERVED_SHIFT: u32 = 3;
const TRANSPORT_MODE_SHIFT: u32 = 6;
const POSITION_FLAG_SHIFT: u32 = 5;
const POSITION_FLAG_MASK: u8 = 0x01;
const COORDINATE_SYSTEM_SHIFT: u32 = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum IconTransportMode {
InlineData,
Url,
Reserved(u8),
}
impl IconTransportMode {
#[must_use]
pub fn from_u8(v: u8) -> Self {
match v & TRANSPORT_MODE_VALUE_MASK {
0 => Self::InlineData,
1 => Self::Url,
v => Self::Reserved(v),
}
}
#[must_use]
pub const fn to_u8(self) -> u8 {
match self {
Self::InlineData => 0,
Self::Url => 1,
Self::Reserved(v) => v,
}
}
#[must_use]
pub fn name(self) -> &'static str {
match self {
Self::InlineData => "inline data",
Self::Url => "URL",
Self::Reserved(_) => "reserved",
}
}
}
broadcast_core::impl_spec_display!(IconTransportMode, Reserved);
impl<'a> ExtensionBodyDef<'a> for ImageIcon<'a> {
const TAG_EXTENSION: u8 = 0x00;
const NAME: &'static str = "IMAGE_ICON";
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub struct ImageIcon<'a> {
pub descriptor_number: u8,
pub last_descriptor_number: u8,
pub reserved_future_use: ReservedOnes<RESERVED_FUTURE_USE_REGION_BITS>,
pub icon_id: u8,
pub body: ImageIconBody<'a>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub enum ImageIconBody<'a> {
First(ImageIconFirst<'a>),
Continuation {
icon_data: &'a [u8],
},
}
impl<'a> ImageIcon<'a> {
#[must_use]
pub const fn new(
descriptor_number: u8,
last_descriptor_number: u8,
icon_id: u8,
body: ImageIconBody<'a>,
) -> Self {
Self {
descriptor_number,
last_descriptor_number,
reserved_future_use: IMAGE_ICON_RESERVED_FUTURE_USE_5_DEFAULT,
icon_id,
body,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub struct ImageIconFirst<'a> {
pub icon_transport_mode: IconTransportMode,
pub position: Option<IconPosition>,
pub reserved_future_use: Option<ReservedOnes<RESERVED_FUTURE_USE_REGION_BITS>>,
pub icon_type: crate::text::DvbText<'a>,
pub payload: IconLocation<'a>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub enum IconLocation<'a> {
Data(&'a [u8]),
Url(crate::text::DvbText<'a>),
None,
}
impl<'a> ImageIconFirst<'a> {
#[must_use]
pub const fn new(
icon_transport_mode: IconTransportMode,
position: Option<IconPosition>,
icon_type: crate::text::DvbText<'a>,
payload: IconLocation<'a>,
) -> Self {
let reserved_future_use = if position.is_some() {
None
} else {
Some(IMAGE_ICON_RESERVED_FUTURE_USE_5_DEFAULT)
};
Self {
icon_transport_mode,
position,
reserved_future_use,
icon_type,
payload,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct IconPosition {
pub coordinate_system: u8,
pub reserved_future_use: ReservedOnes<RESERVED_FUTURE_USE_AFTER_COORDINATE_BITS>,
pub icon_horizontal_origin: u16,
pub icon_vertical_origin: u16,
}
impl IconPosition {
#[must_use]
pub const fn new(
coordinate_system: u8,
icon_horizontal_origin: u16,
icon_vertical_origin: u16,
) -> Self {
Self {
coordinate_system,
reserved_future_use: IMAGE_ICON_RESERVED_FUTURE_USE_2_DEFAULT,
icon_horizontal_origin,
icon_vertical_origin,
}
}
}
impl<'a> Parse<'a> for ImageIcon<'a> {
type Error = crate::error::Error;
fn parse(sel: &'a [u8]) -> Result<Self> {
need_in(sel, IMAGE_ICON_PREFIX_LEN, "image_icon body")?;
let descriptor_number = sel[0] >> DESCRIPTOR_NUMBER_SHIFT;
let last_descriptor_number = sel[0] & DESCRIPTOR_NUMBER_MASK;
let icon_id = sel[1] & ICON_ID_MASK;
let reserved_future_use = ReservedOnes::from_bits(u64::from(sel[1] >> ICON_RESERVED_SHIFT));
let body = if descriptor_number == 0 {
need_in(sel, SEGMENT_DATA_OFFSET, "image_icon body")?;
let packed = sel[PACKED_BYTE_OFFSET];
let icon_transport_mode = IconTransportMode::from_u8(packed >> TRANSPORT_MODE_SHIFT);
let position_flag = (packed >> POSITION_FLAG_SHIFT) & POSITION_FLAG_MASK;
let mut pos = SEGMENT_DATA_OFFSET;
let mut no_position_reserved = None;
let position = if position_flag == 1 {
let coordinate_system =
(packed >> COORDINATE_SYSTEM_SHIFT) & COORDINATE_SYSTEM_MASK;
let position_reserved = ReservedOnes::from_bits(u64::from(packed));
need_in(sel, pos + ORIGIN_LEN, "image_icon body")?;
let b0 = sel[pos];
let b1 = sel[pos + 1];
let b2 = sel[pos + ORIGIN_THIRD_OFFSET];
let icon_horizontal_origin =
(u16::from(b0) << ORIGIN_HIGH_SHIFT) | (u16::from(b1) >> ORIGIN_HIGH_SHIFT);
let icon_vertical_origin =
((u16::from(b1) & ORIGIN_NIBBLE_MASK) << ORIGIN_SECOND_SHIFT) | u16::from(b2);
pos += ORIGIN_LEN;
Some(IconPosition {
coordinate_system,
reserved_future_use: position_reserved,
icon_horizontal_origin,
icon_vertical_origin,
})
} else {
no_position_reserved = Some(ReservedOnes::from_bits(u64::from(packed)));
None
};
need_in(sel, pos + 1, "image_icon body")?;
let icon_type_length = sel[pos] as usize;
pos += 1;
need_in(sel, pos + icon_type_length, "image_icon body")?;
let icon_type = crate::text::DvbText::new(&sel[pos..pos + icon_type_length]);
pos += icon_type_length;
let payload = match icon_transport_mode {
IconTransportMode::InlineData => {
need_in(sel, pos + 1, "image_icon body")?;
let payload_len = sel[pos] as usize;
pos += 1;
need_in(sel, pos + payload_len, "image_icon body")?;
let p = &sel[pos..pos + payload_len];
pos += payload_len;
IconLocation::Data(p)
}
IconTransportMode::Url => {
need_in(sel, pos + 1, "image_icon body")?;
let payload_len = sel[pos] as usize;
pos += 1;
need_in(sel, pos + payload_len, "image_icon body")?;
let t = crate::text::DvbText::new(&sel[pos..pos + payload_len]);
pos += payload_len;
IconLocation::Url(t)
}
_ => IconLocation::None,
};
if pos != sel.len() {
return Err(invalid("image_icon: trailing bytes"));
}
ImageIconBody::First(ImageIconFirst {
icon_transport_mode,
position,
reserved_future_use: no_position_reserved,
icon_type,
payload,
})
} else {
need_in(sel, SEGMENT_DATA_OFFSET, "image_icon body")?;
let icon_data_length = sel[PACKED_BYTE_OFFSET] as usize;
need_in(
sel,
SEGMENT_DATA_OFFSET + icon_data_length,
"image_icon body",
)?;
let icon_data = &sel[SEGMENT_DATA_OFFSET..SEGMENT_DATA_OFFSET + icon_data_length];
if SEGMENT_DATA_OFFSET + icon_data_length != sel.len() {
return Err(invalid("image_icon: trailing bytes"));
}
ImageIconBody::Continuation { icon_data }
};
Ok(ImageIcon {
descriptor_number,
last_descriptor_number,
reserved_future_use,
icon_id,
body,
})
}
}
impl Serialize for ImageIcon<'_> {
type Error = crate::error::Error;
fn serialized_len(&self) -> usize {
IMAGE_ICON_PREFIX_LEN
+ match &self.body {
ImageIconBody::First(f) => {
1 + if f.position.is_some() { ORIGIN_LEN } else { 0 }
+ 1 + f.icon_type.len()
+ match &f.payload {
IconLocation::Data(d) => 1 + d.len(),
IconLocation::Url(u) => 1 + u.len(),
IconLocation::None => 0,
}
}
ImageIconBody::Continuation { icon_data } => 1 + icon_data.len(),
}
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
let len = self.serialized_len();
need_out(buf, len, "ImageIcon")?;
buf[0] = (broadcast_core::len::fit_mask(
self.descriptor_number,
DESCRIPTOR_NUMBER_MASK,
"descriptor_number",
)? << DESCRIPTOR_NUMBER_SHIFT)
| broadcast_core::len::fit_mask(
self.last_descriptor_number,
DESCRIPTOR_NUMBER_MASK,
"last_descriptor_number",
)?;
buf[1] = ((self.reserved_future_use.get() as u8) << ICON_RESERVED_SHIFT)
| broadcast_core::len::fit_mask(self.icon_id, ICON_ID_MASK, "icon_id")?;
let mut p = IMAGE_ICON_PREFIX_LEN;
match &self.body {
ImageIconBody::First(f) => {
let position_flag = u8::from(f.position.is_some());
let itm = broadcast_core::len::fit_mask(
f.icon_transport_mode.to_u8(),
TRANSPORT_MODE_VALUE_MASK,
"icon_transport_mode",
)?;
if let Some(pos) = &f.position {
buf[p] = (itm << TRANSPORT_MODE_SHIFT)
| (position_flag << POSITION_FLAG_SHIFT)
| (broadcast_core::len::fit_mask(
pos.coordinate_system,
COORDINATE_SYSTEM_MASK,
"coordinate_system",
)? << COORDINATE_SYSTEM_SHIFT)
| pos.reserved_future_use.get() as u8;
p += 1;
let h = broadcast_core::len::fit_mask(
pos.icon_horizontal_origin,
ORIGIN_MASK,
"icon_horizontal_origin",
)?;
let v = broadcast_core::len::fit_mask(
pos.icon_vertical_origin,
ORIGIN_MASK,
"icon_vertical_origin",
)?;
buf[p] = (h >> ORIGIN_HIGH_SHIFT) as u8;
buf[p + 1] = (((h & ORIGIN_NIBBLE_MASK) << ORIGIN_HIGH_SHIFT)
| ((v >> ORIGIN_SECOND_SHIFT) & ORIGIN_NIBBLE_MASK))
as u8;
buf[p + ORIGIN_THIRD_OFFSET] = v as u8;
p += ORIGIN_LEN;
} else {
buf[p] = (itm << TRANSPORT_MODE_SHIFT)
| (position_flag << POSITION_FLAG_SHIFT)
| f.reserved_future_use
.unwrap_or(IMAGE_ICON_RESERVED_FUTURE_USE_5_DEFAULT)
.get() as u8;
p += 1;
}
buf[p] = broadcast_core::len::fit_u8(f.icon_type.len(), "icon_type_length")?;
p += 1;
buf[p..p + f.icon_type.len()].copy_from_slice(f.icon_type.raw());
p += f.icon_type.len();
match &f.payload {
IconLocation::Data(d) => {
buf[p] = broadcast_core::len::fit_u8(d.len(), "icon_data_length")?;
p += 1;
buf[p..p + d.len()].copy_from_slice(d);
}
IconLocation::Url(u) => {
buf[p] = broadcast_core::len::fit_u8(u.len(), "icon_url_length")?;
p += 1;
buf[p..p + u.len()].copy_from_slice(u.raw());
}
IconLocation::None => {}
}
}
ImageIconBody::Continuation { icon_data } => {
buf[p] = broadcast_core::len::fit_u8(icon_data.len(), "icon_data_length")?;
p += 1;
buf[p..p + icon_data.len()].copy_from_slice(icon_data);
}
}
Ok(len)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::descriptors::extension::test_support::*;
use crate::descriptors::extension::{ExtensionBody, ExtensionDescriptor, ExtensionTag};
use alloc::vec;
#[test]
fn parse_image_icon_first_position_mode0() {
let sel = [
0x03, 0x05, 0x24, 0x06, 0x40, 0xC8, 0x02, 0xDE, 0xAD, 0x03, 0x01, 0x02, 0x03,
];
let bytes = wrap(0x00, &sel);
let d = ExtensionDescriptor::parse(&bytes).unwrap();
assert_eq!(d.kind(), Some(ExtensionTag::ImageIcon));
match &d.body {
ExtensionBody::ImageIcon(b) => {
assert_eq!(b.descriptor_number, 0);
assert_eq!(b.last_descriptor_number, 3);
assert_eq!(b.icon_id, 5);
match &b.body {
ImageIconBody::First(f) => {
assert_eq!(f.icon_transport_mode, IconTransportMode::InlineData);
assert!(f.position.is_some());
let pos = f.position.as_ref().unwrap();
assert_eq!(pos.coordinate_system, 1);
assert_eq!(pos.icon_horizontal_origin, 100);
assert_eq!(pos.icon_vertical_origin, 200);
assert_eq!(f.icon_type.raw(), &[0xDE, 0xAD]);
match &f.payload {
IconLocation::Data(d) => assert_eq!(*d, &[0x01, 0x02, 0x03]),
other => panic!("expected Data, got {other:?}"),
}
}
other => panic!("expected First, got {other:?}"),
}
}
other => panic!("expected ImageIcon, got {other:?}"),
}
round_trip(&d);
}
#[test]
fn parse_image_icon_first_no_position_mode1() {
let sel = [0x01, 0x07, 0x40, 0x01, 0xAB, 0x04, b'h', b't', b't', b'p'];
let bytes = wrap(0x00, &sel);
let d = ExtensionDescriptor::parse(&bytes).unwrap();
match &d.body {
ExtensionBody::ImageIcon(b) => match &b.body {
ImageIconBody::First(f) => {
assert_eq!(f.icon_transport_mode, IconTransportMode::Url);
assert!(f.position.is_none());
assert_eq!(f.icon_type.raw(), &[0xAB]);
match &f.payload {
IconLocation::Url(u) => assert_eq!(u.decode(), "http"),
other => panic!("expected Url, got {other:?}"),
}
}
other => panic!("expected First, got {other:?}"),
},
other => panic!("expected ImageIcon, got {other:?}"),
}
round_trip(&d);
}
#[test]
fn parse_image_icon_first_mode2_empty_payload() {
let sel = [0x00, 0x00, 0x80, 0x00];
let bytes = wrap(0x00, &sel);
let d = ExtensionDescriptor::parse(&bytes).unwrap();
match &d.body {
ExtensionBody::ImageIcon(b) => match &b.body {
ImageIconBody::First(f) => {
assert_eq!(f.icon_transport_mode, IconTransportMode::Reserved(2));
assert!(f.position.is_none());
assert!(f.icon_type.is_empty());
assert!(matches!(f.payload, IconLocation::None));
}
other => panic!("expected First, got {other:?}"),
},
other => panic!("expected ImageIcon, got {other:?}"),
}
round_trip(&d);
}
#[test]
fn parse_image_icon_continuation() {
let sel = [0x23, 0x01, 0x04, 0xAA, 0xBB, 0xCC, 0xDD];
let bytes = wrap(0x00, &sel);
let d = ExtensionDescriptor::parse(&bytes).unwrap();
assert_eq!(d.kind(), Some(ExtensionTag::ImageIcon));
match &d.body {
ExtensionBody::ImageIcon(b) => {
assert_eq!(b.descriptor_number, 2);
assert_eq!(b.last_descriptor_number, 3);
assert_eq!(b.icon_id, 1);
match &b.body {
ImageIconBody::Continuation { icon_data } => {
assert_eq!(icon_data, &[0xAA, 0xBB, 0xCC, 0xDD]);
}
other => panic!("expected Continuation, got {other:?}"),
}
}
other => panic!("expected ImageIcon, got {other:?}"),
}
round_trip(&d);
}
#[test]
fn image_icon_reserved_preserved() {
let check = |sel: &[u8], what: &str, r: u8| {
let bytes = wrap(0x00, sel);
let d = ExtensionDescriptor::parse(&bytes).unwrap();
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(buf, bytes, "{what} r={r:#x}");
};
for r in 0u8..=0x1F {
check(&[0x23, (r << 3) | 0x01, 0x01, 0xAA], "byte1", r);
check(&[0x00, 0xF8, 0x40 | r, 0x00, 0x00], "no-position", r);
}
for r in 0u8..=0x03 {
check(
&[
0x00,
0xF8,
0x20 | (1 << 2) | r,
0x06,
0x40,
0xC8,
0x00,
0x00,
],
"position",
r,
);
}
}
#[test]
fn image_icon_default_is_spec_value() {
let pos = IconPosition::new(1, 100, 200);
let first = ImageIconFirst::new(
IconTransportMode::InlineData,
Some(pos),
crate::text::DvbText::new(&[]),
IconLocation::Data(&[]),
);
let d = ImageIcon::new(0, 0, 5, ImageIconBody::First(first));
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(
buf,
[0x00, 0xFD, 0x20 | 0x04 | 0x03, 0x06, 0x40, 0xC8, 0x00, 0x00]
);
let first = ImageIconFirst::new(
IconTransportMode::Url,
None,
crate::text::DvbText::new(&[]),
IconLocation::Url(crate::text::DvbText::new(&[])),
);
let d = ImageIcon::new(0, 0, 0, ImageIconBody::First(first));
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(buf, [0x00, 0xF8, 0x40 | 0x1F, 0x00, 0x00]);
}
#[test]
fn parse_image_icon_rejects_trailing_bytes() {
let sel = [0x00, 0x00, 0x80, 0x00, 0xFF];
let bytes = wrap(0x00, &sel);
assert!(matches!(
ExtensionDescriptor::parse(&bytes).unwrap_err(),
crate::error::Error::InvalidDescriptor {
tag: super::TAG,
..
}
));
}
#[test]
fn parse_image_icon_rejects_truncated_continuation() {
let sel = [0x23, 0x01, 0x05, 0xAA, 0xBB, 0xCC];
let bytes = wrap(0x00, &sel);
assert!(matches!(
ExtensionDescriptor::parse(&bytes).unwrap_err(),
crate::error::Error::BufferTooShort(..)
));
}
#[cfg(feature = "serde")]
#[test]
fn serde_serialize_image_icon() {
let d = ExtensionDescriptor {
tag_extension: 0x00,
body: ExtensionBody::ImageIcon(ImageIcon::new(
2,
3,
1,
ImageIconBody::Continuation {
icon_data: &[0xAA, 0xBB],
},
)),
};
let json = serde_json::to_string(&d).unwrap();
assert!(json.contains("\"tag_extension\":0"));
assert!(json.contains("\"imageIcon\""));
}
#[test]
fn icon_transport_mode_full_range_round_trip() {
for v in 0u8..=0x03 {
let itm = IconTransportMode::from_u8(v);
assert_eq!(
itm.to_u8(),
v,
"IconTransportMode round-trip failed for {v}"
);
}
}
#[test]
fn icon_transport_mode_known_values() {
assert_eq!(IconTransportMode::from_u8(0), IconTransportMode::InlineData);
assert_eq!(IconTransportMode::from_u8(1), IconTransportMode::Url);
assert_eq!(
IconTransportMode::from_u8(2),
IconTransportMode::Reserved(2)
);
assert_eq!(IconTransportMode::InlineData.name(), "inline data");
assert_eq!(IconTransportMode::Url.name(), "URL");
assert_eq!(IconTransportMode::Reserved(3).name(), "reserved");
}
}