Skip to main content

alpha2_host_core/
encode.rs

1//! Encoder sessions behind traits, and the sink that turns an export's pictures and mixed audio
2//! into a container's tracks.
3
4use std::collections::VecDeque;
5use std::time::{Duration, Instant};
6
7use alpha2_container::{
8    AudioCodec, AudioTrack, ContainerWriter, Packet, TrackId, TrackInfo, TrackKind, VideoCodec,
9    VideoTrack,
10};
11use alpha2_media::{
12    AudioBlock, AudioBlockSink, CancelToken, ColorMetadata, EncodeError, Orientation, PixelLayout,
13    SpeakerLayout, VideoRateControl,
14};
15use alpha2_time::FrameRate;
16use bytes::Bytes;
17
18use crate::audio_frames::EncoderAudioInput;
19use crate::rate_control::AppliedRateControl;
20use crate::video_stream::Submit;
21
22/// One plane of a rendered picture.
23#[derive(Clone, Debug, Default)]
24pub struct PlaneBuffer {
25    /// The rows, `stride` bytes apart.
26    pub bytes: Vec<u8>,
27    /// Bytes between rows.
28    pub stride: usize,
29    /// Width in samples.
30    pub width: u32,
31    /// Height in rows.
32    pub height: u32,
33}
34
35/// What a video encoder is asked for.
36#[derive(Clone, Copy, Debug, PartialEq)]
37pub struct VideoEncodeConfig {
38    /// The codec.
39    pub codec: alpha2_media::VideoCodec,
40    /// Picture width in pixels.
41    pub width: u32,
42    /// Picture height in pixels.
43    pub height: u32,
44    /// Frames per second.
45    pub frame_rate: FrameRate,
46    /// The planes each frame arrives in.
47    pub layout: PixelLayout,
48    /// The rate control the export resolved.
49    pub rate: VideoRateControl,
50    /// The color the bitstream is tagged with.
51    pub color: ColorMetadata,
52    /// Frames between forced keyframes.
53    pub keyframe_interval: u32,
54    /// Ask for a software encoder (a retry after a hardware encoder failed).
55    pub software: bool,
56}
57
58/// One encoded frame.
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct EncodedPacket {
61    /// Presentation time, in the session's time units.
62    pub pts: i64,
63    /// Decode time, in the same units.
64    pub dts: i64,
65    /// A sync sample.
66    pub keyframe: bool,
67    /// The frame, as the container stores it (length-prefixed NAL units for H.264 and HEVC).
68    pub data: Bytes,
69}
70
71/// What an encoder session had on a receive.
72#[derive(Debug)]
73pub enum EncodePoll {
74    /// A packet.
75    Packet(EncodedPacket),
76    /// Nothing yet.
77    Pending,
78    /// Input ended and every packet was given.
79    Drained,
80}
81
82/// One video encoder session, used from one thread at a time.
83///
84/// A session the platform takes away fails the encoder unless the backend can resume it in place
85/// with the same configuration record, as `VideoToolbox` can and Android `MediaCodec` cannot.
86pub trait VideoEncodeBackend: Send {
87    /// The encoder's name, for reports.
88    fn name(&self) -> &str;
89
90    /// Whether it runs on hardware.
91    fn hardware(&self) -> bool;
92
93    /// Units per second of the timestamps it takes and gives.
94    fn timescale(&self) -> u32;
95
96    /// Queues a frame at `pts` whose planes are in the configured layout.
97    ///
98    /// # Errors
99    /// A failed encoder.
100    fn submit(
101        &mut self,
102        pts: i64,
103        planes: &[PlaneBuffer],
104        keyframe: bool,
105    ) -> Result<Submit, EncodeError>;
106
107    /// Takes an encoded packet, in decode order. With `wait`, blocks briefly for one. Once it
108    /// answers [`EncodePoll::Drained`] it keeps answering it.
109    ///
110    /// # Errors
111    /// A failed encoder.
112    fn receive(&mut self, wait: bool) -> Result<EncodePoll, EncodeError>;
113
114    /// Finishes every frame submitted so far without ending the input, so none is inside the
115    /// session while the app is away. The default does nothing.
116    ///
117    /// # Errors
118    /// A failed encoder.
119    fn settle(&mut self) -> Result<(), EncodeError> {
120        Ok(())
121    }
122
123    /// No more frames follow.
124    ///
125    /// # Errors
126    /// A failed encoder.
127    fn finish_input(&mut self) -> Result<(), EncodeError>;
128
129    /// The decoder configuration record (`avcC`, `hvcC`, `av1C`), once the first packet is out.
130    fn codec_private(&self) -> Option<Bytes>;
131
132    /// Which form of the rate control the encoder runs.
133    fn applied_rate_control(&self) -> AppliedRateControl;
134}
135
136/// Opens video encoder sessions.
137pub trait VideoEncoders: Send + Sync {
138    /// A session for `config`.
139    ///
140    /// # Errors
141    /// [`EncodeError::EncodersRefused`] naming every encoder tried.
142    fn open(&self, config: &VideoEncodeConfig) -> Result<Box<dyn VideoEncodeBackend>, EncodeError>;
143}
144
145/// What an audio encoder is asked for.
146#[derive(Clone, Copy, Debug, PartialEq)]
147pub struct AudioEncodeConfig {
148    /// The codec.
149    pub codec: alpha2_media::AudioCodec,
150    /// The project's sample rate, which the audio arrives at.
151    pub project_rate: u32,
152    /// The speakers, one plane each.
153    pub speakers: SpeakerLayout,
154    /// Bits per second.
155    pub bitrate: u32,
156}
157
158/// One audio encoder session, used from one thread at a time.
159pub trait AudioEncodeBackend: Send {
160    /// The encoder's name, for reports.
161    fn name(&self) -> &str;
162
163    /// The rate it encodes at.
164    fn sample_rate(&self) -> u32;
165
166    /// Samples per channel in each frame it takes.
167    fn frame_size(&self) -> usize;
168
169    /// The bits per second it encodes at: the configured rate, or the nearest the encoder takes.
170    fn bitrate(&self) -> u32;
171
172    /// Queues one frame of planar samples starting at sample `pts` of the encoded stream; only
173    /// the last frame may be short.
174    ///
175    /// # Errors
176    /// A failed encoder.
177    fn submit(&mut self, pts: i64, planes: &[Vec<f32>]) -> Result<Submit, EncodeError>;
178
179    /// Takes an encoded packet, timestamps in samples at [`Self::sample_rate`] counted from the
180    /// first decoded sample, priming included. Once it answers [`EncodePoll::Drained`] it keeps
181    /// answering it.
182    ///
183    /// # Errors
184    /// A failed encoder.
185    fn receive(&mut self, wait: bool) -> Result<EncodePoll, EncodeError>;
186
187    /// No more frames follow.
188    ///
189    /// # Errors
190    /// A failed encoder.
191    fn finish_input(&mut self) -> Result<(), EncodeError>;
192
193    /// The codec's setup data (`AudioSpecificConfig`, `OpusHead`), once known.
194    fn codec_private(&self) -> Option<Bytes>;
195
196    /// Samples of priming at the start of the decoded stream, which the container's edit list
197    /// skips.
198    fn priming(&self) -> u32;
199}
200
201/// Opens audio encoder sessions.
202pub trait AudioEncoders: Send + Sync {
203    /// A session for `config`.
204    ///
205    /// # Errors
206    /// [`EncodeError::EncodersRefused`] naming every encoder tried.
207    fn open(&self, config: &AudioEncodeConfig) -> Result<Box<dyn AudioEncodeBackend>, EncodeError>;
208}
209
210/// How long encoders may take no frame and hand out no packet before the sink gives up on them.
211const DRAIN_STALL: Duration = Duration::from_secs(10);
212
213/// The most one turn of a wait adds to a stall, so a process frozen inside a wait adds no more.
214const STALL_TURN: Duration = Duration::from_millis(100);
215
216/// The time a wait on the encoders has made no progress, added up turn by turn.
217struct Stall {
218    last: Instant,
219    stalled: Duration,
220    limit: Duration,
221}
222
223impl Stall {
224    fn new(limit: Duration) -> Self {
225        Self {
226            last: Instant::now(),
227            stalled: Duration::ZERO,
228            limit,
229        }
230    }
231
232    /// Records one turn of the wait; true once the turns without progress reach the limit.
233    fn turn(&mut self, progressed: bool) -> bool {
234        let now = Instant::now();
235        let spent = now.saturating_duration_since(self.last).min(STALL_TURN);
236        self.last = now;
237        self.stalled = if progressed {
238            Duration::ZERO
239        } else {
240            self.stalled + spent
241        };
242        self.stalled >= self.limit
243    }
244}
245
246/// The container codec of `codec` encoded in `layout`: `ProRes` is 4444 (`ap4h`) with alpha, else
247/// 422 HQ (`apch`), as [`crate::codecs::NativeVideoCodec::ProRes`] encodes it.
248fn container_video_codec(codec: alpha2_media::VideoCodec, layout: PixelLayout) -> VideoCodec {
249    match codec {
250        alpha2_media::VideoCodec::H264 => VideoCodec::H264,
251        alpha2_media::VideoCodec::Hevc => VideoCodec::Hevc,
252        alpha2_media::VideoCodec::Vp9 => VideoCodec::Vp9,
253        alpha2_media::VideoCodec::Av1 => VideoCodec::Av1,
254        alpha2_media::VideoCodec::Mpeg4Part2 => VideoCodec::Mpeg4Part2,
255        alpha2_media::VideoCodec::ProRes => {
256            VideoCodec::ProRes(alpha2_container::FourCc(if layout.alpha {
257                *b"ap4h"
258            } else {
259                *b"apch"
260            }))
261        }
262    }
263}
264
265fn container_audio_codec(codec: alpha2_media::AudioCodec) -> AudioCodec {
266    match codec {
267        alpha2_media::AudioCodec::Aac => AudioCodec::Aac,
268        alpha2_media::AudioCodec::Opus => AudioCodec::Opus,
269    }
270}
271
272/// A track waiting for its encoder's configuration record before it is added.
273struct PendingTrack {
274    id: Option<TrackId>,
275    queued: VecDeque<EncodedPacket>,
276}
277
278impl PendingTrack {
279    const fn new() -> Self {
280        Self {
281            id: None,
282            queued: VecDeque::new(),
283        }
284    }
285}
286
287/// How far audio written to the container may run ahead of the video written, in seconds.
288const AUDIO_LEAD: i64 = 1;
289
290/// Whether audio starting at `start` (in units of `rate` per second) is at most [`AUDIO_LEAD`]
291/// past the video packet decoded at `video` (in units of `video_rate`); never before any video.
292fn within_lead(start: i64, rate: u32, video: Option<i64>, video_rate: u32) -> bool {
293    video.is_some_and(|video| {
294        let limit = (i128::from(video) + i128::from(AUDIO_LEAD) * i128::from(video_rate))
295            * i128::from(rate);
296        i128::from(start) * i128::from(video_rate) <= limit
297    })
298}
299
300/// Turns an export's pictures and mixed audio into a container's tracks.
301///
302/// Tracks are added once every encoder has published its configuration record; packets before
303/// that wait. Audio goes to the writer at most one second ahead of the video written, so a mix
304/// encoded before the pictures still reaches the writer interleaved with them.
305pub struct EncodeSink {
306    writer: Option<Box<dyn ContainerWriter>>,
307    video: Box<dyn VideoEncodeBackend>,
308    video_config: VideoEncodeConfig,
309    video_track: PendingTrack,
310    audio: Option<(
311        Box<dyn AudioEncodeBackend>,
312        EncoderAudioInput,
313        AudioEncodeConfig,
314    )>,
315    audio_track: PendingTrack,
316    /// Samples handed to the audio encoder, at its rate.
317    audio_pts: i64,
318    /// The decode time of the last video packet written, in the video encoder's units.
319    video_written: Option<i64>,
320    /// Packets taken from both encoders.
321    received: u64,
322    /// Every input is in: held audio packets go out.
323    finishing: bool,
324    /// Stops the waits on a busy encoder.
325    cancel: CancelToken,
326    /// How long the encoders may make no progress before a wait on them fails.
327    stall_limit: Duration,
328    /// Frames the video encoder accepted.
329    video_frames: u64,
330}
331
332impl std::fmt::Debug for EncodeSink {
333    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
334        formatter
335            .debug_struct("EncodeSink")
336            .field("video", &self.video.name())
337            .finish_non_exhaustive()
338    }
339}
340
341impl EncodeSink {
342    /// A sink writing `video` (and `audio`, when the export has sound) into `writer`; `cancel`
343    /// stops its waits on a busy encoder.
344    #[must_use]
345    pub fn new(
346        writer: Box<dyn ContainerWriter>,
347        video: Box<dyn VideoEncodeBackend>,
348        video_config: VideoEncodeConfig,
349        audio: Option<(Box<dyn AudioEncodeBackend>, AudioEncodeConfig)>,
350        cancel: CancelToken,
351    ) -> Self {
352        let audio = audio.map(|(encoder, config)| {
353            let input = EncoderAudioInput::new(
354                config.project_rate,
355                encoder.sample_rate(),
356                config.speakers.speakers().len(),
357                encoder.frame_size(),
358            );
359            (encoder, input, config)
360        });
361        Self {
362            writer: Some(writer),
363            video,
364            video_config,
365            video_track: PendingTrack::new(),
366            audio,
367            audio_track: PendingTrack::new(),
368            audio_pts: 0,
369            video_written: None,
370            received: 0,
371            finishing: false,
372            cancel,
373            stall_limit: DRAIN_STALL,
374            video_frames: 0,
375        }
376    }
377
378    #[cfg(test)]
379    fn with_stall_limit(mut self, limit: Duration) -> Self {
380        self.stall_limit = limit;
381        self
382    }
383
384    /// The video encoder's name and the rate control it ran.
385    #[must_use]
386    pub fn video_encoder(&self) -> (&str, bool, AppliedRateControl) {
387        (
388            self.video.name(),
389            self.video.hardware(),
390            self.video.applied_rate_control(),
391        )
392    }
393
394    fn writer(&mut self) -> Result<&mut Box<dyn ContainerWriter>, EncodeError> {
395        self.writer
396            .as_mut()
397            .ok_or_else(|| EncodeError::Adapter("the output is already finished".into()))
398    }
399
400    fn video_info(&self) -> Option<TrackInfo> {
401        let private = self.video.codec_private()?;
402        let config = &self.video_config;
403        Some(TrackInfo {
404            id: TrackId(0),
405            kind: TrackKind::Video,
406            timescale: self.video.timescale(),
407            duration: None,
408            language: None,
409            title: None,
410            default: true,
411            enabled: true,
412            video: Some(VideoTrack {
413                codec: container_video_codec(config.codec, config.layout),
414                codec_private: private,
415                in_band_parameter_sets: false,
416                width: config.width,
417                height: config.height,
418                orientation: Orientation::default(),
419                sample_aspect_ratio: None,
420                color: Some(config.color),
421                clean_aperture: None,
422                frame_rate: Some(config.frame_rate),
423                alpha: config.layout.alpha,
424                reorder_depth: None,
425            }),
426            audio: None,
427        })
428    }
429
430    fn audio_info(&self) -> Option<TrackInfo> {
431        let (encoder, _, config) = self.audio.as_ref()?;
432        let private = encoder.codec_private()?;
433        Some(TrackInfo {
434            id: TrackId(0),
435            kind: TrackKind::Audio,
436            timescale: encoder.sample_rate(),
437            duration: None,
438            language: None,
439            title: None,
440            default: true,
441            enabled: true,
442            video: None,
443            audio: Some(AudioTrack {
444                codec: container_audio_codec(config.codec),
445                codec_private: private,
446                sample_rate: encoder.sample_rate(),
447                channels: u32::try_from(config.speakers.channels()).unwrap_or(u32::MAX),
448                speakers: Some(config.speakers),
449                bits_per_sample: None,
450                priming: encoder.priming(),
451                seek_preroll: None,
452            }),
453        })
454    }
455
456    /// Moves packets the encoders have into their tracks.
457    fn drain(&mut self, wait_video: bool, wait_audio: bool) -> Result<(bool, bool), EncodeError> {
458        let mut video_done = false;
459        loop {
460            let received = self.video.receive(wait_video);
461            match received.map_err(|error| self.rejected(error))? {
462                EncodePoll::Packet(packet) => {
463                    self.received += 1;
464                    self.video_track.queued.push_back(packet);
465                }
466                EncodePoll::Pending => break,
467                EncodePoll::Drained => {
468                    video_done = true;
469                    break;
470                }
471            }
472        }
473        let mut audio_done = self.audio.is_none();
474        if let Some((encoder, _, _)) = self.audio.as_mut() {
475            loop {
476                match encoder.receive(wait_audio)? {
477                    EncodePoll::Packet(packet) => {
478                        self.received += 1;
479                        self.audio_track.queued.push_back(packet);
480                    }
481                    EncodePoll::Pending => break,
482                    EncodePoll::Drained => {
483                        audio_done = true;
484                        break;
485                    }
486                }
487            }
488        }
489        self.flush_tracks()?;
490        Ok((video_done, audio_done))
491    }
492
493    /// Adds tracks whose configuration is known and writes their queued packets.
494    fn flush_tracks(&mut self) -> Result<(), EncodeError> {
495        // Containers add every track before the first packet; video is always the first track.
496        if self.video_track.id.is_none() {
497            let Some(video) = self.video_info() else {
498                return Ok(());
499            };
500            let audio = match self.audio {
501                Some(_) => match self.audio_info() {
502                    Some(info) => Some(info),
503                    None => return Ok(()),
504                },
505                None => None,
506            };
507            self.video_track.id = Some(self.writer()?.add_track(&video)?);
508            if let Some(info) = audio {
509                self.audio_track.id = Some(self.writer()?.add_track(&info)?);
510            }
511        }
512        let Some(video) = self.video_track.id else {
513            return Ok(());
514        };
515        let priming = self
516            .audio
517            .as_ref()
518            .map_or(0, |(encoder, _, _)| encoder.priming());
519        let frame_duration = i64::from(self.video_config.frame_rate.denominator())
520            * i64::from(self.video.timescale())
521            / i64::from(self.video_config.frame_rate.numerator().max(1));
522        while let Some(packet) = self.video_track.queued.pop_front() {
523            let packet = Packet {
524                track: video,
525                pts: packet.pts,
526                dts: packet.dts,
527                duration: frame_duration,
528                keyframe: packet.keyframe,
529                data: packet.data,
530                discard: (0, 0),
531            };
532            self.video_written = Some(packet.dts);
533            self.writer()?.write(packet)?;
534        }
535        if let (Some(audio), Some((encoder, _, _))) = (self.audio_track.id, self.audio.as_ref()) {
536            let frame = i64::try_from(encoder.frame_size()).unwrap_or(i64::MAX);
537            // Audio ends where the input does: a packet reaching past the samples written so far
538            // waits, and at the end its duration stops at the last input sample. Encoders pad
539            // their last frames; with the priming taken off, a packet starting at or after the
540            // end decodes to padding alone.
541            let end = self.audio_pts;
542            let rate = encoder.sample_rate();
543            let video_rate = self.video.timescale();
544            while let Some(packet) = self.audio_track.queued.front() {
545                let start = packet.pts - i64::from(priming);
546                if !self.finishing
547                    && (start + frame > end
548                        || !within_lead(start, rate, self.video_written, video_rate))
549                {
550                    break;
551                }
552                let Some(packet) = self.audio_track.queued.pop_front() else {
553                    break;
554                };
555                if start >= end {
556                    continue;
557                }
558                let packet = Packet {
559                    track: audio,
560                    pts: start,
561                    dts: packet.dts - i64::from(priming),
562                    duration: (end - start).clamp(1, frame),
563                    keyframe: true,
564                    data: packet.data,
565                    discard: (0, 0),
566                };
567                self.writer()?.write(packet)?;
568            }
569        }
570        Ok(())
571    }
572
573    fn submit_audio(&mut self, frames: Vec<Vec<Vec<f32>>>) -> Result<(), EncodeError> {
574        for frame in frames {
575            let length = i64::try_from(frame.first().map_or(0, Vec::len)).unwrap_or(0);
576            let mut stall = Stall::new(self.stall_limit);
577            loop {
578                let pts = self.audio_pts;
579                let Some((encoder, _, _)) = self.audio.as_mut() else {
580                    return Ok(());
581                };
582                match encoder.submit(pts, &frame)? {
583                    Submit::Accepted => break,
584                    Submit::Busy => self.wait_busy(&mut stall, false, "audio")?,
585                }
586            }
587            self.audio_pts += length;
588            self.drain(false, false)?;
589        }
590        Ok(())
591    }
592
593    /// Ends both inputs, drains the encoders and closes the output.
594    ///
595    /// # Errors
596    /// As [`Self::write_frame`]; encoders that give no packet for 10 s while draining, or an
597    /// encoder that never published its configuration.
598    pub fn finish(mut self) -> Result<(), EncodeError> {
599        let tail = self
600            .audio
601            .as_mut()
602            .map(|(_, input, _)| input.finish())
603            .unwrap_or_default();
604        self.submit_audio(tail)?;
605        let finished = self.video.finish_input();
606        finished.map_err(|error| self.rejected(error))?;
607        if let Some((encoder, _, _)) = self.audio.as_mut() {
608            encoder.finish_input()?;
609        }
610        let mut done = (false, self.audio.is_none());
611        let mut stall = Stall::new(self.stall_limit);
612        while !(done.0 && done.1) {
613            let received = self.received;
614            let (video, audio) = self.drain(!done.0, !done.1)?;
615            done = (done.0 || video, done.1 || audio);
616            if stall.turn(self.received != received) {
617                let which = match done {
618                    (false, false) => "video and audio encoders",
619                    (false, true) => "video encoder",
620                    _ => "audio encoder",
621                };
622                return Err(EncodeError::Adapter(format!(
623                    "the {which} gave no packet for {} s while draining",
624                    self.stall_limit.as_secs_f64()
625                )));
626            }
627        }
628        self.finishing = true;
629        self.flush_tracks()?;
630        if self.video_track.id.is_none() {
631            let which = if self.video_info().is_none() {
632                "video"
633            } else {
634                "audio"
635            };
636            return Err(EncodeError::Adapter(format!(
637                "the {which} encoder published no configuration"
638            )));
639        }
640        let writer = self
641            .writer
642            .take()
643            .ok_or_else(|| EncodeError::Adapter("the output is already finished".into()))?;
644        writer.finish().map_err(EncodeError::from)
645    }
646}
647
648impl EncodeSink {
649    /// Encodes frame `index` of the export, its planes in the configured layout.
650    ///
651    /// # Errors
652    /// [`EncodeError::EncoderRejected`] for any failure of the video encoder; a writer or audio
653    /// encoder failure as it is; [`EncodeError::Cancelled`] when the token is set while an encoder
654    /// is busy; an encoder that takes no frame and gives no packet for 10 s.
655    pub fn write_frame(&mut self, index: u64, planes: &[PlaneBuffer]) -> Result<(), EncodeError> {
656        let rate = self.video_config.frame_rate;
657        let pts = i64::try_from(index).unwrap_or(i64::MAX)
658            * i64::from(rate.denominator())
659            * i64::from(self.video.timescale())
660            / i64::from(rate.numerator().max(1));
661        let interval = u64::from(self.video_config.keyframe_interval.max(1));
662        let keyframe = index.is_multiple_of(interval);
663        let mut stall = Stall::new(self.stall_limit);
664        loop {
665            let submitted = self.video.submit(pts, planes, keyframe);
666            match submitted.map_err(|error| self.rejected(error))? {
667                Submit::Accepted => break,
668                Submit::Busy => self.wait_busy(&mut stall, true, "video")?,
669            }
670        }
671        self.video_frames += 1;
672        self.drain(false, false).map(|_| ())
673    }
674
675    /// Lets the video encoder finish the frames it holds and takes their packets.
676    ///
677    /// # Errors
678    /// As [`Self::write_frame`].
679    pub fn settle(&mut self) -> Result<(), EncodeError> {
680        let settled = self.video.settle();
681        settled.map_err(|error| self.rejected(error))?;
682        self.drain(false, false).map(|_| ())
683    }
684
685    /// One turn of a wait for the `which` encoder to take a frame: drains the encoders, waiting on
686    /// the video one when `video`.
687    fn wait_busy(
688        &mut self,
689        stall: &mut Stall,
690        video: bool,
691        which: &str,
692    ) -> Result<(), EncodeError> {
693        if self.cancel.is_cancelled() {
694            return Err(EncodeError::Cancelled);
695        }
696        let received = self.received;
697        self.drain(video, !video)?;
698        if stall.turn(self.received != received) {
699            return Err(EncodeError::Adapter(format!(
700                "the {which} encoder accepted no frame for {} s",
701                self.stall_limit.as_secs_f64()
702            )));
703        }
704        Ok(())
705    }
706
707    /// A video encoder failure as one another encoder may not have: anything but a cancel.
708    fn rejected(&self, error: EncodeError) -> EncodeError {
709        match error {
710            EncodeError::Cancelled | EncodeError::EncoderRejected { .. } => error,
711            error => EncodeError::EncoderRejected {
712                encoder: self.video.name().to_owned(),
713                frame: self.video_frames,
714                message: error.to_string(),
715            },
716        }
717    }
718}
719
720#[cfg(feature = "engine")]
721impl crate::export::VideoSink for EncodeSink {
722    fn write_video(
723        &mut self,
724        index: u64,
725        _time: alpha2_time::MediaTime,
726        _layout: PixelLayout,
727        planes: &[PlaneBuffer],
728    ) -> Result<(), EncodeError> {
729        self.write_frame(index, planes)
730    }
731
732    fn settle(&mut self) -> Result<(), EncodeError> {
733        Self::settle(self)
734    }
735}
736
737impl AudioBlockSink for EncodeSink {
738    fn write_audio(&mut self, block: &AudioBlock, cancel: &CancelToken) -> Result<(), EncodeError> {
739        if cancel.is_cancelled() {
740            return Err(EncodeError::Cancelled);
741        }
742        let Some((_, input, _)) = self.audio.as_mut() else {
743            return Ok(());
744        };
745        let frames = input.push(block)?;
746        self.submit_audio(frames)
747    }
748
749    fn finish_audio(&mut self, _cancel: &CancelToken) -> Result<(), EncodeError> {
750        Ok(())
751    }
752
753    fn abort_audio(&mut self) -> Result<(), EncodeError> {
754        Ok(())
755    }
756}
757
758#[cfg(test)]
759#[path = "encode_tests.rs"]
760mod tests;