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}
70
71/// Data Stream Alignment Descriptor.
72#[derive(Debug, Clone, PartialEq, Eq)]
73#[cfg_attr(feature = "serde", derive(serde::Serialize))]
74pub struct DataStreamAlignmentDescriptor {
75    /// Alignment type — typed; reserved/unknown bytes are preserved as
76    /// [`AlignmentType::Reserved`] for byte-identical round-trip.
77    pub alignment_type: AlignmentType,
78}
79
80impl<'a> Parse<'a> for DataStreamAlignmentDescriptor {
81    type Error = crate::error::Error;
82
83    fn parse(bytes: &'a [u8]) -> Result<Self> {
84        let body = descriptor_body(
85            bytes,
86            TAG,
87            "DataStreamAlignmentDescriptor",
88            "unexpected tag for data_stream_alignment_descriptor",
89        )?;
90        if body.len() != BODY_LEN as usize {
91            return Err(Error::InvalidDescriptor {
92                tag: TAG,
93                reason: "data_stream_alignment_descriptor length must equal 1",
94            });
95        }
96        Ok(Self {
97            alignment_type: AlignmentType::from_u8(body[0]),
98        })
99    }
100}
101
102impl Serialize for DataStreamAlignmentDescriptor {
103    type Error = crate::error::Error;
104
105    fn serialized_len(&self) -> usize {
106        HEADER_LEN + BODY_LEN as usize
107    }
108
109    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
110        let len = self.serialized_len();
111        if buf.len() < len {
112            return Err(Error::OutputBufferTooSmall {
113                need: len,
114                have: buf.len(),
115            });
116        }
117        buf[0] = TAG;
118        buf[1] = BODY_LEN;
119        buf[2] = self.alignment_type.to_u8();
120        Ok(len)
121    }
122}
123impl<'a> crate::traits::DescriptorDef<'a> for DataStreamAlignmentDescriptor {
124    const TAG: u8 = TAG;
125    const NAME: &'static str = "DATA_STREAM_ALIGNMENT";
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn parse_slice_or_video_access_unit() {
134        let d = DataStreamAlignmentDescriptor::parse(&[TAG, 1, 0x01]).unwrap();
135        assert_eq!(d.alignment_type, AlignmentType::SliceOrVideoAccessUnit);
136    }
137
138    #[test]
139    fn parse_video_access_unit() {
140        let d = DataStreamAlignmentDescriptor::parse(&[TAG, 1, 0x02]).unwrap();
141        assert_eq!(d.alignment_type, AlignmentType::VideoAccessUnit);
142    }
143
144    #[test]
145    fn parse_gop_or_seq() {
146        let d = DataStreamAlignmentDescriptor::parse(&[TAG, 1, 0x03]).unwrap();
147        assert_eq!(d.alignment_type, AlignmentType::GopOrSeq);
148    }
149
150    #[test]
151    fn parse_seq() {
152        let d = DataStreamAlignmentDescriptor::parse(&[TAG, 1, 0x04]).unwrap();
153        assert_eq!(d.alignment_type, AlignmentType::Seq);
154    }
155
156    #[test]
157    fn parse_reserved_preserves_byte() {
158        // 0x00 and 0x05..=0xFF are reserved; the wire byte must round-trip.
159        let d = DataStreamAlignmentDescriptor::parse(&[TAG, 1, 0x05]).unwrap();
160        assert_eq!(d.alignment_type, AlignmentType::Reserved(0x05));
161        assert_eq!(d.alignment_type.name(), "reserved");
162    }
163
164    #[test]
165    fn alignment_type_conversion() {
166        assert_eq!(
167            AlignmentType::from_u8(0x01),
168            AlignmentType::SliceOrVideoAccessUnit
169        );
170        assert_eq!(AlignmentType::from_u8(0x04), AlignmentType::Seq);
171        assert_eq!(AlignmentType::from_u8(0x00), AlignmentType::Reserved(0x00));
172        assert_eq!(AlignmentType::from_u8(0x05), AlignmentType::Reserved(0x05));
173        assert_eq!(AlignmentType::from_u8(0xFF), AlignmentType::Reserved(0xFF));
174    }
175
176    #[test]
177    fn alignment_type_round_trip() {
178        for v in [0x00u8, 0x01, 0x02, 0x03, 0x04, 0x05, 0xFF] {
179            assert_eq!(
180                AlignmentType::from_u8(v).to_u8(),
181                v,
182                "round-trip failed for {v:#04x}"
183            );
184        }
185    }
186
187    #[test]
188    fn alignment_type_name() {
189        assert_eq!(
190            AlignmentType::SliceOrVideoAccessUnit.name(),
191            "Slice, or video access unit"
192        );
193        assert_eq!(AlignmentType::VideoAccessUnit.name(), "Video access unit");
194        assert_eq!(AlignmentType::GopOrSeq.name(), "GOP, or SEQ");
195        assert_eq!(AlignmentType::Seq.name(), "SEQ");
196    }
197
198    #[test]
199    fn parse_rejects_wrong_tag() {
200        let err = DataStreamAlignmentDescriptor::parse(&[0x07, 1, 0x01]).unwrap_err();
201        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x07, .. }));
202    }
203
204    #[test]
205    fn parse_rejects_wrong_length() {
206        let err = DataStreamAlignmentDescriptor::parse(&[TAG, 2, 0x01, 0x00]).unwrap_err();
207        assert!(matches!(err, Error::InvalidDescriptor { .. }));
208    }
209
210    #[test]
211    fn parse_rejects_short_buffer() {
212        let err = DataStreamAlignmentDescriptor::parse(&[TAG]).unwrap_err();
213        assert!(matches!(err, Error::BufferTooShort { .. }));
214    }
215
216    #[test]
217    fn serialize_round_trip() {
218        let d = DataStreamAlignmentDescriptor {
219            alignment_type: AlignmentType::GopOrSeq,
220        };
221        let mut buf = vec![0u8; d.serialized_len()];
222        d.serialize_into(&mut buf).unwrap();
223        let reparsed = DataStreamAlignmentDescriptor::parse(&buf).unwrap();
224        assert_eq!(d, reparsed);
225    }
226
227    #[test]
228    fn descriptor_length_matches_payload() {
229        let d = DataStreamAlignmentDescriptor {
230            alignment_type: AlignmentType::VideoAccessUnit,
231        };
232        assert_eq!(d.serialized_len() - 2, 1);
233    }
234}