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