1use 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
55pub struct VideoRecorder {
63 state: Option<RecorderState>,
64 config: VideoRecorderConfig,
65}
66
67impl VideoRecorder {
68 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 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 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 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 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 pub fn close(&mut self) {
259 self.state = None;
260 }
261
262 #[must_use]
264 pub fn is_open(&self) -> bool {
265 self.state.as_ref().is_some_and(|state| !state.finalized)
266 }
267
268 #[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 #[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 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 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 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
415const 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}