1use crate::{Error, Result};
4
5const H264_SPS: u8 = 7;
6const H264_PPS: u8 = 8;
7const H265_VPS: u8 = 32;
8const H265_SPS: u8 = 33;
9const H265_PPS: u8 = 34;
10const ANNEX_B_START_CODE: [u8; 4] = [0, 0, 0, 1];
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct NalUnit<'a> {
18 nal_unit_type: u8,
19 reference_idc: u8,
20 bytes: &'a [u8],
21 start_code_offset: Option<usize>,
22 start_code_len: usize,
23}
24
25impl<'a> NalUnit<'a> {
26 pub fn new_from_h264_payload(payload: &'a [u8]) -> Result<Self> {
32 let Some(&header) = payload.first() else {
33 return Err(Error::invalid_argument("H.264 NAL payload is empty"));
34 };
35 Ok(Self {
36 nal_unit_type: header & 0x1f,
37 reference_idc: (header >> 5) & 0x03,
38 bytes: payload,
39 start_code_offset: None,
40 start_code_len: 0,
41 })
42 }
43
44 pub const fn nal_unit_type(self) -> u8 {
46 self.nal_unit_type
47 }
48
49 pub const fn reference_idc(self) -> u8 {
51 self.reference_idc
52 }
53
54 pub const fn payload(self) -> &'a [u8] {
56 self.bytes.split_at(self.start_code_len).1
57 }
58
59 pub(super) fn prefixed_slice(self) -> Result<&'a [u8]> {
61 match self.start_code_len {
62 3 => Ok(self.bytes),
63 4 => Ok(&self.bytes[1..]),
64 _ => Err(Error::internal("coded slice has no Annex-B prefix")),
65 }
66 }
67
68 pub const fn start_code_offset(self) -> Option<usize> {
70 self.start_code_offset
71 }
72
73 pub const fn start_code_len(self) -> usize {
75 self.start_code_len
76 }
77}
78
79pub fn parse_nal_annex_b(bytes: &[u8]) -> Vec<NalUnit<'_>> {
85 let mut units = Vec::new();
86 let Some((mut current, mut prefix_len)) = find_start_code(bytes, 0) else {
87 return units;
88 };
89
90 loop {
91 let payload_start = current + prefix_len;
92 let next = find_start_code(bytes, payload_start);
93 let payload_end = next.map_or(bytes.len(), |(offset, _)| offset);
94 if let Ok(mut unit) = NalUnit::new_from_h264_payload(&bytes[payload_start..payload_end]) {
95 unit.bytes = &bytes[current..payload_end];
96 unit.start_code_offset = Some(current);
97 unit.start_code_len = prefix_len;
98 units.push(unit);
99 }
100 let Some((next_offset, next_prefix_len)) = next else {
101 break;
102 };
103 current = next_offset;
104 prefix_len = next_prefix_len;
105 }
106
107 units
108}
109
110pub fn emit_nal_annex_b(units: &[NalUnit<'_>]) -> Result<Vec<u8>> {
116 let total = units.iter().try_fold(0_usize, |total, unit| {
117 total
118 .checked_add(ANNEX_B_START_CODE.len())
119 .and_then(|total| total.checked_add(unit.payload().len()))
120 .ok_or_else(|| Error::invalid_argument("Annex-B output size overflows usize"))
121 })?;
122 let mut output = Vec::new();
123 output
124 .try_reserve_exact(total)
125 .map_err(|_| Error::resource_exhausted("Annex-B output allocation failed"))?;
126 for unit in units {
127 output.extend_from_slice(&ANNEX_B_START_CODE);
128 output.extend_from_slice(unit.payload());
129 }
130 Ok(output)
131}
132
133pub fn extract_sps(bytes: &[u8]) -> Option<Vec<u8>> {
135 extract_first_h264(bytes, H264_SPS)
136}
137
138pub fn extract_pps(bytes: &[u8]) -> Option<Vec<u8>> {
140 extract_first_h264(bytes, H264_PPS)
141}
142
143pub fn extract_vps_h265(bytes: &[u8]) -> Option<Vec<u8>> {
145 extract_first_h265(bytes, H265_VPS)
146}
147
148pub fn extract_sps_h265(bytes: &[u8]) -> Option<Vec<u8>> {
150 extract_first_h265(bytes, H265_SPS)
151}
152
153pub fn extract_pps_h265(bytes: &[u8]) -> Option<Vec<u8>> {
155 extract_first_h265(bytes, H265_PPS)
156}
157
158fn find_start_code(bytes: &[u8], offset: usize) -> Option<(usize, usize)> {
159 let mut index = offset;
160 while index + 2 < bytes.len() {
161 if bytes[index] == 0 && bytes[index + 1] == 0 {
162 if bytes[index + 2] == 1 {
163 return Some((index, 3));
164 }
165 if index + 3 < bytes.len() && bytes[index + 2] == 0 && bytes[index + 3] == 1 {
166 return Some((index, 4));
167 }
168 }
169 index += 1;
170 }
171 None
172}
173
174fn extract_first_h264(bytes: &[u8], nal_unit_type: u8) -> Option<Vec<u8>> {
175 parse_nal_annex_b(bytes)
176 .into_iter()
177 .find(|unit| unit.nal_unit_type == nal_unit_type)
178 .map(|unit| unit.payload().to_vec())
179}
180
181fn extract_first_h265(bytes: &[u8], nal_unit_type: u8) -> Option<Vec<u8>> {
182 let (mut current, mut prefix_len) = find_start_code(bytes, 0)?;
183 loop {
184 let payload_start = current + prefix_len;
185 let next = find_start_code(bytes, payload_start);
186 let mut payload_end = next.map_or(bytes.len(), |(offset, _)| offset);
187 while payload_end > payload_start && bytes[payload_end - 1] == 0 {
188 payload_end -= 1;
189 }
190 let payload = &bytes[payload_start..payload_end];
191 if payload.len() >= 2 && ((payload[0] >> 1) & 0x3f) == nal_unit_type {
192 return Some(payload.to_vec());
193 }
194 let (next_offset, next_prefix_len) = next?;
195 current = next_offset;
196 prefix_len = next_prefix_len;
197 }
198}