Skip to main content

dvb_si/descriptors/
data_stream_alignment.rs

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