Skip to main content

oa/video/
recorder.rs

1//! Streaming MP4 recording session over the hardware video encoder.
2//!
3//! Donor: `source/cpp/include/oa/vision/videoRecorder.h` and
4//! `source/cpp/lib/oa/vision/video/videoRecorder.cpp`.
5//!
6//! One recorder owns a [`VideoEncoder`], a [`VideoMuxer`], and an optional
7//! [`AudioEncoder`]. Frames enter as packed RGBA8 bytes; interleaved F32 audio
8//! enters independently and is aligned to the first video presentation
9//! timestamp. `finalize` flushes the encoder and completes the container;
10//! `close` abandons them deliberately and never manufactures a partial file
11//! that appears finished.
12
13use crate::audio::{AudioCaptureChunk, AudioCodec, AudioEncoder};
14use crate::{Engine, Error, Result};
15
16use super::{
17	EncodedVideoPacket, VideoCodec, VideoColorMatrix, VideoEncodeConfig, VideoEncoder, VideoMuxer,
18	VideoMuxerAudioConfig, VideoMuxerConfig, extract_pps, extract_pps_h265, extract_sps,
19	extract_sps_h265, extract_vps_h265,
20};
21pub use crate::video::types::VideoRecorderConfig;
22
23impl Default for VideoRecorderConfig {
24	fn default() -> Self {
25		Self {
26			output_path: String::from("output.mp4"),
27			encode: VideoEncodeConfig::new(super::VideoEncodeProfile::h264_high_420_8bit(), 0, 0),
28			color_space: VideoColorMatrix::Unspecified,
29			full_range: false,
30			audio: None,
31		}
32	}
33}
34
35struct PendingAudioChunk {
36	samples: Vec<f32>,
37	pts_micros: u64,
38}
39
40struct RecorderState {
41	encoder: VideoEncoder,
42	muxer: VideoMuxer,
43	audio_encoder: Option<AudioEncoder>,
44	pending_audio: Vec<PendingAudioChunk>,
45	audio_scratch: Vec<f32>,
46	first_video_pts_micros: u64,
47	next_audio_frame: u64,
48	has_first_video_pts: bool,
49	submitted_frame_count: u64,
50	muxed_frame_count: u64,
51	codec_config_written: bool,
52	finalized: bool,
53}
54
55/// Stateful streaming MP4 recorder for hardware-encoded H.264/H.265 video.
56///
57/// `write_rgba` submits one packed RGBA8 frame asynchronously and muxes every
58/// packet the slot ring has completed; `finalize` drains the remaining
59/// encoder jobs and closes the container. Audio chunks arriving before the
60/// first video frame are buffered until the first video presentation
61/// timestamp establishes the shared timeline.
62pub struct VideoRecorder {
63	state: Option<RecorderState>,
64	config: VideoRecorderConfig,
65}
66
67impl VideoRecorder {
68	/// Create a recorder, its encoder session, and the output container.
69	///
70	/// The encode profile must carry a non-zero extent admitted by the
71	/// engine's queried encode capabilities; audio, when configured, admits
72	/// only the muxer's PCM-S16 track.
73	///
74	/// # Errors
75	///
76	/// Returns an error for an empty output path or zero extent, when the
77	/// device does not admit the encode session, when the audio profile is
78	/// not PCM-S16, or when the container cannot be created.
79	pub fn new(engine: &Engine, config: VideoRecorderConfig) -> Result<Self> {
80		if config.output_path.is_empty() {
81			return Err(Error::invalid_argument(
82				"VideoRecorder output path must not be empty",
83			));
84		}
85		if config.encode.width == 0 || config.encode.height == 0 {
86			return Err(Error::invalid_argument(
87				"VideoRecorder requires a non-zero encode extent",
88			));
89		}
90		let codec = encode_codec(&config);
91		if let Some(profile) = &config.audio
92			&& profile.codec != AudioCodec::PcmS16
93		{
94			return Err(Error::missing_capability(
95				"the recorder's MP4 audio track admits PCM-S16 only",
96			));
97		}
98		let encoder = VideoEncoder::new(engine, config.encode)?;
99		let audio_encoder = config.audio.map(AudioEncoder::new).transpose()?;
100		let mut mux_config = VideoMuxerConfig::new(codec, config.encode.width, config.encode.height)?;
101		mux_config.frame_rate = config.encode.frame_rate;
102		mux_config.audio = audio_encoder.as_ref().map(|encoder| VideoMuxerAudioConfig {
103			sample_rate: encoder
104				.profile()
105				.map(|profile| profile.sample_rate)
106				.unwrap_or_default(),
107			channel_count: encoder
108				.profile()
109				.map(|profile| profile.channel_count)
110				.unwrap_or_default(),
111			priming_frames: encoder.priming_frames(),
112		});
113		let muxer = VideoMuxer::new(&config.output_path, mux_config)?;
114		Ok(Self {
115			state: Some(RecorderState {
116				encoder,
117				muxer,
118				audio_encoder,
119				pending_audio: Vec::new(),
120				audio_scratch: Vec::new(),
121				first_video_pts_micros: 0,
122				next_audio_frame: 0,
123				has_first_video_pts: false,
124				submitted_frame_count: 0,
125				muxed_frame_count: 0,
126				codec_config_written: false,
127				finalized: false,
128			}),
129			config,
130		})
131	}
132
133	/// Submit one packed RGBA8 frame and mux every packet now complete.
134	///
135	/// `rgba` must contain exactly `encode.width * encode.height * 4` bytes.
136	/// The encode job runs asynchronously on the session's slot ring; packets
137	/// are muxed in submission order while `finalize` drains the tail.
138	///
139	/// # Errors
140	///
141	/// Returns an error after close or finalize, for a mismatched input size,
142	/// or when submission, feedback, or muxing fails.
143	pub fn write_rgba(&mut self, rgba: &[u8], pts_micros: u64) -> Result<()> {
144		let (color_space, full_range) = color_selection(&self.config);
145		let state = self.open_state()?;
146		state.set_first_video_pts(pts_micros)?;
147		let ready = state
148			.encoder
149			.submit_rgba(rgba, pts_micros, color_space, full_range)?;
150		state.submitted_frame_count += 1;
151		for packet in &ready {
152			state.write_encoded(packet)?;
153		}
154		Ok(())
155	}
156
157	/// Append captured interleaved F32 audio aligned to the video timeline.
158	///
159	/// Sample format must match the configured audio profile. Chunks received
160	/// before the first video frame are retained until the first video
161	/// presentation timestamp arrives; gaps are filled with silence and
162	/// overlapping samples are trimmed.
163	///
164	/// # Errors
165	///
166	/// Returns an error after close or finalize, when audio is not enabled,
167	/// for a mismatched sample format or incomplete frames, or when encoding
168	/// or muxing fails.
169	pub fn write_audio(
170		&mut self,
171		interleaved: &[f32],
172		sample_rate: u32,
173		channel_count: u32,
174		pts_micros: u64,
175	) -> Result<()> {
176		let profile = self
177			.config
178			.audio
179			.ok_or_else(|| Error::failed_precondition("VideoRecorder audio was not enabled"))?;
180		if sample_rate != profile.sample_rate || channel_count != profile.channel_count {
181			return Err(Error::invalid_argument(
182				"audio chunk format does not match the recorder profile",
183			));
184		}
185		if interleaved.is_empty() || !interleaved.len().is_multiple_of(channel_count as usize) {
186			return Err(Error::invalid_argument(
187				"audio chunk contains incomplete interleaved frames",
188			));
189		}
190		let state = self.open_state()?;
191		if !state.has_first_video_pts {
192			state.pending_audio.push(PendingAudioChunk {
193				samples: interleaved.to_vec(),
194				pts_micros,
195			});
196			return Ok(());
197		}
198		state.write_audio_aligned(interleaved, pts_micros)
199	}
200
201	/// Append one capture chunk through [`write_audio`](Self::write_audio).
202	///
203	/// # Errors
204	///
205	/// Returns an error under the same conditions as `write_audio`.
206	pub fn write_audio_chunk(&mut self, chunk: &AudioCaptureChunk) -> Result<()> {
207		self.write_audio(
208			&chunk.interleaved,
209			chunk.sample_rate,
210			chunk.channel_count,
211			chunk.presentation_timestamp_us,
212		)
213	}
214
215	/// Drain the encoder, flush pending audio, and finalize the container.
216	///
217	/// Idempotent: a second call returns `Ok(())`. A recording with no muxed
218	/// frame cannot be finalized — the file would carry a header and no
219	/// samples.
220	///
221	/// # Errors
222	///
223	/// Returns an error after close, when any outstanding encode job fails,
224	/// or when the container trailer cannot be written.
225	pub fn finalize(&mut self) -> Result<()> {
226		let Some(state) = self.state.as_mut() else {
227			return Err(Error::failed_precondition("VideoRecorder is not open"));
228		};
229		if state.finalized {
230			return Ok(());
231		}
232		for packet in &state.encoder.flush()? {
233			state.write_encoded(packet)?;
234		}
235		if let Some(audio) = &mut state.audio_encoder {
236			if !state.has_first_video_pts {
237				state.pending_audio.clear();
238			}
239			for packet in &audio.flush()? {
240				state.muxer.write_audio_packet(packet)?;
241			}
242		}
243		if state.submitted_frame_count == 0 || state.muxed_frame_count == 0 {
244			return Err(Error::failed_precondition(
245				"VideoRecorder cannot finalize an empty recording",
246			));
247		}
248		state.muxer.finalize()?;
249		state.finalized = true;
250		Ok(())
251	}
252
253	/// Abandon the recording and release encoder, muxer, and host state.
254	///
255	/// Closing an unfinished recording never writes a movie trailer; the
256	/// output file remains at whatever was muxed so far. Call
257	/// [`finalize`](Self::finalize) first when the recording is required.
258	pub fn close(&mut self) {
259		self.state = None;
260	}
261
262	/// Return whether the recorder still accepts video and audio input.
263	#[must_use]
264	pub fn is_open(&self) -> bool {
265		self.state.as_ref().is_some_and(|state| !state.finalized)
266	}
267
268	/// Return the number of video frames submitted for encode.
269	#[must_use]
270	pub fn frame_count(&self) -> u64 {
271		self
272			.state
273			.as_ref()
274			.map_or(0, |state| state.submitted_frame_count)
275	}
276
277	/// Return the active configuration.
278	#[must_use]
279	pub const fn config(&self) -> &VideoRecorderConfig {
280		&self.config
281	}
282
283	fn open_state(&mut self) -> Result<&mut RecorderState> {
284		let state = self
285			.state
286			.as_mut()
287			.ok_or_else(|| Error::failed_precondition("VideoRecorder is not open"))?;
288		if state.finalized {
289			return Err(Error::failed_precondition("VideoRecorder is finalized"));
290		}
291		Ok(state)
292	}
293}
294
295impl RecorderState {
296	/// Mux one encoded packet, seeding the container's codec configuration
297	/// from the first keyframe's embedded parameter sets.
298	fn write_encoded(&mut self, packet: &EncodedVideoPacket) -> Result<()> {
299		if !self.codec_config_written && packet.is_keyframe() {
300			let bitstream = packet.bitstream();
301			match self.muxer.config().codec {
302				VideoCodec::H264 => {
303					let sps = extract_sps(bitstream)
304						.ok_or_else(|| Error::data_loss("encoded H.264 keyframe does not contain SPS/PPS"))?;
305					let pps = extract_pps(bitstream)
306						.ok_or_else(|| Error::data_loss("encoded H.264 keyframe does not contain SPS/PPS"))?;
307					self.muxer.set_h264_codec_config(&sps, &pps)?;
308				}
309				VideoCodec::H265 => {
310					let vps = extract_vps_h265(bitstream).ok_or_else(|| {
311						Error::data_loss("encoded H.265 keyframe does not contain VPS/SPS/PPS")
312					})?;
313					let sps = extract_sps_h265(bitstream).ok_or_else(|| {
314						Error::data_loss("encoded H.265 keyframe does not contain VPS/SPS/PPS")
315					})?;
316					let pps = extract_pps_h265(bitstream).ok_or_else(|| {
317						Error::data_loss("encoded H.265 keyframe does not contain VPS/SPS/PPS")
318					})?;
319					self.muxer.set_h265_codec_config(&vps, &sps, &pps)?;
320				}
321				_ => {
322					return Err(Error::missing_capability(
323						"the recorder's container configuration supports H.264/H.265 only",
324					));
325				}
326			}
327			self.codec_config_written = true;
328		}
329		self.muxer.write_packet(packet)?;
330		self.muxed_frame_count += 1;
331		Ok(())
332	}
333
334	/// Establish the shared timeline's origin on the first video frame and
335	/// release every audio chunk buffered while it was unknown.
336	fn set_first_video_pts(&mut self, pts_micros: u64) -> Result<()> {
337		if self.has_first_video_pts {
338			return Ok(());
339		}
340		self.first_video_pts_micros = pts_micros;
341		self.has_first_video_pts = true;
342		let pending = std::mem::take(&mut self.pending_audio);
343		for chunk in &pending {
344			self.write_audio_aligned(&chunk.samples, chunk.pts_micros)?;
345		}
346		Ok(())
347	}
348
349	/// Encode `interleaved` at the timeline position `pts_micros` implies,
350	/// filling gaps with silence and trimming overlap, then mux the packets.
351	fn write_audio_aligned(&mut self, interleaved: &[f32], pts_micros: u64) -> Result<()> {
352		let Some(audio) = &self.audio_encoder else {
353			return Err(Error::failed_precondition(
354				"VideoRecorder audio was not enabled",
355			));
356		};
357		let channels = u64::from(
358			audio
359				.profile()
360				.map(|profile| profile.channel_count)
361				.unwrap_or_default(),
362		);
363		let sample_rate = i64::from(
364			audio
365				.profile()
366				.map(|profile| profile.sample_rate)
367				.unwrap_or_default(),
368		);
369		let input_frames = interleaved.len() as u64 / channels;
370		let delta_micros = pts_micros
371			.checked_sub(self.first_video_pts_micros)
372			.map(i64::try_from)
373			.transpose()
374			.map_err(|_| Error::out_of_range("audio timeline offset exceeds i64"))?
375			.unwrap_or_else(|| {
376				-i64::try_from(self.first_video_pts_micros - pts_micros).unwrap_or(i64::MIN)
377			});
378		let desired_start = delta_micros
379			.checked_mul(sample_rate)
380			.ok_or_else(|| Error::out_of_range("audio timeline offset overflows"))?
381			/ 1_000_000;
382		let desired_end = desired_start + input_frames as i64;
383		if desired_end <= self.next_audio_frame as i64 {
384			return Ok(());
385		}
386		let mut trim_frames = 0_u64;
387		if desired_start < self.next_audio_frame as i64 {
388			trim_frames = self.next_audio_frame - desired_start as u64;
389		}
390		let audio = self.audio_encoder.as_mut().expect("audio checked");
391		if desired_start > self.next_audio_frame as i64 {
392			let gap_frames = desired_start as u64 - self.next_audio_frame;
393			self
394				.audio_scratch
395				.resize(gap_frames as usize * channels as usize, 0.0);
396			for packet in &audio.encode(&self.audio_scratch)? {
397				self.muxer.write_audio_packet(packet)?;
398			}
399			self.next_audio_frame += gap_frames;
400		}
401		if trim_frames >= input_frames {
402			return Ok(());
403		}
404		let accepted_frames = input_frames - trim_frames;
405		let sample_offset = (trim_frames * channels) as usize;
406		let sample_count = (accepted_frames * channels) as usize;
407		for packet in &audio.encode(&interleaved[sample_offset..sample_offset + sample_count])? {
408			self.muxer.write_audio_packet(packet)?;
409		}
410		self.next_audio_frame += accepted_frames;
411		Ok(())
412	}
413}
414
415/// Map a public color matrix to the conversion kernel's selector.
416const fn color_selection(config: &VideoRecorderConfig) -> (u32, bool) {
417	let space = match config.color_space {
418		VideoColorMatrix::Bt601 => 0,
419		VideoColorMatrix::Bt709 | VideoColorMatrix::Unspecified => 1,
420		VideoColorMatrix::Bt2020 => 2,
421	};
422	(space, config.full_range)
423}
424
425fn encode_codec(config: &VideoRecorderConfig) -> VideoCodec {
426	match config.encode.profile {
427		super::VideoEncodeProfile::H264 { .. } => VideoCodec::H264,
428		super::VideoEncodeProfile::H265 { .. } => VideoCodec::H265,
429	}
430}