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
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn parse_video_access_unit() {
104        let bytes = [TAG, 1, 0x01];
105        let d = DataStreamAlignmentDescriptor::parse(&bytes).unwrap();
106        assert_eq!(d.alignment_type, 0x01);
107    }
108
109    #[test]
110    fn parse_video_and_audio() {
111        let bytes = [TAG, 1, 0x03];
112        let d = DataStreamAlignmentDescriptor::parse(&bytes).unwrap();
113        assert_eq!(d.alignment_type, 0x03);
114    }
115
116    #[test]
117    fn alignment_type_conversion() {
118        assert_eq!(
119            AlignmentType::try_from(0x01).unwrap(),
120            AlignmentType::VideoAccessUnit
121        );
122        assert_eq!(
123            AlignmentType::try_from(0x02).unwrap(),
124            AlignmentType::AudioAccessUnit
125        );
126        assert_eq!(
127            AlignmentType::try_from(0x03).unwrap(),
128            AlignmentType::VideoAndAudioAccessUnit
129        );
130        assert_eq!(
131            AlignmentType::try_from(0x04).unwrap(),
132            AlignmentType::Reserved
133        );
134        assert!(AlignmentType::try_from(0xFF).is_err());
135    }
136
137    #[test]
138    fn exhaustive_byte_sweep() {
139        let mut matched = 0u16;
140        for byte in 0u8..=0xFF {
141            if let Ok(v) = AlignmentType::try_from(byte) {
142                assert_eq!(v as u8, byte, "round-trip failed for {byte:#04x}");
143                matched += 1;
144            }
145        }
146        assert_eq!(matched, 4, "expected 4 matched variants");
147    }
148
149    #[test]
150    fn parse_rejects_wrong_tag() {
151        let err = DataStreamAlignmentDescriptor::parse(&[0x07, 1, 0x01]).unwrap_err();
152        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x07, .. }));
153    }
154
155    #[test]
156    fn parse_rejects_wrong_length() {
157        let err = DataStreamAlignmentDescriptor::parse(&[TAG, 2, 0x01, 0x00]).unwrap_err();
158        assert!(matches!(err, Error::InvalidDescriptor { .. }));
159    }
160
161    #[test]
162    fn parse_rejects_short_buffer() {
163        let err = DataStreamAlignmentDescriptor::parse(&[TAG]).unwrap_err();
164        assert!(matches!(err, Error::BufferTooShort { .. }));
165    }
166
167    #[test]
168    fn serialize_round_trip() {
169        let d = DataStreamAlignmentDescriptor {
170            alignment_type: 0x03,
171        };
172        let mut buf = vec![0u8; d.serialized_len()];
173        d.serialize_into(&mut buf).unwrap();
174        let reparsed = DataStreamAlignmentDescriptor::parse(&buf).unwrap();
175        assert_eq!(d, reparsed);
176    }
177
178    #[test]
179    fn descriptor_length_matches_payload() {
180        let d = DataStreamAlignmentDescriptor {
181            alignment_type: 0x02,
182        };
183        assert_eq!(d.descriptor_length(), 1);
184    }
185}