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