Skip to main content

dvb_si/descriptors/
data_stream_alignment.rs

1//! Data Stream Alignment Descriptor — ISO/IEC 13818-1 §2.6.10 (tag 0x06).
2//!
3//! Indicates the alignment of data within PES packets.
4//! Alignment type values per ISO/IEC 13818-1 Table 2-53.
5
6use super::descriptor_body;
7use crate::error::{Error, Result};
8use dvb_common::{Parse, Serialize};
9
10/// Descriptor tag for data_stream_alignment_descriptor.
11pub const TAG: u8 = 0x06;
12const HEADER_LEN: usize = 2;
13const BODY_LEN: u8 = 1;
14
15/// Alignment type values per ISO/IEC 13818-1 Table 2-53.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize))]
18#[non_exhaustive]
19pub enum AlignmentType {
20    /// 0x01 — Slice, or video access unit aligned at PES packet start.
21    SliceOrVideoAccessUnit,
22    /// 0x02 — Video access unit aligned at PES packet start.
23    VideoAccessUnit,
24    /// 0x03 — GOP, or SEQ aligned at PES packet start.
25    GopOrSeq,
26    /// 0x04 — SEQ aligned at PES packet start.
27    Seq,
28    /// Reserved/unrecognised wire value (0x00, 0x05..=0xFF), preserved verbatim
29    /// for byte-identical round-trip.
30    Reserved(u8),
31}
32
33impl AlignmentType {
34    /// Construct from a raw byte; unknown values are preserved as `Reserved`.
35    #[must_use]
36    pub fn from_u8(v: u8) -> Self {
37        match v {
38            0x01 => Self::SliceOrVideoAccessUnit,
39            0x02 => Self::VideoAccessUnit,
40            0x03 => Self::GopOrSeq,
41            0x04 => Self::Seq,
42            v => Self::Reserved(v),
43        }
44    }
45
46    /// Return the raw byte value.
47    #[must_use]
48    pub fn to_u8(self) -> u8 {
49        match self {
50            Self::SliceOrVideoAccessUnit => 0x01,
51            Self::VideoAccessUnit => 0x02,
52            Self::GopOrSeq => 0x03,
53            Self::Seq => 0x04,
54            Self::Reserved(v) => v,
55        }
56    }
57
58    /// Returns a human-readable name, or `"reserved"` for unrecognised values.
59    #[must_use]
60    pub fn name(self) -> &'static str {
61        match self {
62            Self::SliceOrVideoAccessUnit => "Slice, or video access unit",
63            Self::VideoAccessUnit => "Video access unit",
64            Self::GopOrSeq => "GOP, or SEQ",
65            Self::Seq => "SEQ",
66            Self::Reserved(_) => "reserved",
67        }
68    }
69}
70dvb_common::impl_spec_display!(AlignmentType, Reserved);
71
72/// Data Stream Alignment Descriptor.
73#[derive(Debug, Clone, PartialEq, Eq)]
74#[cfg_attr(feature = "serde", derive(serde::Serialize))]
75pub struct DataStreamAlignmentDescriptor {
76    /// Alignment type — typed; reserved/unknown bytes are preserved as
77    /// [`AlignmentType::Reserved`] for byte-identical round-trip.
78    pub alignment_type: AlignmentType,
79}
80
81impl<'a> Parse<'a> for DataStreamAlignmentDescriptor {
82    type Error = crate::error::Error;
83
84    fn parse(bytes: &'a [u8]) -> Result<Self> {
85        let body = descriptor_body(
86            bytes,
87            TAG,
88            "DataStreamAlignmentDescriptor",
89            "unexpected tag for data_stream_alignment_descriptor",
90        )?;
91        if body.len() != BODY_LEN as usize {
92            return Err(Error::InvalidDescriptor {
93                tag: TAG,
94                reason: "data_stream_alignment_descriptor length must equal 1",
95            });
96        }
97        Ok(Self {
98            alignment_type: AlignmentType::from_u8(body[0]),
99        })
100    }
101}
102
103impl Serialize for DataStreamAlignmentDescriptor {
104    type Error = crate::error::Error;
105
106    fn serialized_len(&self) -> usize {
107        HEADER_LEN + BODY_LEN as usize
108    }
109
110    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
111        let len = self.serialized_len();
112        if buf.len() < len {
113            return Err(Error::OutputBufferTooSmall {
114                need: len,
115                have: buf.len(),
116            });
117        }
118        buf[0] = TAG;
119        buf[1] = BODY_LEN;
120        buf[2] = self.alignment_type.to_u8();
121        Ok(len)
122    }
123}
124impl<'a> crate::traits::DescriptorDef<'a> for DataStreamAlignmentDescriptor {
125    const TAG: u8 = TAG;
126    const NAME: &'static str = "DATA_STREAM_ALIGNMENT";
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn parse_slice_or_video_access_unit() {
135        let d = DataStreamAlignmentDescriptor::parse(&[TAG, 1, 0x01]).unwrap();
136        assert_eq!(d.alignment_type, AlignmentType::SliceOrVideoAccessUnit);
137    }
138
139    #[test]
140    fn parse_video_access_unit() {
141        let d = DataStreamAlignmentDescriptor::parse(&[TAG, 1, 0x02]).unwrap();
142        assert_eq!(d.alignment_type, AlignmentType::VideoAccessUnit);
143    }
144
145    #[test]
146    fn parse_gop_or_seq() {
147        let d = DataStreamAlignmentDescriptor::parse(&[TAG, 1, 0x03]).unwrap();
148        assert_eq!(d.alignment_type, AlignmentType::GopOrSeq);
149    }
150
151    #[test]
152    fn parse_seq() {
153        let d = DataStreamAlignmentDescriptor::parse(&[TAG, 1, 0x04]).unwrap();
154        assert_eq!(d.alignment_type, AlignmentType::Seq);
155    }
156
157    #[test]
158    fn parse_reserved_preserves_byte() {
159        // 0x00 and 0x05..=0xFF are reserved; the wire byte must round-trip.
160        let d = DataStreamAlignmentDescriptor::parse(&[TAG, 1, 0x05]).unwrap();
161        assert_eq!(d.alignment_type, AlignmentType::Reserved(0x05));
162        assert_eq!(d.alignment_type.name(), "reserved");
163    }
164
165    #[test]
166    fn alignment_type_conversion() {
167        assert_eq!(
168            AlignmentType::from_u8(0x01),
169            AlignmentType::SliceOrVideoAccessUnit
170        );
171        assert_eq!(AlignmentType::from_u8(0x04), AlignmentType::Seq);
172        assert_eq!(AlignmentType::from_u8(0x00), AlignmentType::Reserved(0x00));
173        assert_eq!(AlignmentType::from_u8(0x05), AlignmentType::Reserved(0x05));
174        assert_eq!(AlignmentType::from_u8(0xFF), AlignmentType::Reserved(0xFF));
175    }
176
177    #[test]
178    fn alignment_type_round_trip() {
179        for v in [0x00u8, 0x01, 0x02, 0x03, 0x04, 0x05, 0xFF] {
180            assert_eq!(
181                AlignmentType::from_u8(v).to_u8(),
182                v,
183                "round-trip failed for {v:#04x}"
184            );
185        }
186    }
187
188    #[test]
189    fn alignment_type_name() {
190        assert_eq!(
191            AlignmentType::SliceOrVideoAccessUnit.name(),
192            "Slice, or video access unit"
193        );
194        assert_eq!(AlignmentType::VideoAccessUnit.name(), "Video access unit");
195        assert_eq!(AlignmentType::GopOrSeq.name(), "GOP, or SEQ");
196        assert_eq!(AlignmentType::Seq.name(), "SEQ");
197    }
198
199    #[test]
200    fn parse_rejects_wrong_tag() {
201        let err = DataStreamAlignmentDescriptor::parse(&[0x07, 1, 0x01]).unwrap_err();
202        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x07, .. }));
203    }
204
205    #[test]
206    fn parse_rejects_wrong_length() {
207        let err = DataStreamAlignmentDescriptor::parse(&[TAG, 2, 0x01, 0x00]).unwrap_err();
208        assert!(matches!(err, Error::InvalidDescriptor { .. }));
209    }
210
211    #[test]
212    fn parse_rejects_short_buffer() {
213        let err = DataStreamAlignmentDescriptor::parse(&[TAG]).unwrap_err();
214        assert!(matches!(err, Error::BufferTooShort { .. }));
215    }
216
217    #[test]
218    fn serialize_round_trip() {
219        let d = DataStreamAlignmentDescriptor {
220            alignment_type: AlignmentType::GopOrSeq,
221        };
222        let mut buf = vec![0u8; d.serialized_len()];
223        d.serialize_into(&mut buf).unwrap();
224        let reparsed = DataStreamAlignmentDescriptor::parse(&buf).unwrap();
225        assert_eq!(d, reparsed);
226    }
227
228    #[test]
229    fn descriptor_length_matches_payload() {
230        let d = DataStreamAlignmentDescriptor {
231            alignment_type: AlignmentType::VideoAccessUnit,
232        };
233        assert_eq!(d.serialized_len() - 2, 1);
234    }
235}