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    /// The encoder's pool, when it lends buffers the renderer draws frames into instead of
136    /// taking planes. The default lends none.
137    fn lender(&mut self) -> Option<&mut dyn PoolLender> {
138        None
139    }
140}
141
142/// A buffer of an encoder's input pool lent for one frame. Dropping it unsubmitted gives it and
143/// its place among the encoder's frames in flight back.
144pub struct LentBuffer {
145    surface: usize,
146    generation: u64,
147    most_out: usize,
148    owner: Box<dyn std::any::Any + Send>,
149}
150
151impl std::fmt::Debug for LentBuffer {
152    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        formatter
154            .debug_struct("LentBuffer")
155            .field("generation", &self.generation)
156            .finish_non_exhaustive()
157    }
158}
159
160impl LentBuffer {
161    /// A lent `surface` (the platform's buffer, such as a `CVPixelBufferRef`) of pool
162    /// `generation`, out of at most `most_out` the encoder has out at once; `owner` holds the
163    /// buffer and is the lender's to take back.
164    #[must_use]
165    pub fn new(
166        surface: *mut std::ffi::c_void,
167        generation: u64,
168        most_out: usize,
169        owner: Box<dyn std::any::Any + Send>,
170    ) -> Self {
171        Self {
172            surface: surface.addr(),
173            generation,
174            most_out,
175            owner,
176        }
177    }
178
179    /// The platform's buffer, valid while this lives.
180    #[must_use]
181    pub fn surface(&self) -> *mut std::ffi::c_void {
182        std::ptr::without_provenance_mut(self.surface)
183    }
184
185    /// The pool it came from: a replaced encoder session has a new pool and a new generation.
186    #[must_use]
187    pub const fn generation(&self) -> u64 {
188        self.generation
189    }
190
191    /// The most buffers the encoder has out at once, lent or encoding.
192    #[must_use]
193    pub const fn most_out(&self) -> usize {
194        self.most_out
195    }
196
197    /// What holds the buffer, for the lender that made it.
198    #[must_use]
199    pub fn into_owner(self) -> Box<dyn std::any::Any + Send> {
200        self.owner
201    }
202}
203
204/// What a lend gave.
205#[derive(Debug)]
206pub enum Lend {
207    /// A buffer for the next frame.
208    Buffer(LentBuffer),
209    /// The encoder holds as many frames as it may; take its packets and ask again.
210    Busy,
211}
212
213/// An encoder's input pool lending buffers to render into.
214pub trait PoolLender {
215    /// A buffer for the next frame. A lent buffer counts as in flight from here, so
216    /// [`Self::encode_lent`] never waits.
217    ///
218    /// # Errors
219    /// A failed encoder.
220    fn lend(&mut self) -> Result<Lend, EncodeError>;
221
222    /// Encodes the frame drawn into `buffer`, at `pts`.
223    ///
224    /// # Errors
225    /// A buffer this pool did not lend, or a failed encoder.
226    fn encode_lent(
227        &mut self,
228        pts: i64,
229        buffer: LentBuffer,
230        keyframe: bool,
231    ) -> Result<(), EncodeError>;
232}
233
234/// Opens video encoder sessions.
235pub trait VideoEncoders: Send + Sync {
236    /// A session for `config`.
237    ///
238    /// # Errors
239    /// [`EncodeError::EncodersRefused`] naming every encoder tried.
240    fn open(&self, config: &VideoEncodeConfig) -> Result<Box<dyn VideoEncodeBackend>, EncodeError>;
241}
242
243/// What an audio encoder is asked for.
244#[derive(Clone, Copy, Debug, PartialEq)]
245pub struct AudioEncodeConfig {
246    /// The codec.
247    pub codec: alpha2_media::AudioCodec,
248    /// The project's sample rate, which the audio arrives at.
249    pub project_rate: u32,
250    /// The speakers, one plane each.
251    pub speakers: SpeakerLayout,
252    /// Bits per second.
253    pub bitrate: u32,
254}
255
256/// One audio encoder session, used from one thread at a time.
257pub trait AudioEncodeBackend: Send {
258    /// The encoder's name, for reports.
259    fn name(&self) -> &str;
260
261    /// The rate it encodes at.
262    fn sample_rate(&self) -> u32;
263
264    /// Samples per channel in each frame it takes.
265    fn frame_size(&self) -> usize;
266
267    /// The bits per second it encodes at: the configured rate, or the nearest the encoder takes.
268    fn bitrate(&self) -> u32;
269
270    /// Queues one frame of planar samples starting at sample `pts` of the encoded stream; only
271    /// the last frame may be short.
272    ///
273    /// # Errors
274    /// A failed encoder.
275    fn submit(&mut self, pts: i64, planes: &[Vec<f32>]) -> Result<Submit, EncodeError>;
276
277    /// Takes an encoded packet, timestamps in samples at [`Self::sample_rate`] counted from the
278    /// first decoded sample, priming included. Once it answers [`EncodePoll::Drained`] it keeps
279    /// answering it.
280    ///
281    /// # Errors
282    /// A failed encoder.
283    fn receive(&mut self, wait: bool) -> Result<EncodePoll, EncodeError>;
284
285    /// No more frames follow.
286    ///
287    /// # Errors
288    /// A failed encoder.
289    fn finish_input(&mut self) -> Result<(), EncodeError>;
290
291    /// The codec's setup data (`AudioSpecificConfig`, `OpusHead`), once known.
292    fn codec_private(&self) -> Option<Bytes>;
293
294    /// Samples of priming at the start of the decoded stream, which the container's edit list
295    /// skips.
296    fn priming(&self) -> u32;
297}
298
299/// Opens audio encoder sessions.
300pub trait AudioEncoders: Send + Sync {
301    /// A session for `config`.
302    ///
303    /// # Errors
304    /// [`EncodeError::EncodersRefused`] naming every encoder tried.
305    fn open(&self, config: &AudioEncodeConfig) -> Result<Box<dyn AudioEncodeBackend>, EncodeError>;
306}
307
308/// How long encoders may take no frame and hand out no packet before the sink gives up on them.
309pub(crate) const DRAIN_STALL: Duration = Duration::from_secs(10);
310
311/// The most one turn of a wait adds to a stall, so a process frozen inside a wait adds no more.
312const STALL_TURN: Duration = Duration::from_millis(100);
313
314/// The time a wait on the encoders has made no progress, added up turn by turn.
315pub(crate) struct Stall {
316    last: Instant,
317    stalled: Duration,
318    limit: Duration,
319}
320
321impl Stall {
322    pub(crate) fn new(limit: Duration) -> Self {
323        Self {
324            last: Instant::now(),
325            stalled: Duration::ZERO,
326            limit,
327        }
328    }
329
330    /// Records one turn of the wait; true once the turns without progress reach the limit.
331    pub(crate) fn turn(&mut self, progressed: bool) -> bool {
332        let now = Instant::now();
333        let spent = now.saturating_duration_since(self.last).min(STALL_TURN);
334        self.last = now;
335        self.stalled = if progressed {
336            Duration::ZERO
337        } else {
338            self.stalled + spent
339        };
340        self.stalled >= self.limit
341    }
342}
343
344/// The container codec of `codec` encoded in `layout`: `ProRes` is 4444 (`ap4h`) with alpha, else
345/// 422 HQ (`apch`), as [`crate::codecs::NativeVideoCodec::ProRes`] encodes it.
346fn container_video_codec(codec: alpha2_media::VideoCodec, layout: PixelLayout) -> VideoCodec {
347    match codec {
348        alpha2_media::VideoCodec::H264 => VideoCodec::H264,
349        alpha2_media::VideoCodec::Hevc => VideoCodec::Hevc,
350        alpha2_media::VideoCodec::Vp9 => VideoCodec::Vp9,
351        alpha2_media::VideoCodec::Av1 => VideoCodec::Av1,
352        alpha2_media::VideoCodec::Mpeg4Part2 => VideoCodec::Mpeg4Part2,
353        alpha2_media::VideoCodec::ProRes => {
354            VideoCodec::ProRes(alpha2_container::FourCc(if layout.alpha {
355                *b"ap4h"
356            } else {
357                *b"apch"
358            }))
359        }
360    }
361}
362
363pub(crate) fn container_audio_codec(codec: alpha2_media::AudioCodec) -> AudioCodec {
364    match codec {
365        alpha2_media::AudioCodec::Aac => AudioCodec::Aac,
366        alpha2_media::AudioCodec::Opus => AudioCodec::Opus,
367    }
368}
369
370/// A track waiting for its encoder's configuration record before it is added.
371struct PendingTrack {
372    id: Option<TrackId>,
373    queued: VecDeque<EncodedPacket>,
374}
375
376impl PendingTrack {
377    const fn new() -> Self {
378        Self {
379            id: None,
380            queued: VecDeque::new(),
381        }
382    }
383}
384
385/// How far audio written to the container may run ahead of the video written, in seconds.
386const AUDIO_LEAD: i64 = 1;
387
388/// Whether audio starting at `start` (in units of `rate` per second) is at most [`AUDIO_LEAD`]
389/// past the video packet decoded at `video` (in units of `video_rate`); never before any video.
390fn within_lead(start: i64, rate: u32, video: Option<i64>, video_rate: u32) -> bool {
391    video.is_some_and(|video| {
392        let limit = (i128::from(video) + i128::from(AUDIO_LEAD) * i128::from(video_rate))
393            * i128::from(rate);
394        i128::from(start) * i128::from(video_rate) <= limit
395    })
396}
397
398/// Turns an export's pictures and mixed audio into a container's tracks.
399///
400/// Tracks are added once every encoder has published its configuration record; packets before
401/// that wait. Audio goes to the writer at most one second ahead of the video written, so a mix
402/// encoded before the pictures still reaches the writer interleaved with them.
403pub struct EncodeSink {
404    writer: Option<Box<dyn ContainerWriter>>,
405    video: Box<dyn VideoEncodeBackend>,
406    video_config: VideoEncodeConfig,
407    video_track: PendingTrack,
408    audio: Option<(
409        Box<dyn AudioEncodeBackend>,
410        EncoderAudioInput,
411        AudioEncodeConfig,
412    )>,
413    audio_track: PendingTrack,
414    /// Samples handed to the audio encoder, at its rate.
415    audio_pts: i64,
416    /// The decode time of the last video packet written, in the video encoder's units.
417    video_written: Option<i64>,
418    /// Packets taken from both encoders.
419    received: u64,
420    /// Every input is in: held audio packets go out.
421    finishing: bool,
422    /// Stops the waits on a busy encoder.
423    cancel: CancelToken,
424    /// How long the encoders may make no progress before a wait on them fails.
425    stall_limit: Duration,
426    /// Frames the video encoder accepted.
427    video_frames: u64,
428}
429
430impl std::fmt::Debug for EncodeSink {
431    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
432        formatter
433            .debug_struct("EncodeSink")
434            .field("video", &self.video.name())
435            .finish_non_exhaustive()
436    }
437}
438
439impl EncodeSink {
440    /// A sink writing `video` (and `audio`, when the export has sound) into `writer`; `cancel`
441    /// stops its waits on a busy encoder.
442    #[must_use]
443    pub fn new(
444        writer: Box<dyn ContainerWriter>,
445        video: Box<dyn VideoEncodeBackend>,
446        video_config: VideoEncodeConfig,
447        audio: Option<(Box<dyn AudioEncodeBackend>, AudioEncodeConfig)>,
448        cancel: CancelToken,
449    ) -> Self {
450        let audio = audio.map(|(encoder, config)| {
451            let input = EncoderAudioInput::new(
452                config.project_rate,
453                encoder.sample_rate(),
454                config.speakers.speakers().len(),
455                encoder.frame_size(),
456            );
457            (encoder, input, config)
458        });
459        Self {
460            writer: Some(writer),
461            video,
462            video_config,
463            video_track: PendingTrack::new(),
464            audio,
465            audio_track: PendingTrack::new(),
466            audio_pts: 0,
467            video_written: None,
468            received: 0,
469            finishing: false,
470            cancel,
471            stall_limit: DRAIN_STALL,
472            video_frames: 0,
473        }
474    }
475
476    #[cfg(test)]
477    fn with_stall_limit(mut self, limit: Duration) -> Self {
478        self.stall_limit = limit;
479        self
480    }
481
482    /// The video encoder's name and the rate control it ran.
483    #[must_use]
484    pub fn video_encoder(&self) -> (&str, bool, AppliedRateControl) {
485        (
486            self.video.name(),
487            self.video.hardware(),
488            self.video.applied_rate_control(),
489        )
490    }
491
492    fn writer(&mut self) -> Result<&mut Box<dyn ContainerWriter>, EncodeError> {
493        self.writer
494            .as_mut()
495            .ok_or_else(|| EncodeError::Adapter("the output is already finished".into()))
496    }
497
498    fn video_info(&self) -> Option<TrackInfo> {
499        let private = self.video.codec_private()?;
500        let config = &self.video_config;
501        Some(TrackInfo {
502            id: TrackId(0),
503            kind: TrackKind::Video,
504            timescale: self.video.timescale(),
505            duration: None,
506            language: None,
507            title: None,
508            default: true,
509            enabled: true,
510            video: Some(VideoTrack {
511                codec: container_video_codec(config.codec, config.layout),
512                codec_private: private,
513                in_band_parameter_sets: false,
514                width: config.width,
515                height: config.height,
516                orientation: Orientation::default(),
517                sample_aspect_ratio: None,
518                color: Some(config.color),
519                clean_aperture: None,
520                frame_rate: Some(config.frame_rate),
521                alpha: config.layout.alpha,
522                reorder_depth: None,
523            }),
524            audio: None,
525        })
526    }
527
528    fn audio_info(&self) -> Option<TrackInfo> {
529        let (encoder, _, config) = self.audio.as_ref()?;
530        let private = encoder.codec_private()?;
531        Some(TrackInfo {
532            id: TrackId(0),
533            kind: TrackKind::Audio,
534            timescale: encoder.sample_rate(),
535            duration: None,
536            language: None,
537            title: None,
538            default: true,
539            enabled: true,
540            video: None,
541            audio: Some(AudioTrack {
542                codec: container_audio_codec(config.codec),
543                codec_private: private,
544                sample_rate: encoder.sample_rate(),
545                channels: u32::try_from(config.speakers.channels()).unwrap_or(u32::MAX),
546                speakers: Some(config.speakers),
547                bits_per_sample: None,
548                priming: encoder.priming(),
549                seek_preroll: None,
550            }),
551        })
552    }
553
554    /// Moves packets the encoders have into their tracks.
555    fn drain(&mut self, wait_video: bool, wait_audio: bool) -> Result<(bool, bool), EncodeError> {
556        let mut video_done = false;
557        loop {
558            let received = self.video.receive(wait_video);
559            match received.map_err(|error| self.rejected(error))? {
560                EncodePoll::Packet(packet) => {
561                    self.received += 1;
562                    self.video_track.queued.push_back(packet);
563                }
564                EncodePoll::Pending => break,
565                EncodePoll::Drained => {
566                    video_done = true;
567                    break;
568                }
569            }
570        }
571        let mut audio_done = self.audio.is_none();
572        if let Some((encoder, _, _)) = self.audio.as_mut() {
573            loop {
574                match encoder.receive(wait_audio)? {
575                    EncodePoll::Packet(packet) => {
576                        self.received += 1;
577                        self.audio_track.queued.push_back(packet);
578                    }
579                    EncodePoll::Pending => break,
580                    EncodePoll::Drained => {
581                        audio_done = true;
582                        break;
583                    }
584                }
585            }
586        }
587        self.flush_tracks()?;
588        Ok((video_done, audio_done))
589    }
590
591    /// Adds tracks whose configuration is known and writes their queued packets.
592    fn flush_tracks(&mut self) -> Result<(), EncodeError> {
593        // Containers add every track before the first packet; video is always the first track.
594        if self.video_track.id.is_none() {
595            let Some(video) = self.video_info() else {
596                return Ok(());
597            };
598            let audio = match self.audio {
599                Some(_) => match self.audio_info() {
600                    Some(info) => Some(info),
601                    None => return Ok(()),
602                },
603                None => None,
604            };
605            self.video_track.id = Some(self.writer()?.add_track(&video)?);
606            if let Some(info) = audio {
607                self.audio_track.id = Some(self.writer()?.add_track(&info)?);
608            }
609        }
610        let Some(video) = self.video_track.id else {
611            return Ok(());
612        };
613        let priming = self
614            .audio
615            .as_ref()
616            .map_or(0, |(encoder, _, _)| encoder.priming());
617        let frame_duration = i64::from(self.video_config.frame_rate.denominator())
618            * i64::from(self.video.timescale())
619            / i64::from(self.video_config.frame_rate.numerator().max(1));
620        while let Some(packet) = self.video_track.queued.pop_front() {
621            let packet = Packet {
622                track: video,
623                pts: packet.pts,
624                dts: packet.dts,
625                duration: frame_duration,
626                keyframe: packet.keyframe,
627                data: packet.data,
628                discard: (0, 0),
629            };
630            self.video_written = Some(packet.dts);
631            self.writer()?.write(packet)?;
632        }
633        if let (Some(audio), Some((encoder, _, _))) = (self.audio_track.id, self.audio.as_ref()) {
634            let frame = i64::try_from(encoder.frame_size()).unwrap_or(i64::MAX);
635            // Audio ends where the input does: a packet reaching past the samples written so far
636            // waits, and at the end its duration stops at the last input sample. Encoders pad
637            // their last frames; with the priming taken off, a packet starting at or after the
638            // end decodes to padding alone.
639            let end = self.audio_pts;
640            let rate = encoder.sample_rate();
641            let video_rate = self.video.timescale();
642            while let Some(packet) = self.audio_track.queued.front() {
643                let start = packet.pts - i64::from(priming);
644                if !self.finishing
645                    && (start + frame > end
646                        || !within_lead(start, rate, self.video_written, video_rate))
647                {
648                    break;
649                }
650                let Some(packet) = self.audio_track.queued.pop_front() else {
651                    break;
652                };
653                if start >= end {
654                    continue;
655                }
656                let packet = Packet {
657                    track: audio,
658                    pts: start,
659                    dts: packet.dts - i64::from(priming),
660                    duration: (end - start).clamp(1, frame),
661                    keyframe: true,
662                    data: packet.data,
663                    discard: (0, 0),
664                };
665                self.writer()?.write(packet)?;
666            }
667        }
668        Ok(())
669    }
670
671    fn submit_audio(&mut self, frames: Vec<Vec<Vec<f32>>>) -> Result<(), EncodeError> {
672        for frame in frames {
673            let length = i64::try_from(frame.first().map_or(0, Vec::len)).unwrap_or(0);
674            let mut stall = Stall::new(self.stall_limit);
675            loop {
676                let pts = self.audio_pts;
677                let Some((encoder, _, _)) = self.audio.as_mut() else {
678                    return Ok(());
679                };
680                match encoder.submit(pts, &frame)? {
681                    Submit::Accepted => break,
682                    Submit::Busy => self.wait_busy(&mut stall, false, "audio")?,
683                }
684            }
685            self.audio_pts += length;
686            self.drain(false, false)?;
687        }
688        Ok(())
689    }
690
691    /// Ends both inputs, drains the encoders and closes the output.
692    ///
693    /// # Errors
694    /// As [`Self::write_frame`]; encoders that give no packet for 10 s while draining, or an
695    /// encoder that never published its configuration.
696    pub fn finish(mut self) -> Result<(), EncodeError> {
697        let tail = self
698            .audio
699            .as_mut()
700            .map(|(_, input, _)| input.finish())
701            .unwrap_or_default();
702        self.submit_audio(tail)?;
703        let finished = self.video.finish_input();
704        finished.map_err(|error| self.rejected(error))?;
705        if let Some((encoder, _, _)) = self.audio.as_mut() {
706            encoder.finish_input()?;
707        }
708        let mut done = (false, self.audio.is_none());
709        let mut stall = Stall::new(self.stall_limit);
710        while !(done.0 && done.1) {
711            let received = self.received;
712            let (video, audio) = self.drain(!done.0, !done.1)?;
713            done = (done.0 || video, done.1 || audio);
714            if stall.turn(self.received != received) {
715                let which = match done {
716                    (false, false) => "video and audio encoders",
717                    (false, true) => "video encoder",
718                    _ => "audio encoder",
719                };
720                return Err(EncodeError::Adapter(format!(
721                    "the {which} gave no packet for {} s while draining",
722                    self.stall_limit.as_secs_f64()
723                )));
724            }
725        }
726        self.finishing = true;
727        self.flush_tracks()?;
728        if self.video_track.id.is_none() {
729            let which = if self.video_info().is_none() {
730                "video"
731            } else {
732                "audio"
733            };
734            return Err(EncodeError::Adapter(format!(
735                "the {which} encoder published no configuration"
736            )));
737        }
738        let writer = self
739            .writer
740            .take()
741            .ok_or_else(|| EncodeError::Adapter("the output is already finished".into()))?;
742        writer.finish().map_err(EncodeError::from)
743    }
744}
745
746impl EncodeSink {
747    /// Encodes frame `index` of the export, its planes in the configured layout.
748    ///
749    /// # Errors
750    /// [`EncodeError::EncoderRejected`] for any failure of the video encoder; a writer or audio
751    /// encoder failure as it is; [`EncodeError::Cancelled`] when the token is set while an encoder
752    /// is busy; an encoder that takes no frame and gives no packet for 10 s.
753    pub fn write_frame(&mut self, index: u64, planes: &[PlaneBuffer]) -> Result<(), EncodeError> {
754        let (pts, keyframe) = self.frame_timing(index);
755        let mut stall = Stall::new(self.stall_limit);
756        loop {
757            let submitted = self.video.submit(pts, planes, keyframe);
758            match submitted.map_err(|error| self.rejected(error))? {
759                Submit::Accepted => break,
760                Submit::Busy => self.wait_busy(&mut stall, true, "video")?,
761            }
762        }
763        self.video_frames += 1;
764        self.drain(false, false).map(|_| ())
765    }
766
767    fn frame_timing(&self, index: u64) -> (i64, bool) {
768        let rate = self.video_config.frame_rate;
769        let pts = i64::try_from(index).unwrap_or(i64::MAX)
770            * i64::from(rate.denominator())
771            * i64::from(self.video.timescale())
772            / i64::from(rate.numerator().max(1));
773        let interval = u64::from(self.video_config.keyframe_interval.max(1));
774        (pts, index.is_multiple_of(interval))
775    }
776
777    /// A buffer of the video encoder's pool for the next frame, waiting while the encoder is
778    /// busy as [`Self::write_frame`] does.
779    ///
780    /// # Errors
781    /// As [`Self::write_frame`], and [`EncodeError::Adapter`] when the encoder lends no buffers.
782    pub fn lend(&mut self) -> Result<LentBuffer, EncodeError> {
783        let mut stall = Stall::new(self.stall_limit);
784        loop {
785            let lent = self
786                .video
787                .lender()
788                .ok_or_else(|| EncodeError::Adapter("the video encoder lends no buffers".into()))?
789                .lend();
790            match lent.map_err(|error| self.rejected(error))? {
791                Lend::Buffer(buffer) => return Ok(buffer),
792                Lend::Busy => self.wait_busy(&mut stall, true, "video")?,
793            }
794        }
795    }
796
797    /// Encodes frame `index` of the export, drawn into `buffer`, which [`Self::lend`] gave.
798    ///
799    /// # Errors
800    /// As [`Self::write_frame`].
801    pub fn write_lent(&mut self, index: u64, buffer: LentBuffer) -> Result<(), EncodeError> {
802        let (pts, keyframe) = self.frame_timing(index);
803        let encoded = self
804            .video
805            .lender()
806            .ok_or_else(|| EncodeError::Adapter("the video encoder lends no buffers".into()))?
807            .encode_lent(pts, buffer, keyframe);
808        encoded.map_err(|error| self.rejected(error))?;
809        self.video_frames += 1;
810        self.drain(false, false).map(|_| ())
811    }
812
813    /// Lets the video encoder finish the frames it holds and takes their packets.
814    ///
815    /// # Errors
816    /// As [`Self::write_frame`].
817    pub fn settle(&mut self) -> Result<(), EncodeError> {
818        let settled = self.video.settle();
819        settled.map_err(|error| self.rejected(error))?;
820        self.drain(false, false).map(|_| ())
821    }
822
823    /// One turn of a wait for the `which` encoder to take a frame: drains the encoders, waiting on
824    /// the video one when `video`.
825    fn wait_busy(
826        &mut self,
827        stall: &mut Stall,
828        video: bool,
829        which: &str,
830    ) -> Result<(), EncodeError> {
831        if self.cancel.is_cancelled() {
832            return Err(EncodeError::Cancelled);
833        }
834        let received = self.received;
835        self.drain(video, !video)?;
836        if stall.turn(self.received != received) {
837            return Err(EncodeError::Adapter(format!(
838                "the {which} encoder accepted no frame for {} s",
839                self.stall_limit.as_secs_f64()
840            )));
841        }
842        Ok(())
843    }
844
845    /// A video encoder failure as one another encoder may not have: anything but a cancel.
846    fn rejected(&self, error: EncodeError) -> EncodeError {
847        match error {
848            EncodeError::Cancelled | EncodeError::EncoderRejected { .. } => error,
849            error => EncodeError::EncoderRejected {
850                encoder: self.video.name().to_owned(),
851                frame: self.video_frames,
852                message: error.to_string(),
853            },
854        }
855    }
856}
857
858#[cfg(feature = "engine")]
859impl crate::export::VideoSink for EncodeSink {
860    fn write_video(
861        &mut self,
862        index: u64,
863        _time: alpha2_time::MediaTime,
864        _layout: PixelLayout,
865        planes: &[PlaneBuffer],
866    ) -> Result<(), EncodeError> {
867        self.write_frame(index, planes)
868    }
869
870    fn settle(&mut self) -> Result<(), EncodeError> {
871        Self::settle(self)
872    }
873
874    fn lender(&mut self) -> Option<&mut dyn crate::export::SinkLender> {
875        if self.video.lender().is_some() {
876            Some(self)
877        } else {
878            None
879        }
880    }
881}
882
883#[cfg(feature = "engine")]
884impl crate::export::SinkLender for EncodeSink {
885    fn lend(&mut self) -> Result<LentBuffer, EncodeError> {
886        Self::lend(self)
887    }
888
889    fn write_lent(
890        &mut self,
891        index: u64,
892        _time: alpha2_time::MediaTime,
893        buffer: LentBuffer,
894    ) -> Result<(), EncodeError> {
895        Self::write_lent(self, index, buffer)
896    }
897}
898
899impl AudioBlockSink for EncodeSink {
900    fn write_audio(&mut self, block: &AudioBlock, cancel: &CancelToken) -> Result<(), EncodeError> {
901        if cancel.is_cancelled() {
902            return Err(EncodeError::Cancelled);
903        }
904        let Some((_, input, _)) = self.audio.as_mut() else {
905            return Ok(());
906        };
907        let frames = input.push(block)?;
908        self.submit_audio(frames)
909    }
910
911    fn finish_audio(&mut self, _cancel: &CancelToken) -> Result<(), EncodeError> {
912        Ok(())
913    }
914
915    fn abort_audio(&mut self) -> Result<(), EncodeError> {
916        Ok(())
917    }
918}
919
920#[cfg(test)]
921#[path = "encode_tests.rs"]
922mod tests;