1use alpha2_host_core::remote::SourceLocation;
4use std::collections::VecDeque;
5use std::ffi::{CStr, CString};
6use std::io::Read;
7use std::time::{Duration, Instant};
8
9use crate::recovery::{
10 DecodeDiagnostics, DecodePolicy, FfmpegRecovery, Recovery, WorkBudget,
11 audio_timestamp_in_range, submit_packet,
12};
13use alpha2_host_core::audio_timeline::SourceTimeline;
14use alpha2_host_core::{probe_still, still_format};
15
16use crate::convert::{
17 adapter_error, check_frame_size, codec_thread_budget, color_metadata, convert_video_frame,
18 declared_sar, frame_color_metadata, guess_sar, orientation_from_display,
19 reject_unused_decode_options, stream_rotation, tick_base, timestamp, video_decoder_options,
20};
21#[cfg(all(
22 any(target_os = "linux", target_os = "macos", target_os = "windows"),
23 feature = "hwdecode"
24))]
25use crate::video_frame::{HardwareDecoderSpec, HardwareOpenError};
26use alpha2_ffmpeg_bridge::{
27 CustomInput, DecodedFrame, DemuxInput, InputLocation, InputReader, OpenInputError,
28};
29use alpha2_media::{
30 AudioBlock, CancelToken, ColorMetadata, DecodeError, DecodeEvent, DecodeRequest, DecodeResult,
31 DecodedVideoFrame, Decoder, MAX_AUDIO_CHANNELS, Orientation, SampleAspectRatio, SourceAlpha,
32 Speaker, SpeakerLayout, StreamInfo, StreamKind,
33};
34use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND};
35use rsmpeg::avcodec::{AVCodec, AVCodecContext, AVCodecRef, AVPacket};
36#[cfg(all(
37 any(target_os = "linux", target_os = "macos", target_os = "windows"),
38 feature = "hwdecode"
39))]
40use rsmpeg::avutil::AVHWDeviceContext;
41use rsmpeg::avutil::{AVChannelLayout, AVFrame, AVRational, av_rescale_q, av_rescale_q_rnd, ra};
42use rsmpeg::error::RsmpegError;
43use rsmpeg::ffi;
44use rsmpeg::swresample::SwrContext;
45
46#[derive(Clone, Debug, PartialEq)]
48pub struct ProbeResult {
49 pub format: String,
51 pub duration: Option<MediaTime>,
54 pub start: Option<MediaTime>,
57 pub streams: Vec<StreamInfo>,
60 pub selected_video: Option<usize>,
63 pub selected_audio: Option<usize>,
65}
66
67impl ProbeResult {
68 #[must_use]
70 pub fn stream(&self, index: usize) -> Option<&StreamInfo> {
71 self.streams.iter().find(|stream| stream.index == index)
72 }
73
74 #[must_use]
76 pub fn selected_video_stream(&self) -> Option<&StreamInfo> {
77 self.selected_video.and_then(|index| self.stream(index))
78 }
79
80 #[must_use]
82 pub fn selected_audio_stream(&self) -> Option<&StreamInfo> {
83 self.selected_audio.and_then(|index| self.stream(index))
84 }
85
86 pub fn audio_streams(&self) -> impl Iterator<Item = &StreamInfo> {
88 self.streams
89 .iter()
90 .filter(|stream| stream.kind == StreamKind::Audio)
91 }
92
93 #[must_use]
95 pub fn audio_stream(&self, ordinal: u32) -> Option<&StreamInfo> {
96 self.audio_streams().nth(usize::try_from(ordinal).ok()?)
97 }
98
99 #[must_use]
101 pub fn selected_audio_ordinal(&self) -> Option<u32> {
102 let selected = self.selected_audio?;
103 let position = self
104 .audio_streams()
105 .position(|stream| stream.index == selected)?;
106 u32::try_from(position).ok()
107 }
108}
109
110pub fn probe(source: impl Into<SourceLocation>) -> Result<ProbeResult, DecodeError> {
115 let source = source.into();
116 let input = open_input(&source)?;
117 probe_context(&input, &source)
118}
119
120pub fn visit_packet_times(
126 source: impl Into<SourceLocation>,
127 stream: usize,
128 mut visit: impl FnMut(f64) -> bool,
129) -> Result<(), DecodeError> {
130 let mut input = open_input(&source.into())?;
131 let time_base = input
132 .streams()
133 .get(stream)
134 .map(|found| found.time_base)
135 .ok_or_else(|| DecodeError::Unsupported(format!("the file has no stream {stream}")))?;
136 input.discard_all_but(stream);
137 while let Some(packet) = input
138 .read_packet()
139 .map_err(|error| demux_error(&input, error))?
140 {
141 if usize::try_from(packet.stream_index).ok() != Some(stream) {
142 continue;
143 }
144 let time = [packet.pts, packet.dts]
145 .into_iter()
146 .find(|time| *time != ffi::AV_NOPTS_VALUE);
147 let Some(time) = time else { continue };
148 #[allow(clippy::cast_precision_loss)] let seconds = time as f64 * f64::from(time_base.num) / f64::from(time_base.den);
150 if !visit(seconds) {
151 break;
152 }
153 }
154 Ok(())
155}
156
157pub struct NativeDecoder {
159 pub(crate) input: DemuxInput,
160 pub(crate) streams: Vec<StreamInfo>,
161 pub(crate) container_duration: Option<MediaTime>,
162 pub(crate) video_index: usize,
163 pub(crate) time_base: AVRational,
164 pub(crate) decoder: AVCodecContext,
165 pub(crate) orientation: Orientation,
166 pub(crate) sample_aspect_ratio: SampleAspectRatio,
168 pub(crate) color: Option<ColorMetadata>,
170 pub(crate) declared_color: Option<ColorMetadata>,
172 pub(crate) video_scaler: crate::convert::FrameScaler,
173 pub(crate) pending: VecDeque<DecodedFrame>,
174 pub(crate) demux_eof: bool,
175 pub(crate) decoder_flushed: bool,
176 pub(crate) stages: DecodeStageTimings,
177 first_video_pts: Option<MediaTime>,
179 recovery: Recovery,
180 slack: MediaTime,
183 prefetched: Prefetched,
185 dropped_layer: Option<DroppedLayer>,
187}
188
189#[derive(Clone, Debug, Eq, PartialEq)]
191pub struct DroppedLayer {
192 pub code: &'static str,
194 pub reason: String,
196}
197
198#[cfg(test)]
199thread_local! {
200 pub(crate) static READ_DELAY: std::cell::Cell<std::time::Duration> =
203 const { std::cell::Cell::new(std::time::Duration::ZERO) };
204 pub(crate) static WITHOUT_LIBVPX_VP9: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
206}
207
208#[cfg(test)]
210fn take_read_delay() {
211 let delay = READ_DELAY.with(|cell| cell.replace(std::time::Duration::ZERO));
212 if delay.is_zero() {
213 return;
214 }
215 match crate::recovery::VIRTUAL_CLOCK.with(std::cell::Cell::get) {
216 Some(now) => {
217 crate::recovery::VIRTUAL_CLOCK.with(|clock| clock.set(Some(now.saturating_add(delay))));
218 }
219 None => std::thread::sleep(delay),
220 }
221}
222
223type Prefetched = VecDeque<Result<Option<AVPacket>, RsmpegError>>;
225
226fn read_first_packets(input: &mut DemuxInput, index: usize) -> (Prefetched, Vec<i64>) {
232 let mut read = VecDeque::new();
233 let mut timestamps = Vec::with_capacity(alpha2_time::ROUNDING_SCAN_FRAMES);
234 let (mut packets, mut bytes) = (0, 0_u64);
235 while packets < alpha2_time::ROUNDING_SCAN_FRAMES && bytes < alpha2_time::ROUNDING_SCAN_BYTES {
236 let packet = input.read_packet();
237 let more = match &packet {
238 Ok(Some(packet)) => {
239 if usize::try_from(packet.stream_index).ok() == Some(index) {
240 packets += 1;
241 bytes = bytes.saturating_add(u64::try_from(packet.size).unwrap_or(0));
242 if packet.pts != ffi::AV_NOPTS_VALUE {
243 timestamps.push(packet.pts);
244 }
245 }
246 true
247 }
248 Ok(None) | Err(_) => false,
249 };
250 read.push_back(packet);
251 if !more {
252 break;
253 }
254 }
255 (read, timestamps)
256}
257
258fn read_presentation_slack(
260 input: &mut DemuxInput,
261 video_index: usize,
262 time_base: AVRational,
263) -> (Prefetched, MediaTime) {
264 let (read, timestamps) = read_first_packets(input, video_index);
265 let slack = alpha2_time::presentation_slack(
266 i64::from(time_base.num),
267 i64::from(time_base.den),
268 alpha2_time::rounding_quantum(×tamps),
269 );
270 (read, slack)
271}
272
273#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
276pub struct DecodeStageTimings {
277 pub demux: Duration,
279 pub send_packet: Duration,
281 pub receive_frame: Duration,
284 pub convert: Duration,
287 pub seek: Duration,
289}
290
291impl DecodeStageTimings {
292 #[must_use]
294 pub fn merged(self, other: Self) -> Self {
295 Self {
296 demux: self.demux.saturating_add(other.demux),
297 send_packet: self.send_packet.saturating_add(other.send_packet),
298 receive_frame: self.receive_frame.saturating_add(other.receive_frame),
299 convert: self.convert.saturating_add(other.convert),
300 seek: self.seek.saturating_add(other.seek),
301 }
302 }
303}
304
305#[derive(Clone, Copy, PartialEq, Eq)]
306enum InputPosition {
307 Opened,
309 Moved,
310}
311
312#[derive(Clone, Copy, PartialEq, Eq)]
313enum AudioContinuity {
314 Continuous,
315 Damaged,
316}
317
318pub struct NativeAudioDecoder {
325 pub(crate) source: SourceLocation,
326 pub(crate) input: DemuxInput,
327 input_position: InputPosition,
328 pub(crate) streams: Vec<StreamInfo>,
329 pub(crate) container_duration: Option<MediaTime>,
330 pub(crate) audio_index: usize,
331 pub(crate) time_base: AVRational,
332 pub(crate) decoder: AVCodecContext,
333 converter: Option<SwrContext>,
335 pub(crate) sample_rate: u32,
336 pub(crate) channel_count: usize,
337 speakers: SpeakerLayout,
339 speakers_assumed: bool,
341 output_layout: AVChannelLayout,
343 timeline: SourceTimeline,
345 pub(crate) pending: Vec<VecDeque<f32>>,
346 pub(crate) next_sample: Option<i64>,
349 pub(crate) block_frames: usize,
350 pub(crate) demux_eof: bool,
351 pub(crate) decoder_flushed: bool,
352 recovery: Recovery,
353 repair_audio: AudioContinuity,
354 made_up: Option<MadeUpTimestamps>,
357 grid: Option<(u32, alpha2_time::AudioFrameGrid)>,
360 prefetched: Prefetched,
362 frames_placed: u64,
364 seek_preroll: i64,
366}
367
368fn audio_stream_index(probe: &ProbeResult, stream: Option<u32>) -> Result<usize, DecodeError> {
371 match stream {
372 None => probe.selected_audio.ok_or_else(|| {
373 DecodeError::Unsupported("source has no audio stream this runtime decodes".into())
374 }),
375 Some(ordinal) => probe
376 .audio_stream(ordinal)
377 .map(|info| info.index)
378 .ok_or_else(|| {
379 DecodeError::Unsupported(format!(
380 "source has no audio stream {ordinal}; it has {}",
381 probe.audio_streams().count()
382 ))
383 }),
384 }
385}
386
387struct MadeUpTimestamps {
389 rate: u32,
391 drift: i64,
394 rate_changed: bool,
396}
397
398const AUDIO_SEEK_PREROLL_TICKS: i64 = TICKS_PER_SECOND / 10;
403
404const OPUS_SEEK_PREROLL_TICKS: i64 = TICKS_PER_SECOND * 2 / 5;
409
410impl NativeAudioDecoder {
411 pub fn set_decode_policy(&mut self, policy: DecodePolicy) {
413 self.recovery.policy = policy;
414 }
415
416 pub fn set_decode_reporter(
418 &mut self,
419 reporter: impl Fn(crate::DecodeDiagnostic) + Send + Sync + 'static,
420 ) {
421 self.recovery.reporter = Some(Box::new(reporter));
422 }
423
424 #[must_use]
426 pub fn decode_diagnostics(&self) -> &DecodeDiagnostics {
427 &self.recovery.diagnostics
428 }
429
430 pub fn open(
436 source: impl Into<SourceLocation>,
437 project_sample_rate: u32,
438 ) -> Result<Self, DecodeError> {
439 Self::open_stream(source, project_sample_rate, None)
440 }
441
442 pub fn open_stream(
448 source: impl Into<SourceLocation>,
449 project_sample_rate: u32,
450 stream: Option<u32>,
451 ) -> Result<Self, DecodeError> {
452 if project_sample_rate == 0 {
453 return Err(DecodeError::OutOfRange);
454 }
455 let source = source.into();
456 let mut input = open_input(&source)?;
457 let probe = probe_context(&input, &source)?;
458 let selected = audio_stream_index(&probe, stream)?;
459 let stream = probe
460 .stream(selected)
461 .ok_or_else(|| DecodeError::Adapter("selected audio stream disappeared".into()))?;
462 check_source_sample_rate(i64::from(stream.sample_rate.unwrap_or(0)))?;
463 let source_channels =
464 usize::try_from(stream.channels.unwrap_or(0)).map_err(|_| DecodeError::OutOfRange)?;
465 if source_channels == 0 {
466 return Err(DecodeError::Unsupported(
467 "audio stream declares no channels".into(),
468 ));
469 }
470 check_audio_channels(source_channels)?;
471 let decoder = open_audio_decoder(&mut input, selected)?;
472 let (prefetched, timestamps) = read_first_packets(&mut input, selected);
473 let stream = input
474 .streams()
475 .get(selected)
476 .ok_or(DecodeError::OutOfRange)?;
477 let time_base = stream.time_base;
478 let seek_preroll = if stream.codecpar().codec_id == ffi::AV_CODEC_ID_OPUS {
479 OPUS_SEEK_PREROLL_TICKS
480 } else {
481 AUDIO_SEEK_PREROLL_TICKS
482 };
483 let made_up = (input.iformat().name() == c"aac")
486 .then(|| u32::try_from(stream.codecpar().sample_rate).ok())
487 .flatten()
488 .filter(|rate| *rate > 0)
489 .map(|rate| MadeUpTimestamps {
490 rate,
491 drift: 0,
492 rate_changed: false,
493 });
494 let grid = u32::try_from(stream.codecpar().sample_rate)
496 .ok()
497 .filter(|_| made_up.is_none())
498 .and_then(|rate| {
499 alpha2_time::audio_frame_grid(
500 ×tamps,
501 i64::from(time_base.num),
502 i64::from(time_base.den),
503 rate,
504 )
505 .map(|grid| (rate, grid))
506 });
507 let declared = [decoder.ch_layout(), stream.codecpar().ch_layout()]
510 .into_iter()
511 .find(|layout| {
512 layout.order != ffi::AV_CHANNEL_ORDER_UNSPEC
513 && usize::try_from(layout.nb_channels).ok() == Some(source_channels)
514 })
515 .map_or_else(
516 || vec![Speaker::Unnamed; source_channels],
517 |layout| layout_speakers(&layout),
518 );
519 let (speakers, speakers_assumed) = SpeakerLayout::declared_or_default(&declared)
520 .ok_or_else(|| unsupported_channels(source_channels))?;
521 let channel_count = speakers.channels();
522 let output_layout = ffmpeg_layout(&speakers)?;
523 Ok(Self {
524 source,
525 input,
526 input_position: InputPosition::Opened,
527 container_duration: probe.duration,
528 streams: probe.streams,
529 audio_index: selected,
530 time_base,
531 decoder,
532 converter: None,
533 sample_rate: project_sample_rate,
534 channel_count,
535 speakers,
536 speakers_assumed,
537 output_layout,
538 timeline: SourceTimeline::new(project_sample_rate, channel_count, None),
539 pending: (0..channel_count).map(|_| VecDeque::new()).collect(),
540 next_sample: None,
541 block_frames: 1_024,
542 demux_eof: false,
543 decoder_flushed: false,
544 recovery: Recovery::new(crate::recovery::time_base(time_base)),
545 repair_audio: AudioContinuity::Continuous,
546 made_up,
547 grid,
548 prefetched,
549 frames_placed: 0,
550 seek_preroll,
551 })
552 }
553
554 pub fn set_block_frames(&mut self, frames: usize) -> Result<(), DecodeError> {
559 if frames == 0 {
560 return Err(DecodeError::OutOfRange);
561 }
562 self.block_frames = frames;
563 Ok(())
564 }
565
566 #[must_use]
568 pub const fn channels(&self) -> usize {
569 self.channel_count
570 }
571
572 #[must_use]
574 pub const fn speakers(&self) -> SpeakerLayout {
575 self.speakers
576 }
577
578 #[must_use]
580 pub const fn speakers_assumed(&self) -> bool {
581 self.speakers_assumed
582 }
583
584 #[must_use]
590 pub fn audio_duration(&self) -> Option<MediaTime> {
591 effective_media_duration(
592 self.streams
593 .iter()
594 .find(|stream| stream.index == self.audio_index)
595 .and_then(|stream| stream.duration),
596 self.container_duration,
597 )
598 }
599
600 fn stream_start(&self) -> i64 {
602 self.input
603 .streams()
604 .get(self.audio_index)
605 .map(|stream| stream.start_time)
606 .filter(|start| *start != ffi::AV_NOPTS_VALUE)
607 .unwrap_or(0)
608 }
609
610 #[cfg(test)]
612 pub(crate) const fn peak_held_samples(&self) -> usize {
613 self.timeline.peak_held()
614 }
615
616 pub(crate) fn reset_to_start(&mut self) -> Result<(), DecodeError> {
619 if self.input_position == InputPosition::Opened {
620 self.decoder.flush_buffers();
621 } else {
622 let mut input = open_input(&self.source)?;
623 self.decoder = open_audio_decoder(&mut input, self.audio_index)?;
624 self.input = input;
625 self.input_position = InputPosition::Opened;
626 self.prefetched.clear();
627 }
628 self.restart(None);
629 Ok(())
630 }
631
632 fn restart(&mut self, first: Option<i64>) {
634 self.converter = None;
635 self.timeline = SourceTimeline::new(self.sample_rate, self.channel_count, first);
636 self.pending.iter_mut().for_each(VecDeque::clear);
637 self.next_sample = None;
638 self.demux_eof = false;
639 self.decoder_flushed = false;
640 self.repair_audio = AudioContinuity::Continuous;
641 self.recovery.reset_progress();
642 if let Some(made_up) = &mut self.made_up {
643 made_up.drift = 0;
644 }
645 }
646
647 fn made_up_rate_changed(&self) -> bool {
648 self.made_up
649 .as_ref()
650 .is_some_and(|made_up| made_up.rate_changed)
651 }
652
653 fn true_timestamp(&mut self, pts: Option<i64>, rate: u32, samples: i32) -> Option<i64> {
656 let time_base = self.time_base;
657 let Some(made_up) = &mut self.made_up else {
658 return pts;
659 };
660 let declared = made_up.rate;
661 made_up.rate_changed |= rate != declared;
662 let corrected = pts.map(|pts| pts.saturating_sub(made_up.drift));
663 let (num, den) = (
664 i128::from(time_base.num.max(1)),
665 i128::from(time_base.den.max(1)),
666 );
667 let samples = i128::from(samples.max(0));
668 let counted = samples * den / (i128::from(declared) * num);
671 let lasted = (2 * samples * den + i128::from(rate) * num) / (2 * i128::from(rate) * num);
672 made_up.drift = made_up
673 .drift
674 .saturating_add(i64::try_from(counted - lasted).unwrap_or(0));
675 corrected
676 }
677
678 pub(crate) fn receive_audio_frame(&mut self) -> Result<bool, DecodeError> {
679 let mut frame = match self.decoder.receive_frame() {
680 Ok(frame) => frame,
681 Err(RsmpegError::DecoderDrainError | RsmpegError::DecoderFlushedError) => {
682 return Ok(false);
683 }
684 Err(error) => {
685 self.recovery.error(error, "audio receive", None)?;
686 self.repair_audio = AudioContinuity::Damaged;
687 return Ok(true);
688 }
689 };
690 if frame.flags & i32::try_from(ffi::AV_FRAME_FLAG_CORRUPT).expect("flag fits i32") != 0
691 || frame.decode_error_flags != 0
692 {
693 self.recovery
694 .corrupt("audio frame", crate::recovery::pts(frame.pts))?;
695 self.repair_audio = AudioContinuity::Damaged;
696 return Ok(true);
697 }
698 let pts = Some(if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
699 frame.pts
700 } else {
701 frame.best_effort_timestamp
702 })
703 .filter(|pts| *pts != ffi::AV_NOPTS_VALUE);
704 let (num, den) = (self.time_base.num.into(), self.time_base.den.into());
705 if pts.is_some_and(|pts| !audio_timestamp_in_range(pts, num, den)) {
706 self.recovery.corrupt("audio timestamp", pts)?;
707 self.repair_audio = AudioContinuity::Damaged;
708 return Ok(true);
709 }
710 self.recovery.progress(pts)?;
711 normalize_audio_frame_layout(&mut frame, &self.output_layout)?;
712 check_source_sample_rate(i64::from(frame.sample_rate))?;
714 let rate = u32::try_from(frame.sample_rate).map_err(|_| DecodeError::OutOfRange)?;
715 let pts = self.true_timestamp(pts, rate, frame.nb_samples);
716 let planes = self.convert_audio_frame(&frame)?;
717 self.place_audio(rate, pts, planes)?;
718 Ok(true)
719 }
720
721 fn convert_audio_frame(&mut self, frame: &AVFrame) -> Result<Vec<Vec<f32>>, DecodeError> {
723 let mut packed = audio_output_frame(frame.sample_rate, &self.output_layout);
724 let mut converter = match self.converter.take() {
725 Some(converter) => converter,
726 None => audio_converter(frame, &self.output_layout)?,
727 };
728 if let Err(error) = converter.convert_frame(Some(frame), &mut packed) {
729 if error.raw_error() != Some(ffi::AVERROR_INPUT_CHANGED) {
730 return Err(adapter_error(error));
731 }
732 converter = audio_converter(frame, &self.output_layout)?;
733 packed = audio_output_frame(frame.sample_rate, &self.output_layout);
734 converter
735 .convert_frame(Some(frame), &mut packed)
736 .map_err(adapter_error)?;
737 }
738 self.converter = Some(converter);
739 if packed.nb_samples != frame.nb_samples {
741 return Err(DecodeError::Adapter(format!(
742 "converting {} decoded audio samples gave {}",
743 frame.nb_samples, packed.nb_samples
744 )));
745 }
746 let mut planes = (0..self.channel_count)
747 .map(|_| VecDeque::new())
748 .collect::<Vec<_>>();
749 append_interleaved_audio(&packed, &mut planes)?;
750 Ok(planes.into_iter().map(Vec::from).collect())
751 }
752
753 fn place_audio(
760 &mut self,
761 rate: u32,
762 pts: Option<i64>,
763 mut planes: Vec<Vec<f32>>,
764 ) -> Result<(), DecodeError> {
765 let rate_i32 = i32::try_from(rate).map_err(|_| DecodeError::OutOfRange)?;
766 let at = pts.map(|pts| {
767 av_rescale_q_rnd(
768 pts,
769 self.time_base,
770 ra(1, rate_i32),
771 ffi::AV_ROUND_NEAR_INF | ffi::AV_ROUND_PASS_MINMAX,
772 )
773 });
774 let damaged = self.repair_audio == AudioContinuity::Damaged;
775 self.repair_audio = AudioContinuity::Continuous;
776 self.frames_placed = self.frames_placed.wrapping_add(1);
777 let frames = i64::try_from(planes.first().map_or(0, Vec::len)).unwrap_or(i64::MAX);
778 let Some(expected) = self.timeline.expected(rate) else {
779 let at = match (at, self.grid) {
782 (Some(at), Some((grid_rate, grid))) if !damaged && grid_rate == rate => {
783 grid.place(at, frames)
784 }
785 (at, _) => at.unwrap_or(0),
786 };
787 return self.timeline.place(rate, at, planes);
788 };
789 let Some(at) = at else {
790 if damaged {
791 return Err(DecodeError::Adapter(
792 "cannot locate damaged audio gap without PTS".into(),
793 ));
794 }
795 return self.timeline.place(rate, expected, planes);
796 };
797 let ahead = at
798 .checked_sub(expected)
799 .ok_or_else(|| DecodeError::Adapter("audio timestamps are out of range".into()))?;
800 if damaged {
801 if ahead < 0 || ahead > i64::from(rate) * 10 {
802 return Err(DecodeError::Adapter(
803 "damaged audio gap is ambiguous or exceeds 10 seconds".into(),
804 ));
805 }
806 if ahead > 0 {
807 self.recovery.audio_gap(
808 self.timeline.output_at(rate, expected),
809 self.timeline.output_at(rate, at),
810 self.sample_rate,
811 "corrupt input",
812 )?;
813 }
814 return self.timeline.place(rate, at, planes);
815 }
816 let den = i64::from(self.time_base.den.max(1));
818 let unit = (i64::from(rate) * i64::from(self.time_base.num) + den - 1) / den;
819 let tolerance = frames
820 .max((i64::from(rate) + 499) / 500)
821 .max(unit.saturating_mul(2));
822 if ahead.abs() < tolerance {
823 return self.timeline.place(rate, expected, planes);
824 }
825 if ahead > 0 {
826 self.recovery.timestamp_gap(
827 self.timeline.output_at(rate, expected),
828 self.timeline.output_at(rate, at),
829 self.sample_rate,
830 );
831 return self.timeline.place(rate, at, planes);
832 }
833 let repeated = usize::try_from(-ahead).unwrap_or(usize::MAX);
834 self.recovery.timestamp_overlap(
835 self.timeline.output_at(rate, at),
836 self.timeline
837 .output_at(rate, at.saturating_add(frames.min(-ahead))),
838 self.sample_rate,
839 );
840 for plane in &mut planes {
841 plane.drain(..repeated.min(plane.len()));
842 }
843 self.timeline.place(rate, expected, planes)
844 }
845
846 pub(crate) fn fill_pending(
847 &mut self,
848 frames: usize,
849 cancel: &CancelToken,
850 ) -> Result<(), DecodeError> {
851 interrupt_on_cancel(&self.input, cancel);
852 let mut budget = WorkBudget::new();
853 let mut foreign = false;
854 let mut placed = self.frames_placed;
855 loop {
856 let held = self.pending.first().map_or(0, VecDeque::len);
857 if held >= frames {
858 return Ok(());
859 }
860 if self.frames_placed != placed {
863 placed = self.frames_placed;
864 budget.progressed();
865 }
866 if std::mem::take(&mut foreign) {
869 if cancel.is_cancelled() {
870 return Err(DecodeError::Cancelled);
871 }
872 } else {
873 budget.step(cancel)?;
874 }
875 if let Some((start, _)) = self.timeline.produce(&mut self.pending, frames - held) {
876 if held == 0 {
877 self.next_sample = Some(start);
878 }
879 continue;
880 }
881 if self.receive_audio_frame()? {
882 continue;
883 }
884 if self.demux_eof {
885 if !self.decoder_flushed {
886 match self.decoder.send_packet(None) {
887 Ok(()) | Err(RsmpegError::DecoderFlushedError) => {}
888 Err(RsmpegError::DecoderFullError) => continue,
889 Err(error) => {
890 self.recovery.error(error, "flush", None)?;
891 continue;
892 }
893 }
894 self.decoder_flushed = true;
895 continue;
896 }
897 if self.repair_audio == AudioContinuity::Damaged {
898 self.recovery.damaged_tail("audio")?;
901 self.repair_audio = AudioContinuity::Continuous;
902 }
903 if !self.timeline.finished() {
904 self.timeline.finish();
905 continue;
906 }
907 return Ok(());
908 }
909 self.input_position = InputPosition::Moved;
910 let packet = match self
911 .prefetched
912 .pop_front()
913 .unwrap_or_else(|| self.input.read_packet())
914 {
915 Ok(Some(packet)) => packet,
916 Ok(None) => {
917 self.demux_eof = true;
918 continue;
919 }
920 Err(error) => {
921 let error = demux_failure(&self.input, error, cancel)?;
922 self.recovery.error(error, "audio demux", None)?;
923 self.repair_audio = AudioContinuity::Damaged;
924 continue;
925 }
926 };
927 if usize::try_from(packet.stream_index).ok() != Some(self.audio_index) {
928 foreign = true;
929 continue;
930 }
931 budget.advanced();
932 if packet.flags & i32::try_from(ffi::AV_PKT_FLAG_CORRUPT).expect("flag fits i32") != 0 {
933 self.recovery
934 .corrupt("audio packet", crate::recovery::pts(packet.pts))?;
935 self.repair_audio = AudioContinuity::Damaged;
936 continue;
937 }
938 submit_packet(
939 |drain| {
940 if drain {
941 return self.receive_audio_frame();
942 }
943 match self.decoder.send_packet(Some(&packet)) {
944 Ok(()) => Ok(true),
945 Err(RsmpegError::DecoderFullError) => Ok(false),
946 Err(error) => {
947 self.recovery.error(error, "audio send", Some(packet.pts))?;
948 self.repair_audio = AudioContinuity::Damaged;
949 Ok(true)
950 }
951 }
952 },
953 &mut budget,
954 cancel,
955 )?;
956 }
957 }
958}
959
960impl Decoder for NativeAudioDecoder {
961 fn streams(&self) -> &[StreamInfo] {
962 &self.streams
963 }
964 fn flush(&mut self) -> Result<(), DecodeError> {
965 self.reset_to_start()
966 }
967 fn seek(
968 &mut self,
969 request: DecodeRequest,
970 cancel: &CancelToken,
971 ) -> Result<DecodeResult, DecodeError> {
972 if cancel.is_cancelled() {
973 return Err(DecodeError::Cancelled);
974 }
975 let target = request
976 .time
977 .ticks()
978 .saturating_mul(i64::from(self.sample_rate))
979 .div_euclid(TICKS_PER_SECOND);
980 let timestamp = av_rescale_q(
981 request.time.ticks().saturating_sub(self.seek_preroll),
982 tick_base(),
983 self.time_base,
984 );
985 let rate_changed = self.made_up_rate_changed();
989 let from_start = timestamp <= self.stream_start() || rate_changed;
990 if from_start {
991 self.reset_to_start()?;
992 } else {
993 interrupt_on_cancel(&self.input, cancel);
994 self.input_position = InputPosition::Moved;
995 self.prefetched.clear();
996 self.input
997 .seek(
998 i32::try_from(self.audio_index).map_err(|_| DecodeError::OutOfRange)?,
999 timestamp,
1000 i32::try_from(ffi::AVSEEK_FLAG_BACKWARD).expect("seek flag fits i32"),
1001 )
1002 .map_err(|error| seek_failure(&self.input, error, cancel))?;
1003 }
1004 self.decoder.flush_buffers();
1005 self.restart(Some(target));
1006 let mut event = self.decode_next(cancel)?;
1007 if !from_start && !rate_changed && self.made_up_rate_changed() {
1008 self.reset_to_start()?;
1010 self.decoder.flush_buffers();
1011 self.restart(Some(target));
1012 event = self.decode_next(cancel)?;
1013 }
1014 if matches!(event, DecodeEvent::EndOfStream) {
1015 return Err(DecodeError::OutOfRange);
1016 }
1017 Ok(DecodeResult { request, event })
1018 }
1019 fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError> {
1020 if cancel.is_cancelled() {
1021 return Err(DecodeError::Cancelled);
1022 }
1023 self.fill_pending(self.block_frames, cancel)?;
1024 let frames = self
1025 .pending
1026 .first()
1027 .map_or(0, VecDeque::len)
1028 .min(self.block_frames);
1029 if frames == 0 {
1030 return Ok(DecodeEvent::EndOfStream);
1031 }
1032 let start_sample = self.next_sample.unwrap_or(0);
1033 let block = AudioBlock {
1034 start_sample,
1035 sample_rate: self.sample_rate,
1036 speakers: self.speakers,
1037 channels: self
1038 .pending
1039 .iter_mut()
1040 .map(|channel| channel.drain(..frames).collect())
1041 .collect(),
1042 };
1043 self.next_sample =
1044 Some(start_sample.saturating_add(i64::try_from(frames).unwrap_or(i64::MAX)));
1045 Ok(DecodeEvent::Audio(block))
1046 }
1047}
1048
1049fn open_audio_decoder(
1051 input: &mut DemuxInput,
1052 stream_index: usize,
1053) -> Result<AVCodecContext, DecodeError> {
1054 input.discard_all_but(stream_index);
1055 let stream = input
1056 .streams()
1057 .get(stream_index)
1058 .ok_or(DecodeError::OutOfRange)?;
1059 let parameters = stream.codecpar();
1060 let codec = AVCodec::find_decoder(parameters.codec_id)
1061 .ok_or_else(|| DecodeError::Unsupported("audio decoder is unavailable".into()))?;
1062 allowed_decoder(&codec)?;
1063 let mut decoder = AVCodecContext::new(&codec);
1064 decoder.apply_codecpar(¶meters).map_err(adapter_error)?;
1065 decoder.set_pkt_timebase(stream.time_base);
1066 decoder.open(None).map_err(adapter_error)?;
1067 Ok(decoder)
1068}
1069
1070pub const SOURCE_SAMPLE_RATES: std::ops::RangeInclusive<u32> = 1_000..=768_000;
1072
1073fn check_source_sample_rate(rate: i64) -> Result<(), DecodeError> {
1074 if u32::try_from(rate).is_ok_and(|rate| SOURCE_SAMPLE_RATES.contains(&rate)) {
1075 return Ok(());
1076 }
1077 Err(DecodeError::Unsupported(format!(
1078 "the source's audio is {rate} Hz, and alpha2 reads audio from {} Hz to {} Hz",
1079 SOURCE_SAMPLE_RATES.start(),
1080 SOURCE_SAMPLE_RATES.end()
1081 )))
1082}
1083
1084pub(crate) fn audio_converter(
1087 frame: &AVFrame,
1088 output: &AVChannelLayout,
1089) -> Result<SwrContext, DecodeError> {
1090 if frame.sample_rate <= 0 || frame.format == ffi::AV_SAMPLE_FMT_NONE {
1091 return Err(DecodeError::Adapter(
1092 "decoded audio frame has an incomplete format".into(),
1093 ));
1094 }
1095 let input_layout = frame.ch_layout();
1098 let mut converter = SwrContext::new(
1099 output,
1100 ffi::AV_SAMPLE_FMT_FLT,
1101 frame.sample_rate,
1102 &input_layout,
1103 frame.format,
1104 frame.sample_rate,
1105 )
1106 .map_err(adapter_error)?;
1107 converter.init().map_err(adapter_error)?;
1108 Ok(converter)
1109}
1110
1111pub(crate) fn layout_speakers(layout: &AVChannelLayout) -> Vec<Speaker> {
1113 let channels = alpha2_ffmpeg_bridge::channel_layout_channels(layout);
1114 if channels.is_empty() {
1115 return vec![Speaker::Unnamed; usize::try_from(layout.nb_channels).unwrap_or(0)];
1116 }
1117 channels
1118 .into_iter()
1119 .map(|channel| Speaker::from_ffmpeg_channel(i64::from(channel)))
1120 .collect()
1121}
1122
1123pub(crate) fn ffmpeg_layout(speakers: &SpeakerLayout) -> Result<AVChannelLayout, DecodeError> {
1125 let channels = speakers
1126 .speakers()
1127 .iter()
1128 .map(|speaker| {
1129 ffi::AVChannel::try_from(speaker.ffmpeg_channel()).unwrap_or(ffi::AV_CHAN_UNKNOWN)
1130 })
1131 .collect::<Vec<_>>();
1132 alpha2_ffmpeg_bridge::channel_layout_of(&channels).map_err(|error| {
1133 DecodeError::Adapter(format!(
1134 "could not lay out audio channels {}: {error:?}",
1135 speakers.describe()
1136 ))
1137 })
1138}
1139
1140fn unsupported_channels(channels: usize) -> DecodeError {
1141 DecodeError::Unsupported(format!(
1142 "audio with {channels} channels is unsupported: the engine takes 1 to {MAX_AUDIO_CHANNELS}"
1143 ))
1144}
1145
1146fn check_audio_channels(channels: usize) -> Result<(), DecodeError> {
1147 if (1..=MAX_AUDIO_CHANNELS).contains(&channels) {
1148 Ok(())
1149 } else {
1150 Err(unsupported_channels(channels))
1151 }
1152}
1153
1154pub(crate) fn normalize_audio_frame_layout(
1161 frame: &mut AVFrame,
1162 stream: &AVChannelLayout,
1163) -> Result<(), DecodeError> {
1164 let (channels, named) = {
1165 let layout = frame.ch_layout();
1166 let named = matches!(
1167 layout.order,
1168 ffi::AV_CHANNEL_ORDER_NATIVE | ffi::AV_CHANNEL_ORDER_CUSTOM
1169 ) && !layout_speakers(&layout).contains(&Speaker::Unnamed);
1170 (layout.nb_channels, named)
1171 };
1172 if channels <= 0 {
1173 return Err(DecodeError::Adapter(
1174 "decoded audio frame has no channels".into(),
1175 ));
1176 }
1177 if named {
1178 return Ok(());
1179 }
1180 if channels == stream.nb_channels {
1181 let mut owned = AVChannelLayout::from_nb_channels(1);
1182 owned.copy(stream);
1183 frame.set_ch_layout(owned.into_inner());
1184 return Ok(());
1185 }
1186 let count = usize::try_from(channels).map_err(|_| DecodeError::OutOfRange)?;
1187 let speakers = SpeakerLayout::default_for(count).ok_or_else(|| unsupported_channels(count))?;
1188 frame.set_ch_layout(ffmpeg_layout(&speakers)?.into_inner());
1189 Ok(())
1190}
1191
1192pub(crate) fn audio_output_frame(sample_rate: i32, layout: &AVChannelLayout) -> AVFrame {
1193 let mut frame = AVFrame::new();
1194 frame.set_format(ffi::AV_SAMPLE_FMT_FLT);
1195 frame.set_sample_rate(sample_rate);
1196 let mut owned = AVChannelLayout::from_nb_channels(1);
1197 owned.copy(layout);
1198 frame.set_ch_layout(owned.into_inner());
1199 frame
1200}
1201
1202pub(crate) fn append_interleaved_audio(
1203 frame: &AVFrame,
1204 output: &mut [VecDeque<f32>],
1205) -> Result<(), DecodeError> {
1206 let packed = alpha2_ffmpeg_bridge::audio_f32_interleaved(frame).map_err(adapter_error)?;
1207 if output.is_empty() || packed.len() % output.len() != 0 {
1208 return Err(DecodeError::Adapter(
1209 "FFmpeg returned a partial audio frame".into(),
1210 ));
1211 }
1212 for frame in packed.chunks_exact(output.len()) {
1213 for (channel, sample) in output.iter_mut().zip(frame) {
1214 channel.push_back(*sample);
1215 }
1216 }
1217 Ok(())
1218}
1219
1220pub(crate) fn has_hw_config_method(methods: i32, method: impl Into<i64>) -> bool {
1225 i64::from(methods) & method.into() != 0
1226}
1227
1228const STREAM_START_SEEK: i64 = i64::MIN / 2;
1233
1234enum Landing {
1235 Presented(DecodedFrame),
1237 Late(DecodedFrame),
1239 Empty,
1241}
1242
1243impl NativeDecoder {
1244 pub fn set_decode_policy(&mut self, policy: DecodePolicy) {
1246 self.recovery.policy = policy;
1247 }
1248
1249 pub fn declare_color(&mut self, color: Option<ColorMetadata>) {
1252 self.declared_color = color;
1253 }
1254
1255 #[cfg(all(
1257 any(target_os = "linux", target_os = "macos", target_os = "windows"),
1258 feature = "hwdecode"
1259 ))]
1260 pub(crate) fn picture_chroma_location(&self, frame: &AVFrame) -> alpha2_media::ChromaLocation {
1261 crate::convert::decoded_chroma_location(self.decoder.codec_id, frame.chroma_location)
1262 }
1263
1264 pub(crate) fn picture_color(&self, frame: &AVFrame) -> Option<ColorMetadata> {
1266 self.declared_color
1267 .or_else(|| frame_color_metadata(frame))
1268 .or(self.color)
1269 }
1270
1271 pub fn set_decode_reporter(
1273 &mut self,
1274 reporter: impl Fn(crate::DecodeDiagnostic) + Send + Sync + 'static,
1275 ) {
1276 self.recovery.reporter = Some(Box::new(reporter));
1277 }
1278
1279 #[must_use]
1281 pub fn decode_diagnostics(&self) -> &DecodeDiagnostics {
1282 &self.recovery.diagnostics
1283 }
1284
1285 pub fn open(source: impl Into<SourceLocation>) -> Result<Self, DecodeError> {
1290 Self::open_with_threads(source, codec_thread_budget())
1291 }
1292
1293 pub fn open_with_threads(
1298 source: impl Into<SourceLocation>,
1299 threads: i64,
1300 ) -> Result<Self, DecodeError> {
1301 if !(1..=64).contains(&threads) {
1302 return Err(DecodeError::OutOfRange);
1303 }
1304 let source = source.into();
1305 let mut input = open_input(&source)?;
1306 let probed = probe_context(&input, &source)?;
1307 let video_index = probed.selected_video.ok_or_else(|| {
1308 DecodeError::Unsupported("resource has no decodable video stream".into())
1309 })?;
1310 input.discard_all_but(video_index);
1311 let selected = probed
1312 .streams
1313 .iter()
1314 .find(|stream| stream.index == video_index)
1315 .ok_or(DecodeError::OutOfRange)?;
1316 if let Some((width, height)) = selected.dimensions {
1317 check_frame_size(width, height)?;
1318 }
1319 let orientation = selected.orientation;
1320 let sample_aspect_ratio = selected.sample_aspect_ratio;
1321 let color = selected.color;
1323 let dropped_layer;
1324 let (time_base, decoder) = {
1325 let stream = &input.streams()[video_index];
1326 let parameters = stream.codecpar();
1327 let (codec, dropped) = software_decoder_for(¶meters, selected.alpha)?;
1328 dropped_layer = dropped;
1329 let mut decoder = AVCodecContext::new(&codec);
1330 decoder.apply_codecpar(¶meters).map_err(adapter_error)?;
1331 decoder.set_pkt_timebase(stream.time_base);
1332 let unused = alpha2_ffmpeg_bridge::open_codec_context(
1333 &mut decoder,
1334 video_decoder_options(threads),
1335 )
1336 .map_err(adapter_error)?;
1337 reject_unused_decode_options(unused)?;
1338 (stream.time_base, decoder)
1339 };
1340 let (prefetched, slack) = read_presentation_slack(&mut input, video_index, time_base);
1341 Ok(Self {
1342 time_base,
1343 input,
1344 container_duration: probed.duration,
1345 streams: probed.streams,
1346 video_index,
1347 decoder,
1348 orientation,
1349 sample_aspect_ratio,
1350 color,
1351 declared_color: None,
1352 video_scaler: crate::convert::FrameScaler::default(),
1353 pending: VecDeque::new(),
1354 demux_eof: false,
1355 decoder_flushed: false,
1356 stages: DecodeStageTimings::default(),
1357 first_video_pts: None,
1358 recovery: Recovery::new(crate::recovery::time_base(time_base)),
1359 slack,
1360 prefetched,
1361 dropped_layer,
1362 })
1363 }
1364
1365 #[cfg(all(
1369 any(target_os = "linux", target_os = "macos", target_os = "windows"),
1370 feature = "hwdecode"
1371 ))]
1372 #[allow(clippy::too_many_lines)]
1373 pub(crate) fn open_hardware(
1374 source: impl Into<SourceLocation>,
1375 threads: i64,
1376 device: AVHWDeviceContext,
1377 spec: &HardwareDecoderSpec<'_>,
1378 ) -> Result<Self, HardwareOpenError> {
1379 use crate::video_frame::HardwareDecodeFallback::{
1380 DecoderOpenFailed, NoHardwareConfig, SourceUnavailable, UnsupportedColor,
1381 };
1382
1383 let unavailable = |error| HardwareOpenError::new(SourceUnavailable, error);
1384 let source = source.into();
1385 let mut input = open_input(&source).map_err(unavailable)?;
1386 let probed = probe_context(&input, &source).map_err(unavailable)?;
1387 let video_index = probed.selected_video.ok_or_else(|| {
1388 HardwareOpenError::new(
1389 SourceUnavailable,
1390 DecodeError::Unsupported("resource has no decodable video stream".into()),
1391 )
1392 })?;
1393 input.discard_all_but(video_index);
1394 let selected = probed
1395 .streams
1396 .iter()
1397 .find(|stream| stream.index == video_index)
1398 .ok_or_else(|| HardwareOpenError::new(SourceUnavailable, DecodeError::OutOfRange))?;
1399 if let Some((width, height)) = selected.dimensions {
1400 check_frame_size(width, height).map_err(unavailable)?;
1401 }
1402 let orientation = selected.orientation;
1403 let sample_aspect_ratio = selected.sample_aspect_ratio;
1404 let color = selected.color;
1405 if selected.color.is_some_and(ColorMetadata::is_hdr) {
1406 return Err(HardwareOpenError::new(
1407 UnsupportedColor,
1408 DecodeError::Unsupported("hardware export currently supports SDR only".into()),
1409 ));
1410 }
1411 if let Some(alpha) = selected.alpha {
1414 return Err(HardwareOpenError::new(
1415 crate::video_frame::HardwareDecodeFallback::AlphaChannel,
1416 DecodeError::Unsupported(format!(
1417 "the stream carries alpha ({}), which {} decode drops",
1418 alpha.as_str(),
1419 spec.backend
1420 )),
1421 ));
1422 }
1423 let (time_base, decoder) = {
1424 let stream = &input.streams()[video_index];
1425 let parameters = stream.codecpar();
1426 let preferred = AVCodec::find_decoder(parameters.codec_id).ok_or_else(|| {
1427 HardwareOpenError::new(
1428 NoHardwareConfig,
1429 DecodeError::Unsupported("selected video codec has no decoder".into()),
1430 )
1431 })?;
1432 allowed_decoder(&preferred)
1433 .map_err(|error| HardwareOpenError::new(NoHardwareConfig, error))?;
1434 if let Some(codecs) = spec.hardware_codecs {
1435 let listed = hardware_codec_name(parameters.codec_id);
1436 if !listed.is_some_and(|name| codecs.contains(&name)) {
1437 let name = listed.map_or_else(
1438 || preferred.name().to_string_lossy().into_owned(),
1439 str::to_owned,
1440 );
1441 return Err(HardwareOpenError::new(
1442 NoHardwareConfig,
1443 DecodeError::Unsupported(format!(
1444 "{} has no hardware decoder for {name} here",
1445 spec.backend
1446 )),
1447 ));
1448 }
1449 }
1450 let supported = |codec: &AVCodecRef<'_>| {
1451 (0..)
1452 .map_while(|index| codec.hw_config(index))
1453 .any(|config| {
1454 config.device_type == spec.device_type
1455 && config.pix_fmt == spec.pixel_format
1456 && (!spec.require_device_context
1457 || has_hw_config_method(
1458 config.methods,
1459 ffi::AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX,
1460 ))
1461 })
1462 };
1463 let Some(codec) =
1464 registered_video_decoders(parameters.codec_id).find(|codec| supported(codec))
1465 else {
1466 return Err(HardwareOpenError::new(
1467 NoHardwareConfig,
1468 DecodeError::Unsupported(format!(
1469 "decoder {} has no {} hardware configuration",
1470 preferred.name().to_string_lossy(),
1471 spec.backend
1472 )),
1473 ));
1474 };
1475 check_hardware_sample_profile(parameters.format, spec)?;
1476 check_hardware_crop(¶meters, spec)?;
1477 let open_failed = |error| HardwareOpenError::new(DecoderOpenFailed, error);
1478 let mut decoder = AVCodecContext::new(&codec);
1479 decoder
1480 .apply_codecpar(¶meters)
1481 .map_err(adapter_error)
1482 .map_err(open_failed)?;
1483 decoder.set_pkt_timebase(stream.time_base);
1484 decoder.set_get_format(Some(spec.get_format));
1485 decoder.set_hw_device_ctx(device);
1486 let unused = alpha2_ffmpeg_bridge::open_codec_context(
1488 &mut decoder,
1489 video_decoder_options(threads),
1490 )
1491 .map_err(adapter_error)
1492 .map_err(open_failed)?;
1493 reject_unused_decode_options(unused).map_err(open_failed)?;
1494 (stream.time_base, decoder)
1495 };
1496 let (prefetched, slack) = read_presentation_slack(&mut input, video_index, time_base);
1497 Ok(Self {
1498 time_base,
1499 input,
1500 container_duration: probed.duration,
1501 streams: probed.streams,
1502 video_index,
1503 decoder,
1504 orientation,
1505 sample_aspect_ratio,
1506 color,
1507 declared_color: None,
1508 video_scaler: crate::convert::FrameScaler::default(),
1509 pending: VecDeque::new(),
1510 demux_eof: false,
1511 decoder_flushed: false,
1512 stages: DecodeStageTimings::default(),
1513 first_video_pts: None,
1514 recovery: Recovery::hardware(crate::recovery::time_base(time_base)),
1515 slack,
1516 prefetched,
1517 dropped_layer: None,
1518 })
1519 }
1520
1521 #[must_use]
1523 pub const fn dropped_layer(&self) -> Option<&DroppedLayer> {
1524 self.dropped_layer.as_ref()
1525 }
1526
1527 #[must_use]
1532 pub fn video_duration(&self) -> Option<MediaTime> {
1533 effective_media_duration(
1534 self.streams
1535 .iter()
1536 .find(|stream| stream.index == self.video_index)
1537 .and_then(|stream| stream.duration),
1538 self.container_duration,
1539 )
1540 }
1541
1542 pub(crate) fn take_stage_timings(&mut self) -> DecodeStageTimings {
1544 std::mem::take(&mut self.stages)
1545 }
1546
1547 pub(crate) fn receive_available_raw(
1548 &mut self,
1549 cancel: &CancelToken,
1550 ) -> Result<Option<DecodedFrame>, DecodeError> {
1551 let mut budget = WorkBudget::new();
1552 loop {
1553 budget.step(cancel)?;
1554 let started = Instant::now();
1555 let received = DecodedFrame::receive(&mut self.decoder);
1556 self.stages.receive_frame = self.stages.receive_frame.saturating_add(started.elapsed());
1557 match received {
1558 Ok(frame) => {
1559 if frame.flags
1560 & i32::try_from(ffi::AV_FRAME_FLAG_CORRUPT).expect("flag fits i32")
1561 != 0
1562 || frame.decode_error_flags != 0
1563 {
1564 self.recovery
1565 .corrupt("video frame", crate::recovery::pts(frame.pts))?;
1566 continue;
1567 }
1568 #[cfg(test)]
1569 VIDEO_FRAMES_DECODED.with(|decoded| decoded.set(decoded.get() + 1));
1570 self.recovery.progress(crate::recovery::pts(
1571 if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1572 frame.pts
1573 } else {
1574 frame.best_effort_timestamp
1575 },
1576 ))?;
1577 return Ok(Some(frame));
1578 }
1579 Err(RsmpegError::DecoderDrainError | RsmpegError::DecoderFlushedError) => {
1580 return Ok(None);
1581 }
1582 Err(error) => {
1583 self.recovery.error(error, "video receive", None)?;
1584 }
1585 }
1586 }
1587 }
1588
1589 pub(crate) fn convert_received(
1590 &mut self,
1591 frame: &DecodedFrame,
1592 ) -> Result<DecodedVideoFrame, DecodeError> {
1593 let declared = self.picture_color(frame);
1595 let started = Instant::now();
1596 let converted = convert_video_frame(
1597 frame,
1598 self.decoder.codec_id,
1599 self.time_base,
1600 declared.unwrap_or(ColorMetadata::UNDECLARED),
1601 &mut self.video_scaler,
1602 );
1603 self.stages.convert = self.stages.convert.saturating_add(started.elapsed());
1604 let mut converted = converted?;
1605 if declared.is_none() && converted.color == Some(ColorMetadata::UNDECLARED) {
1608 converted.color = None;
1609 }
1610 converted.orientation = self.orientation;
1611 converted.sample_aspect_ratio = self.picture_sample_aspect_ratio(frame);
1612 Ok(converted)
1613 }
1614
1615 pub(crate) fn picture_sample_aspect_ratio(&self, frame: &AVFrame) -> SampleAspectRatio {
1618 if declared_sar(self.input.streams()[self.video_index].sample_aspect_ratio).is_some() {
1620 return self.sample_aspect_ratio;
1621 }
1622 declared_sar(frame.sample_aspect_ratio).unwrap_or(self.sample_aspect_ratio)
1623 }
1624
1625 pub(crate) fn raw_frame_pts(&self, frame: &AVFrame) -> Result<MediaTime, DecodeError> {
1626 let pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1627 frame.pts
1628 } else {
1629 frame.best_effort_timestamp
1630 };
1631 timestamp(pts, self.time_base).ok_or(DecodeError::OutOfRange)
1632 }
1633
1634 pub(crate) fn flush_video(&mut self) {
1636 let started = Instant::now();
1637 self.recovery.reset_progress();
1638 self.decoder.flush_buffers();
1639 self.stages.seek = self.stages.seek.saturating_add(started.elapsed());
1640 self.pending.clear();
1641 self.prefetched.clear();
1642 self.demux_eof = false;
1643 self.decoder_flushed = false;
1644 }
1645
1646 pub(crate) fn seek_raw(
1660 &mut self,
1661 target: MediaTime,
1662 cancel: &CancelToken,
1663 ) -> Result<DecodedFrame, DecodeError> {
1664 if cancel.is_cancelled() {
1665 return Err(DecodeError::Cancelled);
1666 }
1667 let start_time = self.input.streams()[self.video_index].start_time;
1668 let stream_start = timestamp(start_time, self.time_base).unwrap_or(MediaTime::ZERO);
1669 let deadline = self.presentation_deadline(target);
1670 let mut back_off = 0_i64;
1671 loop {
1672 let from = MediaTime::from_ticks(deadline.ticks().saturating_sub(back_off));
1675 let from_start =
1676 from <= stream_start || self.first_video_pts.is_some_and(|first| deadline < first);
1677 if !from_start {
1678 let position = av_rescale_q_rnd(
1680 from.ticks(),
1681 tick_base(),
1682 self.time_base,
1683 ffi::AV_ROUND_DOWN,
1684 );
1685 self.seek_video_to(position, cancel)?;
1686 } else if let Err(error) = self.seek_video_to(STREAM_START_SEEK, cancel) {
1687 if error == DecodeError::Cancelled {
1688 return Err(error);
1689 }
1690 let start = if start_time == ffi::AV_NOPTS_VALUE {
1691 0
1692 } else {
1693 start_time
1694 };
1695 self.seek_video_to(start, cancel)?;
1696 }
1697 let mut first = None;
1698 let landing = self.present_after_seek(target, &mut first, cancel)?;
1699 if from_start {
1700 self.first_video_pts = first.or(self.first_video_pts);
1702 }
1703 match landing {
1704 Landing::Presented(frame) => return Ok(frame),
1705 Landing::Late(frame) if from_start || first == self.first_video_pts => {
1706 return Ok(frame);
1707 }
1708 Landing::Empty if from_start => return Err(DecodeError::OutOfRange),
1709 Landing::Late(_) | Landing::Empty => {}
1710 }
1711 back_off = if back_off == 0 {
1712 TICKS_PER_SECOND
1713 } else {
1714 back_off.saturating_mul(2)
1715 };
1716 }
1717 }
1718
1719 fn seek_video_to(&mut self, position: i64, cancel: &CancelToken) -> Result<(), DecodeError> {
1720 interrupt_on_cancel(&self.input, cancel);
1721 let seek_started = Instant::now();
1722 let sought = self.input.seek(
1723 i32::try_from(self.video_index).map_err(|_| DecodeError::OutOfRange)?,
1724 position,
1725 i32::try_from(ffi::AVSEEK_FLAG_BACKWARD).expect("seek flag fits i32"),
1726 );
1727 self.stages.seek = self.stages.seek.saturating_add(seek_started.elapsed());
1728 sought.map_err(|error| seek_failure(&self.input, error, cancel))?;
1729 self.flush_video();
1730 Ok(())
1731 }
1732
1733 fn present_after_seek(
1736 &mut self,
1737 target: MediaTime,
1738 first: &mut Option<MediaTime>,
1739 cancel: &CancelToken,
1740 ) -> Result<Landing, DecodeError> {
1741 let deadline = self.presentation_deadline(target);
1742 let mut presented: Option<DecodedFrame> = None;
1743 let mut budget = WorkBudget::new();
1744 loop {
1745 budget.step(cancel)?;
1746 let Some(raw) = self.decode_raw_next(cancel)? else {
1747 return Ok(presented.map_or(Landing::Empty, Landing::Presented));
1748 };
1749 budget.progressed();
1751 #[cfg(test)]
1752 crate::recovery::take_frame_delay();
1753 let pts = self.raw_frame_pts(&raw)?;
1754 first.get_or_insert(pts);
1755 if pts > deadline {
1756 return Ok(match presented {
1757 Some(frame) => {
1758 self.pending.push_front(raw);
1759 Landing::Presented(frame)
1760 }
1761 None => Landing::Late(raw),
1762 });
1763 }
1764 if pts >= target {
1766 return Ok(Landing::Presented(raw));
1767 }
1768 presented = Some(raw);
1769 }
1770 }
1771
1772 #[must_use]
1775 pub fn presentation_deadline(&self, time: MediaTime) -> MediaTime {
1776 time.presentation_deadline(self.slack)
1777 }
1778
1779 pub fn peek_video_pts(
1787 &mut self,
1788 cancel: &CancelToken,
1789 ) -> Result<Option<MediaTime>, DecodeError> {
1790 self.peek_raw_pts(cancel)
1791 }
1792
1793 pub(crate) fn peek_raw_pts(
1799 &mut self,
1800 cancel: &CancelToken,
1801 ) -> Result<Option<MediaTime>, DecodeError> {
1802 let Some(raw) = self.decode_raw_next(cancel)? else {
1803 return Ok(None);
1804 };
1805 let pts = self.raw_frame_pts(&raw);
1806 self.pending.push_front(raw);
1807 pts.map(Some)
1808 }
1809
1810 pub(crate) fn decode_raw_next(
1811 &mut self,
1812 cancel: &CancelToken,
1813 ) -> Result<Option<DecodedFrame>, DecodeError> {
1814 if cancel.is_cancelled() {
1815 return Err(DecodeError::Cancelled);
1816 }
1817 if let Some(frame) = self.pending.pop_front() {
1818 return Ok(Some(frame));
1819 }
1820 interrupt_on_cancel(&self.input, cancel);
1821 let mut budget = WorkBudget::new();
1822 let mut foreign = false;
1823 loop {
1824 if std::mem::take(&mut foreign) {
1826 if cancel.is_cancelled() {
1827 return Err(DecodeError::Cancelled);
1828 }
1829 } else {
1830 budget.step(cancel)?;
1831 }
1832 if let Some(frame) = self.pending.pop_front() {
1833 return Ok(Some(frame));
1834 }
1835 if let Some(frame) = self.receive_available_raw(cancel)? {
1836 return Ok(Some(frame));
1837 }
1838 if self.demux_eof {
1839 if !self.decoder_flushed {
1840 match self.decoder.send_packet(None) {
1841 Ok(()) | Err(RsmpegError::DecoderFlushedError) => {}
1842 Err(RsmpegError::DecoderFullError) => continue,
1843 Err(error) => {
1844 self.recovery.error(error, "flush", None)?;
1845 continue;
1846 }
1847 }
1848 self.decoder_flushed = true;
1849 continue;
1850 }
1851 self.recovery.video_eof()?;
1852 return Ok(None);
1853 }
1854 let demux_started = Instant::now();
1855 let packet = self
1856 .prefetched
1857 .pop_front()
1858 .unwrap_or_else(|| self.input.read_packet());
1859 self.stages.demux = self.stages.demux.saturating_add(demux_started.elapsed());
1860 #[cfg(test)]
1861 take_read_delay();
1862 let packet = match packet {
1863 Ok(Some(packet)) => packet,
1864 Ok(None) => {
1865 self.demux_eof = true;
1866 continue;
1867 }
1868 Err(error) => {
1869 let error = demux_failure(&self.input, error, cancel)?;
1870 self.recovery.error(error, "video demux", None)?;
1871 continue;
1872 }
1873 };
1874 if usize::try_from(packet.stream_index).ok() != Some(self.video_index) {
1875 foreign = true;
1876 continue;
1877 }
1878 budget.advanced();
1879 if packet.flags & i32::try_from(ffi::AV_PKT_FLAG_CORRUPT).expect("flag fits i32") != 0 {
1880 self.recovery
1881 .corrupt("video packet", crate::recovery::pts(packet.pts))?;
1882 continue;
1883 }
1884 submit_packet(
1885 |drain| {
1886 if drain {
1887 let corrupt_before = self.recovery.diagnostics.corrupt_packets.len();
1888 if let Some(frame) = self.receive_available_raw(cancel)? {
1889 self.pending.push_back(frame);
1890 return Ok(true);
1891 }
1892 return Ok(self.recovery.diagnostics.corrupt_packets.len() > corrupt_before);
1893 }
1894 let started = Instant::now();
1895 let sent = self.decoder.send_packet(Some(&packet));
1896 self.stages.send_packet += started.elapsed();
1897 match sent {
1898 Ok(()) => Ok(true),
1899 Err(RsmpegError::DecoderFullError) => Ok(false),
1900 Err(error) => {
1901 self.recovery.error(error, "video send", Some(packet.pts))?;
1902 Ok(true)
1903 }
1904 }
1905 },
1906 &mut budget,
1907 cancel,
1908 )?;
1909 }
1910 }
1911}
1912
1913impl Decoder for NativeDecoder {
1914 fn streams(&self) -> &[StreamInfo] {
1915 &self.streams
1916 }
1917
1918 fn flush(&mut self) -> Result<(), DecodeError> {
1919 self.flush_video();
1920 Ok(())
1921 }
1922
1923 fn seek(
1924 &mut self,
1925 request: DecodeRequest,
1926 cancel: &CancelToken,
1927 ) -> Result<DecodeResult, DecodeError> {
1928 let raw = self.seek_raw(request.time, cancel)?;
1929 let frame = self.convert_received(&raw)?;
1930 Ok(DecodeResult {
1931 request,
1932 event: DecodeEvent::Video(frame),
1933 })
1934 }
1935
1936 fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError> {
1937 if cancel.is_cancelled() {
1938 return Err(DecodeError::Cancelled);
1939 }
1940 match self.decode_raw_next(cancel)? {
1941 Some(frame) => Ok(DecodeEvent::Video(self.convert_received(&frame)?)),
1942 None => Ok(DecodeEvent::EndOfStream),
1943 }
1944 }
1945}
1946
1947const HWACCEL_ONLY_DECODERS: &[&str] = &["av1"];
1950
1951pub(crate) fn registered_video_decoders(
1955 codec_id: ffi::AVCodecID,
1956) -> impl Iterator<Item = AVCodecRef<'static>> {
1957 AVCodec::iterate().filter(move |codec| {
1958 codec.id == codec_id
1959 && AVCodec::find_decoder_by_name(codec.name())
1960 .is_some_and(|found| found.as_ptr() == codec.as_ptr())
1961 })
1962}
1963
1964pub(crate) fn software_video_decoder(
1966 codec_id: ffi::AVCodecID,
1967) -> Result<AVCodecRef<'static>, DecodeError> {
1968 let Some(preferred) = AVCodec::find_decoder(codec_id) else {
1969 return Err(DecodeError::Unsupported(
1970 "selected video codec has no decoder".into(),
1971 ));
1972 };
1973 allowed_decoder(&preferred)?;
1974 let hardware_only =
1975 |codec: &AVCodecRef<'_>| HWACCEL_ONLY_DECODERS.contains(&&*codec.name().to_string_lossy());
1976 if !hardware_only(&preferred) {
1977 return Ok(preferred);
1978 }
1979 let experimental = i32::try_from(ffi::AV_CODEC_CAP_EXPERIMENTAL).unwrap_or(0);
1980 AVCodec::iterate()
1981 .find(|codec| {
1982 codec.id == codec_id
1983 && AVCodec::find_decoder_by_name(codec.name())
1984 .is_some_and(|found| found.as_ptr() == codec.as_ptr())
1985 && codec.capabilities & experimental == 0
1986 && !hardware_only(codec)
1987 })
1988 .ok_or_else(|| DecodeError::Unsupported(hardware_only_reason(&preferred)))
1989}
1990
1991const NO_LIBVPX_VP9: &str = "this FFmpeg runtime has no libvpx-vp9 decoder";
1992const HEVC_ALPHA_NOT_DECODED: &str = "alpha in an HEVC auxiliary layer is not decoded";
1993
1994fn libvpx_vp9() -> Option<AVCodecRef<'static>> {
1996 #[cfg(test)]
1997 if WITHOUT_LIBVPX_VP9.with(std::cell::Cell::get) {
1998 return None;
1999 }
2000 AVCodec::find_decoder_by_name(c"libvpx-vp9")
2001}
2002
2003#[must_use]
2005pub fn decodes_vp9_alpha() -> bool {
2006 libvpx_vp9().is_some()
2007}
2008
2009#[must_use]
2011pub fn alpha_dropped_reason(stream: &StreamInfo) -> Option<&'static str> {
2012 match stream.alpha? {
2013 SourceAlpha::Vp9SideData => libvpx_vp9().is_none().then_some(NO_LIBVPX_VP9),
2014 SourceAlpha::HevcAuxiliaryLayer => Some(HEVC_ALPHA_NOT_DECODED),
2015 SourceAlpha::Planar => None,
2016 }
2017}
2018
2019fn software_decoder_for(
2024 parameters: &rsmpeg::avcodec::AVCodecParameters,
2025 alpha: Option<SourceAlpha>,
2026) -> Result<(AVCodecRef<'static>, Option<DroppedLayer>), DecodeError> {
2027 let codec = software_video_decoder(parameters.codec_id)?;
2028 let dropped = |code, reason: &str| {
2029 Some(DroppedLayer {
2030 code,
2031 reason: reason.to_owned(),
2032 })
2033 };
2034 match alpha {
2035 Some(SourceAlpha::Vp9SideData) => Ok(match libvpx_vp9() {
2036 Some(libvpx) => (libvpx, None),
2037 None => (codec, dropped("alpha-dropped", NO_LIBVPX_VP9)),
2038 }),
2039 Some(SourceAlpha::HevcAuxiliaryLayer) => {
2040 Ok((codec, dropped("alpha-dropped", HEVC_ALPHA_NOT_DECODED)))
2041 }
2042 _ if parameters.codec_id == ffi::AV_CODEC_ID_HEVC
2043 && alpha2_host_core::parameter_sets::hevc_layers(
2044 &alpha2_ffmpeg_bridge::codec_parameters_extradata(parameters),
2045 ) == Some(alpha2_host_core::parameter_sets::HevcLayers::Extra) =>
2046 {
2047 Ok((
2048 codec,
2049 dropped(
2050 "extra-layers-dropped",
2051 "the HEVC layers besides the base layer are not decoded",
2052 ),
2053 ))
2054 }
2055 _ => Ok((codec, None)),
2056 }
2057}
2058
2059fn source_alpha(
2062 metadata: Option<rsmpeg::avutil::AVDictionaryRef<'_>>,
2063 parameters: &rsmpeg::avcodec::AVCodecParameters,
2064) -> Option<SourceAlpha> {
2065 let tagged = || {
2066 metadata
2067 .and_then(|metadata| {
2068 metadata
2069 .get(c"alpha_mode", None, 0)
2070 .map(|entry| entry.value().to_bytes() == b"1")
2071 })
2072 .unwrap_or(false)
2073 };
2074 match parameters.codec_id {
2075 ffi::AV_CODEC_ID_VP9 if tagged() => return Some(SourceAlpha::Vp9SideData),
2076 ffi::AV_CODEC_ID_HEVC
2077 if alpha2_host_core::parameter_sets::hevc_layers(
2078 &alpha2_ffmpeg_bridge::codec_parameters_extradata(parameters),
2079 ) == Some(alpha2_host_core::parameter_sets::HevcLayers::AuxiliaryAlpha) =>
2080 {
2081 return Some(SourceAlpha::HevcAuxiliaryLayer);
2082 }
2083 _ => {}
2084 }
2085 alpha2_ffmpeg_bridge::sample_profile(parameters.format)
2086 .filter(|profile| profile.has_alpha)
2087 .map(|_| SourceAlpha::Planar)
2088}
2089
2090fn hardware_only_reason(decoder: &AVCodecRef<'_>) -> String {
2091 let name = decoder.name().to_string_lossy();
2092 format!(
2093 "{name} needs a hardware decoder; this runtime has no software {} decoder",
2094 name.to_uppercase()
2095 )
2096}
2097
2098#[must_use]
2101pub fn software_decode_unsupported(stream: &StreamInfo) -> Option<String> {
2102 if stream.kind != StreamKind::Video {
2103 return None;
2104 }
2105 let name = CString::new(stream.codec.as_str()).ok()?;
2106 let decoder = AVCodec::find_decoder_by_name(&name)?;
2107 software_video_decoder(decoder.id)
2108 .err()
2109 .map(|error| match error {
2110 DecodeError::Unsupported(reason) => reason,
2111 error => error.to_string(),
2112 })
2113}
2114
2115pub(crate) fn effective_media_duration(
2117 stream_duration: Option<MediaTime>,
2118 container_duration: Option<MediaTime>,
2119) -> Option<MediaTime> {
2120 stream_duration.into_iter().chain(container_duration).max()
2121}
2122
2123fn decoded_frame_bytes(format: i32, (width, height): (u32, u32)) -> Option<u64> {
2125 let size = rsmpeg::avutil::AVImage::get_buffer_size(
2126 format,
2127 i32::try_from(width).ok()?,
2128 i32::try_from(height).ok()?,
2129 1,
2130 )?;
2131 u64::try_from(size).ok().filter(|bytes| *bytes > 0)
2132}
2133
2134#[cfg(all(
2136 any(target_os = "linux", target_os = "macos", target_os = "windows"),
2137 feature = "hwdecode"
2138))]
2139const fn hardware_codec_name(codec_id: ffi::AVCodecID) -> Option<&'static str> {
2140 match codec_id {
2141 ffi::AV_CODEC_ID_H264 => Some("h264"),
2142 ffi::AV_CODEC_ID_HEVC => Some("hevc"),
2143 ffi::AV_CODEC_ID_VP9 => Some("vp9"),
2144 ffi::AV_CODEC_ID_AV1 => Some("av1"),
2145 _ => None,
2146 }
2147}
2148
2149#[cfg(all(
2152 any(target_os = "linux", target_os = "macos", target_os = "windows"),
2153 feature = "hwdecode"
2154))]
2155fn check_hardware_crop(
2156 parameters: &rsmpeg::avcodec::AVCodecParameters,
2157 spec: &HardwareDecoderSpec<'_>,
2158) -> Result<(), HardwareOpenError> {
2159 if spec.keeps_leading_crop {
2160 return Ok(());
2161 }
2162 let extradata = alpha2_ffmpeg_bridge::codec_parameters_extradata(parameters);
2163 let codec = match parameters.codec_id {
2164 ffi::AV_CODEC_ID_H264 => Some(alpha2_host_core::parameter_sets::ParameterSetCodec::H264),
2165 ffi::AV_CODEC_ID_HEVC => Some(alpha2_host_core::parameter_sets::ParameterSetCodec::Hevc),
2166 _ => None,
2167 };
2168 match codec.and_then(|codec| alpha2_host_core::parameter_sets::leading_crop(codec, &extradata))
2169 {
2170 Some((left, top)) if left > 0 || top > 0 => Err(HardwareOpenError::new(
2171 crate::video_frame::HardwareDecodeFallback::UnsupportedCrop,
2172 DecodeError::Unsupported(format!(
2173 "{} decode does not show a picture cropped {left} columns from the left and {top} rows from the top",
2174 spec.backend
2175 )),
2176 )),
2177 _ => Ok(()),
2178 }
2179}
2180
2181#[cfg(all(
2186 any(target_os = "linux", target_os = "macos", target_os = "windows"),
2187 feature = "hwdecode"
2188))]
2189fn check_hardware_sample_profile(
2190 format: ffi::AVPixelFormat,
2191 spec: &HardwareDecoderSpec<'_>,
2192) -> Result<(), HardwareOpenError> {
2193 let Some(profile) = alpha2_ffmpeg_bridge::sample_profile(format) else {
2194 return Ok(());
2195 };
2196 let maximum_depth = if spec.ten_bit { 10 } else { 8 };
2197 if profile.is_yuv_420 && !profile.has_alpha && profile.bit_depth <= maximum_depth {
2198 return Ok(());
2199 }
2200 Err(HardwareOpenError::new(
2201 crate::video_frame::HardwareDecodeFallback::UnsupportedProfile,
2202 DecodeError::Unsupported(format!(
2203 "{} decode does not present {}-bit {} input",
2204 spec.backend,
2205 profile.bit_depth,
2206 if profile.is_yuv_420 {
2207 "4:2:0"
2208 } else {
2209 "non-4:2:0"
2210 }
2211 )),
2212 ))
2213}
2214
2215pub(crate) const SOURCE_CONTAINERS: &CStr =
2219 c"mov,matroska,mpegts,avi,mp3,aac,wav,flac,ogg,png_pipe,jpeg_pipe,webp_pipe,gif";
2220
2221pub const SOURCE_DECODERS: &[&str] = &[
2225 "h264",
2227 "hevc",
2228 "vp8",
2229 "vp9",
2230 "libvpx-vp9",
2231 "av1",
2232 "libdav1d",
2233 "mpeg4",
2234 "mpeg2video",
2235 "mpeg1video",
2236 "prores",
2237 "dnxhd",
2238 "ffv1",
2239 "v210",
2240 "mjpeg",
2241 "qtrle",
2242 "rawvideo",
2243 "png",
2244 "webp",
2245 "gif",
2246 "aac",
2248 "aac_latm",
2249 "mp3float",
2250 "mp3",
2251 "mp2",
2252 "mp2float",
2253 "opus",
2254 "libopus",
2255 "vorbis",
2256 "flac",
2257 "alac",
2258 "ac3",
2259 "eac3",
2260 "dca",
2261 "pcm_s16le",
2262 "pcm_s16be",
2263 "pcm_s24le",
2264 "pcm_s24be",
2265 "pcm_s32le",
2266 "pcm_s32be",
2267 "pcm_f32le",
2268 "pcm_f32be",
2269 "pcm_f64le",
2270 "pcm_f64be",
2271 "pcm_u8",
2272 "pcm_s8",
2273 "pcm_alaw",
2274 "pcm_mulaw",
2275];
2276
2277static EVERY_DECODER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
2278
2279pub fn allow_every_decoder() {
2282 EVERY_DECODER.store(true, std::sync::atomic::Ordering::Relaxed);
2283}
2284
2285#[cfg(test)]
2286pub(crate) fn set_every_decoder(every: bool) {
2287 EVERY_DECODER.store(every, std::sync::atomic::Ordering::Relaxed);
2288}
2289
2290#[must_use]
2292pub fn every_decoder_allowed() -> bool {
2293 EVERY_DECODER.load(std::sync::atomic::Ordering::Relaxed)
2294}
2295
2296#[must_use]
2298pub fn source_decoders() -> Vec<&'static str> {
2299 SOURCE_DECODERS
2300 .iter()
2301 .copied()
2302 .filter(|name| {
2303 CString::new(*name)
2304 .ok()
2305 .and_then(|name| AVCodec::find_decoder_by_name(&name))
2306 .is_some()
2307 })
2308 .collect()
2309}
2310
2311pub(crate) fn allowed_decoder(codec: &AVCodecRef<'_>) -> Result<(), DecodeError> {
2313 let name = codec.name().to_string_lossy();
2314 if every_decoder_allowed() || SOURCE_DECODERS.contains(&&*name) {
2315 Ok(())
2316 } else {
2317 Err(DecodeError::Unsupported(format!(
2318 "the {name} decoder is not one alpha2 decodes sources with"
2319 )))
2320 }
2321}
2322
2323fn decoder_whitelist() -> Option<&'static CStr> {
2325 static LIST: std::sync::OnceLock<CString> = std::sync::OnceLock::new();
2326 (!every_decoder_allowed()).then(|| {
2327 LIST.get_or_init(|| {
2328 CString::new(SOURCE_DECODERS.join(",")).expect("decoder names have no NUL")
2329 })
2330 .as_c_str()
2331 })
2332}
2333
2334pub(crate) fn open_input(source: &SourceLocation) -> Result<DemuxInput, DecodeError> {
2338 #[cfg(test)]
2339 INPUTS_OPENED.with(|opened| opened.set(opened.get() + 1));
2340 refuse_oversized_still(source)?;
2341 let opened = match source {
2342 SourceLocation::File(path) => alpha2_ffmpeg_bridge::open_input(
2343 InputLocation::File(path),
2344 SOURCE_CONTAINERS,
2345 decoder_whitelist(),
2346 ),
2347 SourceLocation::Remote(object) => {
2348 let open =
2349 || -> std::io::Result<Box<dyn InputReader>> { Ok(Box::new(object.reader())) };
2350 let shown = object.shown_url();
2351 let custom = CustomInput {
2352 name: shown.rsplit('/').next().unwrap_or(shown),
2353 length: object.len(),
2354 open: &open,
2355 };
2356 alpha2_ffmpeg_bridge::open_input(
2357 InputLocation::Custom(&custom),
2358 SOURCE_CONTAINERS,
2359 decoder_whitelist(),
2360 )
2361 }
2362 };
2363 opened.map_err(|error| match error {
2364 OpenInputError::Path(error) => DecodeError::Unsupported(format!("media path {error}")),
2365 OpenInputError::Refused(format) => DecodeError::Unsupported(format!(
2366 "the file is {format} input, which is not a container alpha2 reads"
2367 )),
2368 OpenInputError::Read(error) => read_failure(&error),
2369 OpenInputError::Ffmpeg(error) => adapter_error(error),
2370 })
2371}
2372
2373fn read_failure(error: &std::io::Error) -> DecodeError {
2375 alpha2_host_core::remote::decode_error(error)
2376 .unwrap_or_else(|| DecodeError::Adapter(format!("the source could not be read: {error}")))
2377}
2378
2379pub(crate) fn demux_error(input: &DemuxInput, error: RsmpegError) -> DecodeError {
2381 input
2382 .take_read_error()
2383 .map_or_else(|| adapter_error(error), |failure| read_failure(&failure))
2384}
2385
2386fn source_head(source: &SourceLocation, limit: u64) -> Option<Vec<u8>> {
2388 let mut head = Vec::new();
2389 match source {
2390 SourceLocation::File(path) => {
2391 std::fs::File::open(path)
2392 .ok()?
2393 .take(limit)
2394 .read_to_end(&mut head)
2395 .ok()?;
2396 }
2397 SourceLocation::Remote(object) => {
2398 object.reader().take(limit).read_to_end(&mut head).ok()?;
2399 }
2400 }
2401 Some(head)
2402}
2403
2404fn refuse_oversized_still(source: &SourceLocation) -> Result<(), DecodeError> {
2407 const HEAD_BYTES: u64 = 1 << 20;
2409 let Some(signature) = source_head(source, 12) else {
2410 return Ok(());
2411 };
2412 if still_format(&signature).is_none() {
2413 return Ok(());
2414 }
2415 let Some(head) = source_head(source, HEAD_BYTES) else {
2416 return Ok(());
2417 };
2418 match probe_still(&head) {
2419 Err(error @ DecodeError::Unsupported(_)) => Err(error),
2420 _ => Ok(()),
2421 }
2422}
2423
2424#[cfg(test)]
2425thread_local! {
2426 pub(crate) static INPUTS_OPENED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2428 pub(crate) static VIDEO_FRAMES_DECODED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2430}
2431
2432pub(crate) fn interrupt_on_cancel(input: &DemuxInput, cancel: &CancelToken) {
2434 let cancel = cancel.clone();
2435 input.interrupt_when(move || cancel.is_cancelled());
2436}
2437
2438fn demux_failure(
2441 input: &DemuxInput,
2442 error: RsmpegError,
2443 cancel: &CancelToken,
2444) -> Result<RsmpegError, DecodeError> {
2445 if cancel.is_cancelled() {
2446 return Err(DecodeError::Cancelled);
2447 }
2448 match input.take_read_error() {
2449 Some(failure) => Err(read_failure(&failure)),
2450 None => Ok(error),
2451 }
2452}
2453
2454fn seek_failure(input: &DemuxInput, error: RsmpegError, cancel: &CancelToken) -> DecodeError {
2456 demux_failure(input, error, cancel).map_or_else(|failure| failure, adapter_error)
2457}
2458
2459const STILL_IMAGE_FORMATS: [&CStr; 3] = [c"jpeg_pipe", c"png_pipe", c"webp_pipe"];
2462
2463fn is_still_image_format(input: &DemuxInput) -> bool {
2464 STILL_IMAGE_FORMATS.contains(&input.iformat().name())
2465}
2466
2467fn still_image_orientation(source: &SourceLocation, index: usize) -> Option<Orientation> {
2470 let mut input = open_input(source).ok()?;
2471 let (codec, mut decoder) = {
2472 let stream = input.streams().get(index)?;
2473 let parameters = stream.codecpar();
2474 let codec = software_video_decoder(parameters.codec_id).ok()?;
2475 let mut decoder = AVCodecContext::new(&codec);
2476 decoder.apply_codecpar(¶meters).ok()?;
2477 decoder.set_pkt_timebase(stream.time_base);
2478 (codec, decoder)
2479 };
2480 let mut options = video_decoder_options(1);
2481 if codec.max_lowres > 0 {
2482 options = options.set_int(c"lowres", i64::from(codec.max_lowres), 0);
2483 }
2484 alpha2_ffmpeg_bridge::open_codec_context(&mut decoder, options).ok()?;
2485 let mut sent = false;
2486 for _ in 0..16 {
2488 match decoder.receive_frame() {
2489 Ok(frame) => {
2490 return alpha2_ffmpeg_bridge::frame_display_rotation(&frame)
2491 .and_then(orientation_from_display);
2492 }
2493 Err(RsmpegError::DecoderDrainError) => {}
2494 Err(_) => return None,
2495 }
2496 match input.read_packet().ok()? {
2497 Some(packet) if usize::try_from(packet.stream_index).ok() == Some(index) => {
2498 decoder.send_packet(Some(&packet)).ok()?;
2499 sent = true;
2500 }
2501 Some(_) => {}
2502 None if sent => {
2503 decoder.send_packet(None).ok()?;
2504 sent = false;
2505 }
2506 None => return None,
2507 }
2508 }
2509 None
2510}
2511
2512#[allow(clippy::too_many_lines)]
2513const PARSED_END_READ: u64 = 250_000;
2516
2517fn parsed_end(input: &DemuxInput, source: &SourceLocation) -> Option<i64> {
2524 if input.duration_estimation_method != ffi::AVFMT_DURATION_FROM_PTS {
2525 return None;
2526 }
2527 let size = source.byte_length().ok()?;
2528 let mut tail = open_input(source).ok()?;
2529 let streams = tail
2530 .streams()
2531 .iter()
2532 .map(|stream| {
2533 let kind = stream.codecpar().codec_type();
2534 (kind.is_audio() || kind.is_video()).then_some(stream.time_base)
2535 })
2536 .collect::<Vec<_>>();
2537 let av_time_base = ra(1, i32::try_from(ffi::AV_TIME_BASE).ok()?);
2538 for doubling in 0..6 {
2539 let from = size.saturating_sub(PARSED_END_READ << doubling);
2540 tail.seek(
2541 -1,
2542 i64::try_from(from).ok()?,
2543 i32::try_from(ffi::AVSEEK_FLAG_BYTE).ok()?,
2544 )
2545 .ok()?;
2546 let mut end = None::<i64>;
2547 while let Ok(Some(packet)) = tail.read_packet() {
2548 let Some(Some(time_base)) = usize::try_from(packet.stream_index)
2549 .ok()
2550 .and_then(|index| streams.get(index))
2551 else {
2552 continue;
2553 };
2554 if packet.pts == ffi::AV_NOPTS_VALUE {
2555 continue;
2556 }
2557 let packet_end = av_rescale_q(
2558 packet.pts.saturating_add(packet.duration.max(0)),
2559 *time_base,
2560 av_time_base,
2561 );
2562 end = Some(end.map_or(packet_end, |end: i64| end.max(packet_end)));
2563 }
2564 if end.is_some() || from == 0 {
2565 return end;
2566 }
2567 }
2568 None
2569}
2570
2571fn guessed_frame_rate(stream: &rsmpeg::avformat::AVStreamRef<'_>) -> Option<FrameRate> {
2572 stream
2573 .guess_framerate()
2574 .filter(|rate| rate.num > 0 && rate.den > 0)
2575 .and_then(|rate| {
2576 FrameRate::new(u32::try_from(rate.num).ok()?, u32::try_from(rate.den).ok()?).ok()
2577 })
2578}
2579
2580fn metadata_text(
2582 metadata: Option<rsmpeg::avutil::AVDictionaryRef<'_>>,
2583 key: &std::ffi::CStr,
2584) -> Option<String> {
2585 let metadata = metadata?;
2586 let entry = metadata.get(key, None, 0)?;
2587 let value = entry.value().to_string_lossy().trim().to_owned();
2588 (!value.is_empty()).then_some(value)
2589}
2590
2591fn decoder_allowed(input: &DemuxInput, index: usize) -> bool {
2593 input.streams().get(index).is_some_and(|stream| {
2594 AVCodec::find_decoder(stream.codecpar().codec_id)
2595 .is_some_and(|codec| allowed_decoder(&codec).is_ok())
2596 })
2597}
2598
2599pub(crate) fn probe_context(
2601 input: &DemuxInput,
2602 source: &SourceLocation,
2603) -> Result<ProbeResult, DecodeError> {
2604 let selected_video = input
2605 .best_stream(ffi::AVMEDIA_TYPE_VIDEO)
2606 .map_err(adapter_error)?;
2607 let selected_audio = input
2609 .best_stream(ffi::AVMEDIA_TYPE_AUDIO)
2610 .map_err(adapter_error)?
2611 .filter(|&index| decoder_allowed(input, index));
2612 let streams = input
2613 .streams()
2614 .iter()
2615 .enumerate()
2616 .filter_map(|(index, stream)| {
2617 let parameters = stream.codecpar();
2618 let kind = if parameters.codec_type().is_video() {
2619 StreamKind::Video
2620 } else if parameters.codec_type().is_audio() {
2621 StreamKind::Audio
2622 } else {
2623 return None;
2624 };
2625 let codec = AVCodec::find_decoder(parameters.codec_id).map_or_else(
2626 || "unknown".to_owned(),
2627 |codec| codec.name().to_string_lossy().into_owned(),
2628 );
2629 let dimensions = (kind == StreamKind::Video).then(|| {
2630 (
2631 u32::try_from(parameters.width).unwrap_or(0),
2632 u32::try_from(parameters.height).unwrap_or(0),
2633 )
2634 });
2635 let frame_rate = guessed_frame_rate(stream);
2636 Some(StreamInfo {
2637 index,
2638 kind,
2639 codec,
2640 duration: timestamp(stream.duration, stream.time_base),
2641 dimensions,
2642 frame_rate,
2643 sample_rate: (parameters.sample_rate > 0)
2644 .then(|| u32::try_from(parameters.sample_rate).unwrap_or(0)),
2645 channels: (kind == StreamKind::Audio)
2646 .then(|| u32::try_from(parameters.ch_layout.nb_channels).unwrap_or(0)),
2647 orientation: alpha2_ffmpeg_bridge::display_rotation(¶meters)
2648 .and_then(orientation_from_display)
2649 .or_else(|| {
2650 (kind == StreamKind::Video
2651 && Some(index) == selected_video
2652 && is_still_image_format(input))
2653 .then(|| still_image_orientation(source, index))
2654 .flatten()
2655 })
2656 .unwrap_or_else(|| Orientation::rotated(stream_rotation(stream.metadata()))),
2657 sample_aspect_ratio: guess_sar(
2658 stream.sample_aspect_ratio,
2659 parameters.sample_aspect_ratio,
2660 ),
2661 color: if kind == StreamKind::Video {
2662 color_metadata(¶meters)
2663 } else {
2664 None
2665 },
2666 alpha: (kind == StreamKind::Video)
2667 .then(|| source_alpha(stream.metadata(), ¶meters))
2668 .flatten(),
2669 frame_bytes: dimensions
2670 .and_then(|size| decoded_frame_bytes(parameters.format, size)),
2671 language: metadata_text(stream.metadata(), c"language"),
2672 title: metadata_text(stream.metadata(), c"title"),
2673 })
2674 })
2675 .collect();
2676 let av_time_base = ra(
2677 1,
2678 i32::try_from(ffi::AV_TIME_BASE).expect("time base fits i32"),
2679 );
2680 let duration = parsed_end(input, source)
2681 .filter(|_| input.start_time != ffi::AV_NOPTS_VALUE)
2682 .map(|end| end.saturating_sub(input.start_time))
2683 .map_or(input.duration, |parsed| parsed.max(input.duration));
2684 Ok(ProbeResult {
2685 format: input.iformat().name().to_string_lossy().into_owned(),
2686 duration: (duration > 0)
2687 .then(|| MediaTime::from_ticks(av_rescale_q(duration, av_time_base, tick_base()))),
2688 start: (input.start_time != ffi::AV_NOPTS_VALUE).then(|| {
2689 MediaTime::from_ticks(av_rescale_q(
2690 input.start_time,
2691 ra(
2692 1,
2693 i32::try_from(ffi::AV_TIME_BASE).expect("time base fits i32"),
2694 ),
2695 tick_base(),
2696 ))
2697 }),
2698 streams,
2699 selected_video,
2700 selected_audio,
2701 })
2702}
2703
2704#[cfg(feature = "timeline")]
2706impl alpha2_host_core::audio_windows::WindowedAudioDecoder for NativeAudioDecoder {
2707 fn channels(&self) -> usize {
2708 Self::channels(self)
2709 }
2710
2711 fn speakers(&self) -> SpeakerLayout {
2712 Self::speakers(self)
2713 }
2714
2715 fn audio_duration(&self) -> Option<MediaTime> {
2716 Self::audio_duration(self)
2717 }
2718}