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