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 video and audio data within the PES packets.
4
5use num_enum::TryFromPrimitive;
6
7use super::descriptor_body;
8use crate::error::{Error, Result};
9use dvb_common::{Parse, Serialize};
10
11/// Descriptor tag for data_stream_alignment_descriptor.
12pub const TAG: u8 = 0x06;
13const HEADER_LEN: usize = 2;
14const BODY_LEN: u8 = 1;
15
16/// Alignment type values per ISO/IEC 13818-1 Table 2-39.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromPrimitive)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize))]
19#[repr(u8)]
20#[non_exhaustive]
21pub enum AlignmentType {
22    /// Video access units start at the beginning of a PES packet.
23    VideoAccessUnit = 0x01,
24    /// Audio access units start at the beginning of a PES packet.
25    AudioAccessUnit = 0x02,
26    /// Video and audio access units start at the beginning of a PES packet.
27    VideoAndAudioAccessUnit = 0x03,
28    /// Reserved for future use.
29    Reserved = 0x04,
30}
31
32/// Data Stream Alignment Descriptor.
33#[derive(Debug, Clone, PartialEq, Eq)]
34#[cfg_attr(feature = "serde", derive(serde::Serialize))]
35pub struct DataStreamAlignmentDescriptor {
36    /// Alignment type (see [`AlignmentType`]).
37    pub alignment_type: u8,
38}
39
40impl<'a> Parse<'a> for DataStreamAlignmentDescriptor {
41    type Error = crate::error::Error;
42
43    fn parse(bytes: &'a [u8]) -> Result<Self> {
44        let body = descriptor_body(
45            bytes,
46            TAG,
47            "DataStreamAlignmentDescriptor",
48            "unexpected tag for data_stream_alignment_descriptor",
49        )?;
50        if body.len() != BODY_LEN as usize {
51            return Err(Error::InvalidDescriptor {
52                tag: TAG,
53                reason: "data_stream_alignment_descriptor length must equal 1",
54            });
55        }
56        Ok(Self {
57            alignment_type: body[0],
58        })
59    }
60}
61
62impl Serialize for DataStreamAlignmentDescriptor {
63    type Error = crate::error::Error;
64
65    fn serialized_len(&self) -> usize {
66        HEADER_LEN + BODY_LEN as usize
67    }
68
69    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
70        let len = self.serialized_len();
71        if buf.len() < len {
72            return Err(Error::OutputBufferTooSmall {
73                need: len,
74                have: buf.len(),
75            });
76        }
77        buf[0] = TAG;
78        buf[1] = BODY_LEN;
79        buf[2] = self.alignment_type;
80        Ok(len)
81    }
82}
83impl<'a> crate::traits::DescriptorDef<'a> for DataStreamAlignmentDescriptor {
84    const TAG: u8 = TAG;
85    const NAME: &'static str = "DATA_STREAM_ALIGNMENT";
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    #[test]
93    fn parse_video_access_unit() {
94        let bytes = [TAG, 1, 0x01];
95        let d = DataStreamAlignmentDescriptor::parse(&bytes).unwrap();
96        assert_eq!(d.alignment_type, 0x01);
97    }
98
99    #[test]
100    fn parse_video_and_audio() {
101        let bytes = [TAG, 1, 0x03];
102        let d = DataStreamAlignmentDescriptor::parse(&bytes).unwrap();
103        assert_eq!(d.alignment_type, 0x03);
104    }
105
106    #[test]
107    fn alignment_type_conversion() {
108        assert_eq!(
109            AlignmentType::try_from(0x01).unwrap(),
110            AlignmentType::VideoAccessUnit
111        );
112        assert_eq!(
113            AlignmentType::try_from(0x02).unwrap(),
114            AlignmentType::AudioAccessUnit
115        );
116        assert_eq!(
117            AlignmentType::try_from(0x03).unwrap(),
118            AlignmentType::VideoAndAudioAccessUnit
119        );
120        assert_eq!(
121            AlignmentType::try_from(0x04).unwrap(),
122            AlignmentType::Reserved
123        );
124        assert!(AlignmentType::try_from(0xFF).is_err());
125    }
126
127    #[test]
128    fn exhaustive_byte_sweep() {
129        let mut matched = 0u16;
130        for byte in 0u8..=0xFF {
131            if let Ok(v) = AlignmentType::try_from(byte) {
132                assert_eq!(v as u8, byte, "round-trip failed for {byte:#04x}");
133                matched += 1;
134            }
135        }
136        assert_eq!(matched, 4, "expected 4 matched variants");
137    }
138
139    #[test]
140    fn parse_rejects_wrong_tag() {
141        let err = DataStreamAlignmentDescriptor::parse(&[0x07, 1, 0x01]).unwrap_err();
142        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x07, .. }));
143    }
144
145    #[test]
146    fn parse_rejects_wrong_length() {
147        let err = DataStreamAlignmentDescriptor::parse(&[TAG, 2, 0x01, 0x00]).unwrap_err();
148        assert!(matches!(err, Error::InvalidDescriptor { .. }));
149    }
150
151    #[test]
152    fn parse_rejects_short_buffer() {
153        let err = DataStreamAlignmentDescriptor::parse(&[TAG]).unwrap_err();
154        assert!(matches!(err, Error::BufferTooShort { .. }));
155    }
156
157    #[test]
158    fn serialize_round_trip() {
159        let d = DataStreamAlignmentDescriptor {
160            alignment_type: 0x03,
161        };
162        let mut buf = vec![0u8; d.serialized_len()];
163        d.serialize_into(&mut buf).unwrap();
164        let reparsed = DataStreamAlignmentDescriptor::parse(&buf).unwrap();
165        assert_eq!(d, reparsed);
166    }
167
168    #[test]
169    fn descriptor_length_matches_payload() {
170        let d = DataStreamAlignmentDescriptor {
171            alignment_type: 0x02,
172        };
173        assert_eq!(d.serialized_len() - 2, 1);
174    }
175}