Skip to main content

oa/video/
nal.rs

1//! CPU-only Annex-B NAL operations ported from `oa::FnVideo`.
2
3use 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/// Borrowed H.264 NAL payload and decoded header fields.
13///
14/// The payload starts at the NAL header byte and aliases the input Annex-B
15/// buffer. It does not include the three- or four-byte start code.
16#[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	/// Interpret a non-empty payload using the H.264 one-byte NAL header.
27	///
28	/// # Errors
29	///
30	/// Returns an error when `payload` is empty.
31	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	/// Return the H.264 `nal_unit_type` header field.
45	pub const fn nal_unit_type(self) -> u8 {
46		self.nal_unit_type
47	}
48
49	/// Return the H.264 `nal_ref_idc` header field.
50	pub const fn reference_idc(self) -> u8 {
51		self.reference_idc
52	}
53
54	/// Return the borrowed payload including its NAL header byte.
55	pub const fn payload(self) -> &'a [u8] {
56		self.bytes.split_at(self.start_code_len).1
57	}
58
59	/// Borrow the coded unit with the three-byte prefix consumed by Vulkan Video.
60	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	/// Return the source Annex-B start-code byte offset, when parsed from a stream.
69	pub const fn start_code_offset(self) -> Option<usize> {
70		self.start_code_offset
71	}
72
73	/// Return the source Annex-B start-code width, or zero for a raw payload.
74	pub const fn start_code_len(self) -> usize {
75		self.start_code_len
76	}
77}
78
79/// Split an Annex-B byte stream into borrowed H.264 NAL payloads.
80///
81/// Both `00 00 01` and `00 00 00 01` start codes are recognized. Bytes before
82/// the first start code and empty units are ignored, matching the donor
83/// `oa::FnVideo::parseNalAnnexB` contract.
84pub 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
110/// Emit borrowed NAL payloads as canonical four-byte-start-code Annex-B.
111///
112/// # Errors
113///
114/// Returns an error when the output size overflows or host allocation fails.
115pub 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
133/// Copy the first H.264 sequence parameter set payload.
134pub fn extract_sps(bytes: &[u8]) -> Option<Vec<u8>> {
135	extract_first_h264(bytes, H264_SPS)
136}
137
138/// Copy the first H.264 picture parameter set payload.
139pub fn extract_pps(bytes: &[u8]) -> Option<Vec<u8>> {
140	extract_first_h264(bytes, H264_PPS)
141}
142
143/// Copy the first H.265 video parameter set payload.
144pub fn extract_vps_h265(bytes: &[u8]) -> Option<Vec<u8>> {
145	extract_first_h265(bytes, H265_VPS)
146}
147
148/// Copy the first H.265 sequence parameter set payload.
149pub fn extract_sps_h265(bytes: &[u8]) -> Option<Vec<u8>> {
150	extract_first_h265(bytes, H265_SPS)
151}
152
153/// Copy the first H.265 picture parameter set payload.
154pub 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}