1use std::fs;
4use std::path::PathBuf;
5
6use crate::capabilities::{
7 NativeVideoCodec, NativeVideoEncoderSelection, VideoEncoderOpenRequest, open_video_encoder,
8};
9use crate::convert::{
10 codec_thread_budget, configure_rgba_to_yuv, encode_adapter_error, encode_adapter_error_at,
11 tick_base,
12};
13use crate::encode::{EncodeStageTimings, timed};
14use crate::partial::{OutputTarget, PartialOutput};
15use alpha2_ffmpeg_bridge::OutputFile;
16use alpha2_ffmpeg_bridge::Yuv420pFrameBuffer;
17use alpha2_media::{
18 CancelToken, ColorMatrix, ColorMetadata, Container, DecodedVideoFrame, EncodeError,
19 EncodeEvent, EncodeSink, Orientation, PixelFormat, SampleAspectRatio, VideoRateControl,
20};
21use alpha2_time::{FrameRate, MediaTime};
22use rsmpeg::avutil::{AVFrameWithImage, AVImage, AVRational, av_rescale_q, ra};
23use rsmpeg::error::RsmpegError;
24use rsmpeg::ffi;
25use rsmpeg::swscale::SwsContext;
26
27#[derive(Copy, Clone, Debug, PartialEq)]
29pub struct VideoEncodeConfig {
30 pub width: u32,
32 pub height: u32,
34 pub frame_rate: FrameRate,
36 pub color: ColorMetadata,
38 pub rate_control: VideoRateControl,
41 pub codec: NativeVideoCodec,
43 pub display: VideoDisplay,
45 pub container: Container,
47}
48
49#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
52pub struct VideoDisplay {
53 pub orientation: Orientation,
55 pub sample_aspect_ratio: SampleAspectRatio,
58}
59
60pub(crate) fn check_video_config(config: &VideoEncodeConfig) -> Result<(), EncodeError> {
62 let refuse = |reason: String| Err(EncodeError::Adapter(reason));
63 if !config.container.offers_video(config.codec.model()) {
64 return refuse(format!(
65 "{} does not offer video codec {}",
66 config.container,
67 config.codec.as_str()
68 ));
69 }
70 if config.width == 0
71 || config.height == 0
72 || !config.width.is_multiple_of(2)
73 || !config.height.is_multiple_of(2)
74 {
75 return refuse(format!(
76 "a {}x{} output is refused: 4:2:0 video needs an even, non-zero width and height",
77 config.width, config.height
78 ));
79 }
80 if config.rate_control.bitrate == 0 {
81 return refuse("the output bitrate must be positive".into());
82 }
83 if config.color.is_hdr() {
84 return refuse(format!(
85 "the output is HDR ({:?}), and native encoding writes SDR only",
86 config.color.transfer
87 ));
88 }
89 if config.color.matrix == ColorMatrix::Rgb {
90 return refuse(
91 "the output is tagged as RGB, and 4:2:0 video is Y'CbCr: tag the matrix it is encoded with"
92 .into(),
93 );
94 }
95 let sar = config.display.sample_aspect_ratio;
96 if sar.num == 0 || sar.den == 0 || i32::try_from(sar.num.max(sar.den)).is_err() {
97 return refuse(format!(
98 "the pixel aspect ratio {}:{} is out of range",
99 sar.num, sar.den
100 ));
101 }
102 Ok(())
103}
104
105pub(crate) fn describe_output_stream(
108 stream: &mut rsmpeg::avformat::AVStreamMut<'_>,
109 codec_id: ffi::AVCodecID,
110 display: VideoDisplay,
111 container: Container,
112) -> Result<(), EncodeError> {
113 let sar = display.sample_aspect_ratio;
114 if sar != SampleAspectRatio::default() {
115 stream.set_sample_aspect_ratio(ra(
116 i32::try_from(sar.num).unwrap_or(1),
117 i32::try_from(sar.den).unwrap_or(1),
118 ));
119 }
120 if let Some(matrix) = crate::convert::display_of(display.orientation) {
121 alpha2_ffmpeg_bridge::set_stream_display_matrix(stream, matrix)
122 .map_err(encode_adapter_error)?;
123 }
124 let tag = crate::convert::container_codec_tag(
125 container,
126 codec_id,
127 stream.codecpar().codec_tag,
128 false,
129 );
130 alpha2_ffmpeg_bridge::set_stream_codec_tag(stream, tag);
131 Ok(())
132}
133
134pub struct NativeVideoEncodeSink {
139 pub(crate) target: OutputTarget,
140 pub(crate) partial_path: PathBuf,
141 pub(crate) _partial_lock: crate::partial::PartialLock,
143 pub(crate) output: Option<OutputFile>,
144 pub(crate) encoder: crate::video_backend::VideoEncoderBackend,
145 pub(crate) stream_index: i32,
146 pub(crate) encoder_time_base: AVRational,
147 pub(crate) frame_units: i64,
149 pub(crate) stream_time_base: AVRational,
150 pub(crate) scaler: SwsContext,
151 pub(crate) yuv_input: crate::convert::Yuv420pConverter,
153 pub(crate) width: i32,
154 pub(crate) height: i32,
155 pub(crate) last_pts: Option<i64>,
156 pub(crate) complete: bool,
157 pub(crate) selection: NativeVideoEncoderSelection,
158 pub(crate) stages: EncodeStageTimings,
159}
160
161impl NativeVideoEncodeSink {
162 pub fn create(
167 path: impl Into<OutputTarget>,
168 config: VideoEncodeConfig,
169 ) -> Result<Self, EncodeError> {
170 Self::create_selected(path, config, None, &codec_thread_budget)
171 }
172
173 pub fn create_with_encoder(
179 path: impl Into<OutputTarget>,
180 config: VideoEncodeConfig,
181 encoder_name: &str,
182 ) -> Result<Self, EncodeError> {
183 Self::create_selected(path, config, Some(encoder_name), &codec_thread_budget)
184 }
185
186 pub fn create_with_encoder_threads(
203 path: impl Into<OutputTarget>,
204 config: VideoEncodeConfig,
205 encoder_name: Option<&str>,
206 software_threads: &dyn Fn() -> i64,
207 ) -> Result<Self, EncodeError> {
208 Self::create_selected(path, config, encoder_name, software_threads)
209 }
210
211 #[allow(clippy::too_many_lines)]
212 pub(crate) fn create_selected(
213 path: impl Into<OutputTarget>,
214 config: VideoEncodeConfig,
215 encoder_name: Option<&str>,
216 software_threads: &dyn Fn() -> i64,
217 ) -> Result<Self, EncodeError> {
218 check_video_config(&config)?;
219 let target = path.into();
220 let partial = PartialOutput::claim(&target)?;
221 let partial_path = partial.path().to_owned();
222 let mut output = partial.open_muxer(config.container)?;
223 let width = i32::try_from(config.width)
224 .map_err(|_| EncodeError::Adapter("width is out of range".into()))?;
225 let height = i32::try_from(config.height)
226 .map_err(|_| EncodeError::Adapter("height is out of range".into()))?;
227 let (encoder, selection) = open_video_encoder(&VideoEncoderOpenRequest {
228 config: &config,
229 requested_name: encoder_name,
230 threads: crate::capabilities::SoftwareEncoderThreads::new(software_threads),
231 global_header: output.oformat().flags
232 & i32::try_from(ffi::AVFMT_GLOBALHEADER).unwrap_or(0)
233 != 0,
234 width,
235 height,
236 })?;
237 let encoder_time_base = encoder.time_base();
239 let mut stream_time_base;
240 let stream_index;
241 {
242 let mut stream = output.new_stream();
243 stream_time_base = encoder_time_base;
244 stream.set_time_base(stream_time_base);
245 let parameters = encoder.codec_parameters();
246 stream.set_codecpar(parameters);
247 describe_output_stream(
248 &mut stream,
249 encoder.codec_id(),
250 config.display,
251 config.container,
252 )?;
253 stream_index = stream.index;
254 }
255 output
256 .write_header(&mut crate::convert::muxer_header_options(config.container))
257 .map_err(encode_adapter_error)?;
258 stream_time_base = output.streams()[usize::try_from(stream_index).unwrap_or(0)].time_base;
259 let mut scaler = SwsContext::get_context(
260 width,
261 height,
262 ffi::AV_PIX_FMT_RGBA,
263 width,
264 height,
265 ffi::AV_PIX_FMT_YUV420P,
266 ffi::SWS_BILINEAR,
267 None,
268 None,
269 None,
270 )
271 .ok_or_else(|| EncodeError::Adapter("cannot create RGBA to YUV scaler".into()))?;
272 configure_rgba_to_yuv(&mut scaler, config.color).map_err(encode_adapter_error)?;
273 let partial_lock = partial.keep();
274 Ok(Self {
275 target,
276 partial_path,
277 _partial_lock: partial_lock,
278 output: Some(output),
279 encoder,
280 stream_index,
281 encoder_time_base,
282 frame_units: crate::mux::frame_units(config.frame_rate, encoder_time_base),
283 stream_time_base,
284 scaler,
285 yuv_input: crate::convert::Yuv420pConverter::new(config.color),
286 width,
287 height,
288 last_pts: None,
289 complete: false,
290 selection,
291 stages: EncodeStageTimings::default(),
292 })
293 }
294
295 #[must_use]
297 pub fn stage_timings(&self) -> EncodeStageTimings {
298 self.stages
299 }
300
301 #[must_use]
303 pub fn selection(&self) -> &NativeVideoEncoderSelection {
304 &self.selection
305 }
306
307 pub(crate) fn drain_packets(&mut self, flushing: bool) -> Result<(), EncodeError> {
308 loop {
309 let received = timed(&mut self.stages.video_receive_packet, || {
310 self.encoder.receive_packet()
311 });
312 match received {
313 Ok(mut packet) => {
314 packet.set_stream_index(self.stream_index);
315 crate::mux::fill_frame_duration(&mut packet, self.frame_units);
316 packet.rescale_ts(self.encoder_time_base, self.stream_time_base);
317 let output = self
318 .output
319 .as_mut()
320 .ok_or_else(|| EncodeError::Adapter("muxer is already closed".into()))?;
321 timed(&mut self.stages.video_mux_write, || {
322 output.interleaved_write_frame(&mut packet)
323 })
324 .map_err(|error| encode_adapter_error_at("packet write failed", error))?;
325 }
326 Err(RsmpegError::EncoderDrainError) if !flushing => return Ok(()),
327 Err(RsmpegError::EncoderFlushedError | RsmpegError::EncoderDrainError)
328 if flushing =>
329 {
330 return Ok(());
331 }
332 Err(error) => {
333 return Err(encode_adapter_error_at(
334 "video encoder packet drain failed",
335 error,
336 ));
337 }
338 }
339 }
340 }
341
342 pub fn write_prepared_video(
353 &mut self,
354 frame: &mut Yuv420pFrameBuffer,
355 pts: MediaTime,
356 ) -> Result<(), EncodeError> {
357 let (width, height) = frame.size();
358 if width != usize::try_from(self.width).unwrap_or(0)
359 || height != usize::try_from(self.height).unwrap_or(0)
360 {
361 return Err(EncodeError::Adapter(
362 "encoder input dimensions do not match its configuration".into(),
363 ));
364 }
365 let pts = av_rescale_q(pts.ticks(), tick_base(), self.encoder_time_base);
366 if self.last_pts.is_some_and(|previous| pts <= previous) {
367 return Err(EncodeError::InvalidTimestamp);
368 }
369 frame.set_presentation(pts, self.encoder_time_base);
370 timed(&mut self.stages.video_send_frame, || {
371 self.encoder.send_frame(Some(frame.frame()))
372 })
373 .map_err(|error| {
374 encode_adapter_error_at("video encoder rejected a YUV420P frame", error)
375 })?;
376 self.last_pts = Some(pts);
377 self.drain_packets(false)
378 }
379
380 pub(crate) fn write_video(&mut self, frame: &DecodedVideoFrame) -> Result<(), EncodeError> {
381 if frame.visible_rect.width != u32::try_from(self.width).unwrap_or(0)
382 || frame.visible_rect.height != u32::try_from(self.height).unwrap_or(0)
383 {
384 return Err(EncodeError::Adapter(
385 "encoder input dimensions do not match its configuration".into(),
386 ));
387 }
388 let pts = av_rescale_q(frame.pts.ticks(), tick_base(), self.encoder_time_base);
389 if self.last_pts.is_some_and(|previous| pts <= previous) {
390 return Err(EncodeError::InvalidTimestamp);
391 }
392 if let Some(mut yuv) = self.yuv_input.convert(frame, self.width, self.height)? {
393 yuv.set_pts(pts);
394 yuv.set_time_base(self.encoder_time_base);
395 timed(&mut self.stages.video_send_frame, || {
396 self.encoder.send_frame(Some(&yuv))
397 })
398 .map_err(|error| {
399 encode_adapter_error_at("video encoder rejected a YUV420P frame", error)
400 })?;
401 self.last_pts = Some(pts);
402 return self.drain_packets(false);
403 }
404 if frame.pixel_format != PixelFormat::Rgba8 || frame.planes.len() != 1 {
405 return Err(EncodeError::Adapter(
406 "encoder expects YUV planes or one tightly packed RGBA8 plane".into(),
407 ));
408 }
409 let plane = &frame.planes[0];
410 let expected = usize::try_from(self.width)
411 .ok()
412 .and_then(|width| {
413 usize::try_from(self.height)
414 .ok()
415 .and_then(|height| width.checked_mul(height))
416 })
417 .and_then(|pixels| pixels.checked_mul(4))
418 .ok_or_else(|| EncodeError::Adapter("frame dimensions overflow".into()))?;
419 if plane.bytes.len() != expected
420 || plane.stride != u32::try_from(self.width).unwrap_or(0) * 4
421 {
422 return Err(EncodeError::Adapter(
423 "RGBA plane is not tightly packed".into(),
424 ));
425 }
426 let rgba = alpha2_ffmpeg_bridge::rgba_frame(&plane.bytes, self.width, self.height)
430 .map_err(encode_adapter_error)?;
431 let yuv_image = AVImage::new(ffi::AV_PIX_FMT_YUV420P, self.width, self.height, 1)
432 .ok_or_else(|| EncodeError::Adapter("cannot allocate YUV input".into()))?;
433 let mut yuv = AVFrameWithImage::new(yuv_image);
434 self.scaler
435 .scale_frame(&rgba, 0, self.height, &mut yuv)
436 .map_err(encode_adapter_error)?;
437 yuv.set_pts(pts);
438 yuv.set_time_base(self.encoder_time_base);
439 timed(&mut self.stages.video_send_frame, || {
440 self.encoder.send_frame(Some(&yuv))
441 })
442 .map_err(|error| {
443 encode_adapter_error_at("video encoder rejected a converted YUV420P frame", error)
444 })?;
445 self.last_pts = Some(pts);
446 self.drain_packets(false)
447 }
448}
449
450impl EncodeSink for NativeVideoEncodeSink {
451 fn write(&mut self, event: EncodeEvent, cancel: &CancelToken) -> Result<(), EncodeError> {
452 if cancel.is_cancelled() {
453 self.abort()?;
454 return Err(EncodeError::Cancelled);
455 }
456 match event {
457 EncodeEvent::Video(frame) => self.write_video(&frame),
458 EncodeEvent::Audio(_) => Err(EncodeError::Adapter(
459 "this sink was configured for video-only output".into(),
460 )),
461 }
462 }
463
464 fn finish(&mut self, cancel: &CancelToken) -> Result<(), EncodeError> {
465 if cancel.is_cancelled() {
466 self.abort()?;
467 return Err(EncodeError::Cancelled);
468 }
469 timed(&mut self.stages.video_send_frame, || {
470 self.encoder.send_frame(None)
471 })
472 .map_err(encode_adapter_error)?;
473 self.drain_packets(true)?;
474 crate::encode::beat_encode_call();
475 self.output
476 .as_mut()
477 .ok_or_else(|| EncodeError::Adapter("muxer is already closed".into()))?
478 .write_trailer()
479 .map_err(encode_adapter_error)?;
480 if let Some(output) = self.output.take() {
482 crate::encode::beat_encode_call();
483 output
484 .close()
485 .map_err(|error| encode_adapter_error_at("closing the output", error))?;
486 }
487 crate::partial::publish(&self.partial_path, &self.target)?;
488 self.complete = true;
489 Ok(())
490 }
491
492 fn abort(&mut self) -> Result<(), EncodeError> {
493 drop(self.output.take());
494 match fs::remove_file(&self.partial_path) {
495 Ok(()) => Ok(()),
496 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
497 Err(error) => Err(EncodeError::Adapter(error.to_string())),
498 }
499 }
500}
501
502impl Drop for NativeVideoEncodeSink {
503 fn drop(&mut self) {
504 if !self.complete {
505 drop(self.output.take());
506 let _ = fs::remove_file(&self.partial_path);
507 }
508 }
509}