1use 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#[derive(Clone, Debug, Default)]
24pub struct PlaneBuffer {
25 pub bytes: Vec<u8>,
27 pub stride: usize,
29 pub width: u32,
31 pub height: u32,
33}
34
35#[derive(Clone, Copy, Debug, PartialEq)]
37pub struct VideoEncodeConfig {
38 pub codec: alpha2_media::VideoCodec,
40 pub width: u32,
42 pub height: u32,
44 pub frame_rate: FrameRate,
46 pub layout: PixelLayout,
48 pub rate: VideoRateControl,
50 pub color: ColorMetadata,
52 pub keyframe_interval: u32,
54 pub software: bool,
56}
57
58#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct EncodedPacket {
61 pub pts: i64,
63 pub dts: i64,
65 pub keyframe: bool,
67 pub data: Bytes,
69}
70
71#[derive(Debug)]
73pub enum EncodePoll {
74 Packet(EncodedPacket),
76 Pending,
78 Drained,
80}
81
82pub trait VideoEncodeBackend: Send {
87 fn name(&self) -> &str;
89
90 fn hardware(&self) -> bool;
92
93 fn timescale(&self) -> u32;
95
96 fn submit(
101 &mut self,
102 pts: i64,
103 planes: &[PlaneBuffer],
104 keyframe: bool,
105 ) -> Result<Submit, EncodeError>;
106
107 fn receive(&mut self, wait: bool) -> Result<EncodePoll, EncodeError>;
113
114 fn settle(&mut self) -> Result<(), EncodeError> {
120 Ok(())
121 }
122
123 fn finish_input(&mut self) -> Result<(), EncodeError>;
128
129 fn codec_private(&self) -> Option<Bytes>;
131
132 fn applied_rate_control(&self) -> AppliedRateControl;
134
135 fn lender(&mut self) -> Option<&mut dyn PoolLender> {
138 None
139 }
140}
141
142pub 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 #[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 #[must_use]
181 pub fn surface(&self) -> *mut std::ffi::c_void {
182 std::ptr::without_provenance_mut(self.surface)
183 }
184
185 #[must_use]
187 pub const fn generation(&self) -> u64 {
188 self.generation
189 }
190
191 #[must_use]
193 pub const fn most_out(&self) -> usize {
194 self.most_out
195 }
196
197 #[must_use]
199 pub fn into_owner(self) -> Box<dyn std::any::Any + Send> {
200 self.owner
201 }
202}
203
204#[derive(Debug)]
206pub enum Lend {
207 Buffer(LentBuffer),
209 Busy,
211}
212
213pub trait PoolLender {
215 fn lend(&mut self) -> Result<Lend, EncodeError>;
221
222 fn encode_lent(
227 &mut self,
228 pts: i64,
229 buffer: LentBuffer,
230 keyframe: bool,
231 ) -> Result<(), EncodeError>;
232}
233
234pub trait VideoEncoders: Send + Sync {
236 fn open(&self, config: &VideoEncodeConfig) -> Result<Box<dyn VideoEncodeBackend>, EncodeError>;
241}
242
243#[derive(Clone, Copy, Debug, PartialEq)]
245pub struct AudioEncodeConfig {
246 pub codec: alpha2_media::AudioCodec,
248 pub project_rate: u32,
250 pub speakers: SpeakerLayout,
252 pub bitrate: u32,
254}
255
256pub trait AudioEncodeBackend: Send {
258 fn name(&self) -> &str;
260
261 fn sample_rate(&self) -> u32;
263
264 fn frame_size(&self) -> usize;
266
267 fn bitrate(&self) -> u32;
269
270 fn submit(&mut self, pts: i64, planes: &[Vec<f32>]) -> Result<Submit, EncodeError>;
276
277 fn receive(&mut self, wait: bool) -> Result<EncodePoll, EncodeError>;
284
285 fn finish_input(&mut self) -> Result<(), EncodeError>;
290
291 fn codec_private(&self) -> Option<Bytes>;
293
294 fn priming(&self) -> u32;
297}
298
299pub trait AudioEncoders: Send + Sync {
301 fn open(&self, config: &AudioEncodeConfig) -> Result<Box<dyn AudioEncodeBackend>, EncodeError>;
306}
307
308pub(crate) const DRAIN_STALL: Duration = Duration::from_secs(10);
310
311const STALL_TURN: Duration = Duration::from_millis(100);
313
314pub(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 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
344fn 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
370struct 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
385const AUDIO_LEAD: i64 = 1;
387
388fn 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
398pub 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 audio_pts: i64,
416 video_written: Option<i64>,
418 received: u64,
420 finishing: bool,
422 cancel: CancelToken,
424 stall_limit: Duration,
426 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 #[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 #[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 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 fn flush_tracks(&mut self) -> Result<(), EncodeError> {
593 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 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 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 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 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 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 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 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 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;