Skip to main content

alpha2_native/
video_encode.rs

1//! Video-only encode sink.
2
3use 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/// Configuration for deterministic native video encoding.
24#[derive(Copy, Clone, Debug, PartialEq)]
25pub struct VideoEncodeConfig {
26    /// Encoded frame width; 4:2:0 codecs require an even value.
27    pub width: u32,
28    /// Encoded frame height; 4:2:0 codecs require an even value.
29    pub height: u32,
30    /// Constant output frame rate.
31    pub frame_rate: FrameRate,
32    /// SDR output color tags.
33    pub color: ColorMetadata,
34    /// Resolved rate control; the host resolves the quality level before this point.
35    pub rate_control: VideoRateControl,
36    /// Video codec selected by the downstream host.
37    pub codec: NativeVideoCodec,
38    /// How the pictures are shown, recorded by the container.
39    pub display: VideoDisplay,
40    /// The file format the output is written in, which must offer `codec`.
41    pub container: Container,
42    /// The pictures the output is written in ([`alpha2_media::resolve_pixels`]): 8-bit 4:2:0 unless
43    /// the export asked for alpha or 10 bits.
44    pub pixels: alpha2_media::PixelLayout,
45}
46
47/// How encoded pictures are shown, as recorded by the container rather than the bitstream.
48#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
49pub struct VideoDisplay {
50    /// Turned and mirrored as this says (MP4's `tkhd` display matrix).
51    pub orientation: Orientation,
52    /// Pixel width for its height (the bitstream and container sample aspect ratio).
53    pub sample_aspect_ratio: SampleAspectRatio,
54}
55
56/// Refuses an output this sink cannot write, saying which condition fails.
57pub(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
101/// Writes the container-side description of a stream: display matrix, pixel
102/// aspect ratio, and codec tag.
103pub(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
130/// Transactional `FFmpeg` video encoder and muxer.
131///
132/// Frames go to a sibling partial file, renamed to the destination only after a
133/// successful drain and trailer write.
134pub struct NativeVideoEncodeSink {
135    pub(crate) output: Option<OutputFile>,
136    /// The partial file `output` writes. Declared after `output`, which closes first.
137    pub(crate) partial: PartialOutput,
138    /// How the finished file was published.
139    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    /// One frame in `encoder_time_base`.
144    pub(crate) frame_units: i64,
145    pub(crate) stream_time_base: AVRational,
146    pub(crate) scaler: alpha2_ffmpeg_bridge::PackedScaler,
147    /// Turns decoded YUV of any layout into the encoder's 4:2:0.
148    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    /// Creates a sink that encodes `config.codec` into a `config.container` file at `path`.
159    ///
160    /// # Errors
161    /// Returns an adapter failure for invalid dimensions, paths, codecs, or muxers.
162    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    /// Creates a concrete encoder selected by its `FFmpeg` short name.
170    ///
171    /// # Errors
172    /// Returns an adapter failure when the name is unavailable, implements a different codec, or
173    /// the remaining configuration is invalid.
174    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    /// Creates an encoder whose software thread count the caller decides.
183    ///
184    /// `software_threads` is asked at most once, only when a CPU candidate opens, so a hardware
185    /// candidate that falls through to software still gets a software share of the CPU.
186    ///
187    /// `encoder_name` pins one encoder (that one or an error); `None` tries the codec's
188    /// candidates in preference order.
189    ///
190    /// # Errors
191    /// Returns an adapter failure when no candidate opens or the output configuration is invalid.
192    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        // The frame length, or the finest unit an encoder that cannot hold it takes.
227        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    /// Where this sink's time has gone so far.
277    #[must_use]
278    pub fn stage_timings(&self) -> EncodeStageTimings {
279        self.stages
280    }
281
282    /// The encoder this sink opened, and the candidates it passed over.
283    #[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    /// Encodes a frame the caller already packed, without copying it.
329    ///
330    /// [`EncodeEvent::Video`] copies engine planes into a new `AVFrame` on the encode worker, the
331    /// saturated thread; a caller that packed straight into an encoder frame hands it over instead.
332    ///
333    /// # Errors
334    /// Returns an error for a frame sized differently from this encoder, a non-monotonic
335    /// timestamp, or a codec failure.
336    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        // Decoded and RGBA frames are converted to YUV420P; other outputs take
372        // caller-packed frames ([`Self::write_prepared_video`]).
373        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        // Without alpha in the output, keep premultiplied RGB: frames arrive opaque
425        // over the project background, and dividing alpha out would show
426        // translucent layers at full strength.
427        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    /// How the finished file was published; `None` until it is.
482    #[must_use]
483    pub fn publish_report(&self) -> Option<PublishReport> {
484        self.published
485    }
486
487    /// Flushes the encoder, writes the trailer and closes the file,
488    /// before [`EncodeSink::finish`] publishes.
489    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        // A write error reported only at close fails the export here, before the rename.
502        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}