Skip to main content

alpha2_native/
decode.rs

1//! Container probing and the native audio/video decoders.
2
3use 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/// Container-level probe and deterministic stream selection.
47#[derive(Clone, Debug, PartialEq)]
48pub struct ProbeResult {
49    /// Demuxer name.
50    pub format: String,
51    /// Container duration from the first presentation to the end of the last; media
52    /// ends at `start + duration`.
53    pub duration: Option<MediaTime>,
54    /// The container's first presentation on the media's own timeline: zero for most files, later
55    /// for a transport stream or a delayed start.
56    pub start: Option<MediaTime>,
57    /// Every audio/video stream in demuxer order, other streams left out; look one up by
58    /// [`StreamInfo::index`], not by position.
59    pub streams: Vec<StreamInfo>,
60    /// The `AVStream` index of the video stream a reader shows (never an attached picture), `None`
61    /// when no video stream decodes.
62    pub selected_video: Option<usize>,
63    /// The `AVStream` index of the audio stream a reader plays, `None` when none decodes.
64    pub selected_audio: Option<usize>,
65}
66
67impl ProbeResult {
68    /// The entry of `streams` with `AVStream` index `index`.
69    #[must_use]
70    pub fn stream(&self, index: usize) -> Option<&StreamInfo> {
71        self.streams.iter().find(|stream| stream.index == index)
72    }
73
74    /// The selected video stream's entry.
75    #[must_use]
76    pub fn selected_video_stream(&self) -> Option<&StreamInfo> {
77        self.selected_video.and_then(|index| self.stream(index))
78    }
79
80    /// The selected audio stream's entry.
81    #[must_use]
82    pub fn selected_audio_stream(&self) -> Option<&StreamInfo> {
83        self.selected_audio.and_then(|index| self.stream(index))
84    }
85
86    /// The audio streams, in demuxer order; a clip's `audio.stream` counts over these.
87    pub fn audio_streams(&self) -> impl Iterator<Item = &StreamInfo> {
88        self.streams
89            .iter()
90            .filter(|stream| stream.kind == StreamKind::Audio)
91    }
92
93    /// The audio stream a clip's `audio.stream` of `ordinal` names.
94    #[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    /// The selected audio stream's position among [`Self::audio_streams`].
100    #[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
110/// Opens a local resource using the system `FFmpeg` 8 shared libraries.
111///
112/// # Errors
113/// Returns a platform-neutral adapter error for invalid paths or demux failures.
114pub 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
120/// Visits each packet time (seconds) of `AVStream` index `stream` in file order until `visit`
121/// returns false. Falls back to decode time; packets with neither are skipped. Nothing is decoded.
122///
123/// # Errors
124/// Returns why the file cannot be opened or read.
125pub 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)] // A packet time is far below 2^52 time-base units.
149        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
157/// Software video decoder with exact timestamp conversion and drain semantics.
158pub 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    /// The probed pixel aspect ratio: the container's declaration, else the codec parameters'.
167    pub(crate) sample_aspect_ratio: SampleAspectRatio,
168    /// The color the stream's tags describe, as probed.
169    pub(crate) color: Option<ColorMetadata>,
170    /// The project's declared color, which overrides every tag ([`Self::declare_color`]).
171    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    /// When the stream's first frame is presented, once a seek from its first packet decoded it.
178    first_video_pts: Option<MediaTime>,
179    recovery: Recovery,
180    /// How late a frame's timestamp may be and still be shown at a time
181    /// ([`Self::presentation_deadline`]).
182    slack: MediaTime,
183    /// Packets read ahead for [`Self::slack`], consumed before the demuxer until a seek drops them.
184    prefetched: Prefetched,
185    /// What this decoder does not decode of its stream (an alpha channel, extra layers).
186    dropped_layer: Option<DroppedLayer>,
187}
188
189/// Something a decoder leaves out of its stream (the frames still decode), for reports.
190#[derive(Clone, Debug, Eq, PartialEq)]
191pub struct DroppedLayer {
192    /// `alpha-dropped` or `extra-layers-dropped`.
193    pub code: &'static str,
194    /// Human-readable explanation.
195    pub reason: String,
196}
197
198#[cfg(test)]
199thread_local! {
200    /// How long the next video packet read on this thread takes, slept or added to the virtual
201    /// clock (`recovery::VIRTUAL_CLOCK`) when set.
202    pub(crate) static READ_DELAY: std::cell::Cell<std::time::Duration> =
203        const { std::cell::Cell::new(std::time::Duration::ZERO) };
204    /// Forces software VP9 opens on this thread onto `FFmpeg`'s own `vp9`, as without libvpx.
205    pub(crate) static WITHOUT_LIBVPX_VP9: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
206}
207
208/// Takes [`READ_DELAY`] once.
209#[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
223/// Packets read ahead from the demuxer, consumed before it until a seek drops them.
224type Prefetched = VecDeque<Result<Option<AVPacket>, RsmpegError>>;
225
226/// Reads stream `index`'s first packets (up to [`alpha2_time::ROUNDING_SCAN_FRAMES`] or
227/// [`alpha2_time::ROUNDING_SCAN_BYTES`]) and returns them with their presentation timestamps.
228///
229/// The decode replays these packets first, so the input never seeks back and a read failure
230/// surfaces where the decode meets it.
231fn 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
258/// The first packets of stream `video_index` and the presentation slack their timestamps show.
259fn 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(&timestamps),
269    );
270    (read, slack)
271}
272
273/// Where one video decode session's wall time went, split so hardware decode is told
274/// apart from mere submission.
275#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
276pub struct DecodeStageTimings {
277    /// `av_read_frame`: container demux and file I/O.
278    pub demux: Duration,
279    /// `avcodec_send_packet`: handing a packet to the codec.
280    pub send_packet: Duration,
281    /// `avcodec_receive_frame`: producing one picture. A hardware session waits here for `FFmpeg`'s
282    /// synchronization, so this separates decode from submission.
283    pub receive_frame: Duration,
284    /// Turning the picture into a host frame: pixel conversion (software) or
285    /// surface metadata (hardware).
286    pub convert: Duration,
287    /// `av_seek_frame` and the codec flush that follows it.
288    pub seek: Duration,
289}
290
291impl DecodeStageTimings {
292    /// Adds another session's spans to these, saturating on overflow.
293    #[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, with no read or seek since.
308    Opened,
309    Moved,
310}
311
312#[derive(Clone, Copy, PartialEq, Eq)]
313enum AudioContinuity {
314    Continuous,
315    Damaged,
316}
317
318/// Streaming `FFmpeg` audio decoder normalized to project-rate planar `f32`.
319///
320/// Blocks keep the stream's channel order ([`NativeAudioDecoder::speakers`]). `swresample` converts
321/// each frame to `f32` at its own rate, rematrixing only a frame whose layout differs from the
322/// stream's; the source timeline places it by timestamp and `alpha2_audio::Resampler` (shared with
323/// the browser host) brings it to the project rate.
324pub 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    /// Converts sample format, and the layout of a frame unlike the stream's; never the rate.
334    converter: Option<SwrContext>,
335    pub(crate) sample_rate: u32,
336    pub(crate) channel_count: usize,
337    /// The speakers the stream declares, or its count's default.
338    speakers: SpeakerLayout,
339    /// Whether the stream declared no speaker and `speakers` is assumed.
340    speakers_assumed: bool,
341    /// `speakers` as `FFmpeg`'s layout: what every frame is converted to.
342    output_layout: AVChannelLayout,
343    /// The decoded source, placed and not yet resampled.
344    timeline: SourceTimeline,
345    pub(crate) pending: Vec<VecDeque<f32>>,
346    /// Source-timeline index, at the output rate, of the first pending sample; `None` until a
347    /// frame's timestamp places it.
348    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    /// How a demuxer's made-up timestamps (raw ADTS) compare with the audio; `None` when
355    /// the container has real ones.
356    made_up: Option<MadeUpTimestamps>,
357    /// The source rate and frame grid of the stream's first timestamps
358    /// ([`alpha2_time::audio_frame_grid`]), used to place the first frame after an open or seek.
359    grid: Option<(u32, alpha2_time::AudioFrameGrid)>,
360    /// Packets read ahead for [`Self::grid`], consumed before the demuxer until a seek drops them.
361    prefetched: Prefetched,
362    /// Frames placed since open; placing one counts as progress before the target is reached.
363    frames_placed: u64,
364    /// The codec's seek pre-roll, in ticks.
365    seek_preroll: i64,
366}
367
368/// The `AVStream` index of audio stream `stream` ([`ProbeResult::audio_stream`]), or of the
369/// selected one for `None`.
370fn 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
387/// Timestamps a demuxer made up by counting each packet's samples at one rate.
388struct MadeUpTimestamps {
389    /// The stream's first rate, which every packet is counted at.
390    rate: u32,
391    /// How far the timestamps have run ahead of the decoded frames since the last restart,
392    /// in the stream's time base.
393    drift: i64,
394    /// Whether a frame came at another rate, after which the timestamps no longer match the audio.
395    rate_changed: bool,
396}
397
398/// How far before a seek target decoding restarts.
399///
400/// A decoder resuming mid-stream lacks history (AAC's first frame misses the previous overlap), so
401/// decoding from 100 ms early and discarding up to the target matches a straight decode.
402const AUDIO_SEEK_PREROLL_TICKS: i64 = TICKS_PER_SECOND / 10;
403
404/// How far before a seek target decoding restarts in Opus (400 ms).
405///
406/// RFC 7845 asks for at least 80 ms, but the decoder converges slowly: the target's samples are
407/// still 2e-2 off from 100 ms, 1e-4 from 250 ms and under 1e-6 from 400 ms.
408const OPUS_SEEK_PREROLL_TICKS: i64 = TICKS_PER_SECOND * 2 / 5;
409
410impl NativeAudioDecoder {
411    /// Selects strict failure (default) or bounded, reported recovery.
412    pub fn set_decode_policy(&mut self, policy: DecodePolicy) {
413        self.recovery.policy = policy;
414    }
415
416    /// Receives each diagnostic before recovery continues, including before errors.
417    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    /// Cumulative corruption and concealment diagnostics, including seeks.
425    #[must_use]
426    pub fn decode_diagnostics(&self) -> &DecodeDiagnostics {
427        &self.recovery.diagnostics
428    }
429
430    /// Decodes the selected audio stream through the linked `FFmpeg` 8 libraries.
431    ///
432    /// # Errors
433    /// Returns a platform-neutral error for invalid rates, missing streams, unsupported layouts,
434    /// codec failures, or malformed decoded audio.
435    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    /// Decodes audio stream `stream`, counted over the file's audio streams in demuxer order
443    /// ([`ProbeResult::audio_stream`]); `None` decodes the selected one, as [`Self::open`] does.
444    ///
445    /// # Errors
446    /// As [`Self::open`], and `Unsupported` when the file has no such audio stream.
447    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        // ADTS has no timestamps: the `aac` demuxer counts each packet as `frame_size` samples at
484        // the starting rate, whatever rate a later header names.
485        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        // Made-up timestamps count samples exactly, so there is no rounding grid.
495        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                    &timestamps,
501                    i64::from(time_base.num),
502                    i64::from(time_base.den),
503                    rate,
504                )
505                .map(|grid| (rate, grid))
506            });
507        // Channels keep the stream's layout; the engine folds them by speaker. The layout comes
508        // from the decoder, else the container, else the count's default.
509        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    /// Sets the maximum observable block size returned by `decode_next`.
555    ///
556    /// # Errors
557    /// Returns [`DecodeError::OutOfRange`] for zero frames.
558    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    /// Channels of every block this decoder returns: the source's, 1 to [`MAX_AUDIO_CHANNELS`].
567    #[must_use]
568    pub const fn channels(&self) -> usize {
569        self.channel_count
570    }
571
572    /// The speaker each plane feeds: the stream's declared layout, or its count's default.
573    #[must_use]
574    pub const fn speakers(&self) -> SpeakerLayout {
575        self.speakers
576    }
577
578    /// Whether the stream declares no layout, so [`Self::speakers`] is a default.
579    #[must_use]
580    pub const fn speakers_assumed(&self) -> bool {
581        self.speakers_assumed
582    }
583
584    /// Effective end of the selected audio source.
585    ///
586    /// Containers often declare a slightly longer duration than the stream (priming,
587    /// time-base rounding). Projects authored in a browser use the container duration, so it
588    /// is kept as the source boundary.
589    #[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    /// The selected stream's first timestamp in its time base, or zero when unknown.
601    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    /// The most decoded samples per channel held at once since the last open or seek.
611    #[cfg(test)]
612    pub(crate) const fn peak_held_samples(&self) -> usize {
613        self.timeline.peak_held()
614    }
615
616    /// Goes back to the stream's first packet. An untouched input replays [`Self::prefetched`]; any
617    /// other is reopened, since a raw elementary stream cannot seek before its first packet.
618    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    /// Forgets everything decoded; the next output is no earlier than `first`.
633    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    /// The real time of a frame whose demuxer made up `pts` by counting every earlier packet at the
654    /// stream's first rate. Other streams return `pts` unchanged.
655    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        // The demuxer's duration rounds down (`compute_pkt_fields`); the
669        // frame's own rounds to nearest.
670        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        // A decoder may change rate mid-stream, so check the frame's own rate.
713        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    /// The frame as `f32` planes feeding [`Self::speakers`], at its own rate.
722    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        // At one rate `swresample` holds nothing back: what goes in comes out.
740        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    /// Places one decoded frame where its timestamp says.
754    ///
755    /// A timestamp within a frame duration, 2 ms, or two time-base units of the previous end
756    /// continues it, since containers round timestamps (Matroska to the millisecond) and the
757    /// browser demuxer ignores sub-frame jumps. Further ahead is a silent gap; further back repeats
758    /// samples, which are dropped. After damage the timestamp is trusted exactly.
759    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            // Snap the first frame after an open or seek to the stream's grid, so it lands where
780            // a straight decode puts it.
781            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        // One time-base unit in source samples, rounded up; 2 ms likewise.
817        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            // A placed frame is progress even before it reaches the output, so a long
861            // seek decode is not cut short.
862            if self.frames_placed != placed {
863                placed = self.frames_placed;
864                budget.progressed();
865            }
866            // Skipped packets of other streams are not progress: a demuxer that ignores the
867            // discard still reads them.
868            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                    // Damage running to the end (Tolerant only) ends the stream at its last healthy
899                    // frame; the damage is already reported.
900                    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        // Raw elementary streams (MP3, ADTS AAC, AC-3) index from the first packet, so a pre-roll
986        // seek before the start fails with -1 (EPERM); reopen instead. The same applies when a rate
987        // change has put the made-up timestamps off the audio.
988        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            // The seek landed past a rate change the made-up timestamps hide.
1009            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
1049/// Opens the decoder for stream `stream_index` and discards every other stream.
1050fn 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(&parameters).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
1070/// Accepted source sample rates (1 kHz to 768 kHz, the `alpha2_audio::Resampler` range).
1071pub 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
1084/// Converts a frame to packed `f32` in the stream's layout `output`, keeping its rate; a frame with
1085/// a different layout is rematrixed.
1086pub(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    // Borrowed, never cloned: rsmpeg 0.18's `AVChannelLayout::clone` copies into uninitialized
1096    // memory that `av_channel_layout_copy` first frees.
1097    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
1111/// The speaker each channel of `layout` feeds; all [`Speaker::Unnamed`] for a count-only layout.
1112pub(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
1123/// `speakers` as an `FFmpeg` layout: native order when possible, custom otherwise.
1124pub(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
1154/// Gives a frame whose layout names no speakers (`UNSPEC`, `AMBISONIC`, or a custom order with
1155/// unknown channels) the layout it is converted to, so `swresample` copies it channel for channel.
1156///
1157/// With the stream's count that is the stream's layout; with another count it is that count's
1158/// default, rematrixed where possible. Left `UNSPEC`, `swresample` would resolve the input itself,
1159/// see a format change and return `AVERROR_INPUT_CHANGED` on every retry.
1160pub(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
1220/// Whether an `AVCodecHWConfig`'s `methods` include `method`.
1221///
1222/// `bindgen` types the enum constants unsigned on Linux, macOS and `MinGW` and `int` on MSVC,
1223/// so both sides are widened.
1224pub(crate) fn has_hw_config_method(methods: i32, method: impl Into<i64>) -> bool {
1225    i64::from(methods) & method.into() != 0
1226}
1227
1228/// A seek position below any indexed timestamp, for reading from a stream's first packet.
1229///
1230/// MPEG-TS needs it because its first packet's decode time precedes the stream start time. A
1231/// demuxer that refuses such a time (the generic search AVI uses) is sought to the start time.
1232const STREAM_START_SEEK: i64 = i64::MIN / 2;
1233
1234enum Landing {
1235    /// The frame presented at the time.
1236    Presented(DecodedFrame),
1237    /// The first frame decoded was already later than the time.
1238    Late(DecodedFrame),
1239    /// No frame before the end of the stream.
1240    Empty,
1241}
1242
1243impl NativeDecoder {
1244    /// Selects strict failure (default) or bounded, reported recovery.
1245    pub fn set_decode_policy(&mut self, policy: DecodePolicy) {
1246        self.recovery.policy = policy;
1247    }
1248
1249    /// Sets the project's declared color for this source, which replaces the frame and stream tags.
1250    /// `None` leaves the tags in charge.
1251    pub fn declare_color(&mut self, color: Option<ColorMetadata>) {
1252        self.declared_color = color;
1253    }
1254
1255    /// Where `frame`'s chroma sits as its codec defines it; only hardware sessions report it.
1256    #[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    /// The color `frame` is shown with: the declaration, else the frame's tags, else the stream's.
1265    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    /// Receives each diagnostic before recovery continues, including before errors.
1272    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    /// Cumulative corruption and concealment diagnostics, including seeks.
1280    #[must_use]
1281    pub fn decode_diagnostics(&self) -> &DecodeDiagnostics {
1282        &self.recovery.diagnostics
1283    }
1284
1285    /// Opens the deterministically selected video stream.
1286    ///
1287    /// # Errors
1288    /// Returns an error when no decodable video stream exists.
1289    pub fn open(source: impl Into<SourceLocation>) -> Result<Self, DecodeError> {
1290        Self::open_with_threads(source, codec_thread_budget())
1291    }
1292
1293    /// Opens the selected stream with an explicit `FFmpeg` worker allocation.
1294    ///
1295    /// # Errors
1296    /// Returns an error when no decodable video stream exists.
1297    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        // HDR decodes like any 10-bit stream; the renderer tone-maps it or the project refuses it.
1322        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(&parameters, selected.alpha)?;
1328            dropped_layer = dropped;
1329            let mut decoder = AVCodecContext::new(&codec);
1330            decoder.apply_codecpar(&parameters).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    /// Opens one hardware decode session for `spec` on an existing device.
1366    ///
1367    /// Failures carry a typed reason so callers can record why a source fell back.
1368    #[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        // A hardware session decodes only the base picture, so it would drop alpha
1412        // a software decoder keeps.
1413        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(&parameters, spec)?;
1477            let open_failed = |error| HardwareOpenError::new(DecoderOpenFailed, error);
1478            let mut decoder = AVCodecContext::new(&codec);
1479            decoder
1480                .apply_codecpar(&parameters)
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            // Hardware decoders failing to open is expected here, so the open must fail cleanly.
1487            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    /// What this decoder leaves out (unreadable alpha, extra HEVC layers), or `None`.
1522    #[must_use]
1523    pub const fn dropped_layer(&self) -> Option<&DroppedLayer> {
1524        self.dropped_layer.as_ref()
1525    }
1526
1527    /// Effective end of the selected video source.
1528    ///
1529    /// Includes the container duration, which browser APIs expose, since the stream can end a few
1530    /// ticks earlier from time-base rounding.
1531    #[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    /// Takes the spans accumulated since the last call.
1543    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        // HDR frames keep their components and color for the renderer to tone-map or refuse.
1594        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        // With no declared color the frame goes untagged, so the renderer applies and reports the
1606        // same fallback. A repack to the identity matrix keeps the color it names.
1607        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    /// The pixel aspect ratio `frame` is shown with: the container's declaration, else the
1616    /// picture's own (broadcast streams may change it), else the probed one.
1617    pub(crate) fn picture_sample_aspect_ratio(&self, frame: &AVFrame) -> SampleAspectRatio {
1618        // A ratio the container declares is the probed one, and overrides the picture's.
1619        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    /// Drops queued packets and frames, keeping the stream selection.
1635    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    /// Seeks to `target` and returns the raw frame presented there: the last frame at or before its
1647    /// presentation deadline ([`Self::presentation_deadline`]).
1648    ///
1649    /// The frame after it is kept for the next `decode_raw_next`. A stream starting after `target`
1650    /// answers with its first frame, one ending before it with its last.
1651    ///
1652    /// The landing is checked, not trusted: MPEG-TS/PS index every packet as a keyframe, and an
1653    /// open GOP's leading frames cannot decode from the I-frame. When the first decoded frame is
1654    /// past the deadline and not the stream's first, the seek restarts 1 s, 2 s, 4 s, ... earlier.
1655    ///
1656    /// # Errors
1657    /// Returns cancellation, seek, and decode failures, and [`DecodeError::OutOfRange`] for a
1658    /// stream with no frame at all.
1659    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            // Seek from the deadline: a keyframe within the slack after the target
1673            // is the frame shown there.
1674            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                // Rounded down, so a time just before a keyframe never seeks onto it.
1679                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                // Read from the first packet, the first frame out is the stream's first frame.
1701                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    /// Decodes from a seek's landing to the frame presented at `target`, noting in `first` when the
1734    /// first decoded frame is presented.
1735    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            // A keyframe far before the target takes long to decode from, and is still progress.
1750            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            // A frame between the target and its deadline is the one shown.
1765            if pts >= target {
1766                return Ok(Landing::Presented(raw));
1767            }
1768            presented = Some(raw);
1769        }
1770    }
1771
1772    /// The latest timestamp a frame may carry and still be shown at `time`: `time` plus
1773    /// the stream's [`alpha2_time::presentation_slack`].
1774    #[must_use]
1775    pub fn presentation_deadline(&self, time: MediaTime) -> MediaTime {
1776        time.presentation_deadline(self.slack)
1777    }
1778
1779    /// When the frame the next [`Decoder::decode_next`] returns is presented, or `None` at the end.
1780    ///
1781    /// The frame is decoded now and kept for that call, so a caller can find the frame shown at a
1782    /// time without consuming the next one.
1783    ///
1784    /// # Errors
1785    /// Returns cancellation and decode failures.
1786    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    /// The presentation time of the frame `decode_raw_next` returns next (decoded now and
1794    /// kept); `None` at the end.
1795    ///
1796    /// # Errors
1797    /// Returns cancellation and decode failures.
1798    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            // Another stream's packet is skipped, not work (see `fill_pending`).
1825            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
1947/// Decoders that open without a hardware session and then fail every packet (`FFmpeg`'s own `av1`
1948/// answers `ENOSYS`). The pinned SDK decodes AV1 with libdav1d instead.
1949const HWACCEL_ONLY_DECODERS: &[&str] = &["av1"];
1950
1951/// Every decoder registered for `codec_id`, preferred first. External software decoders are
1952/// preferred, yet only `FFmpeg`'s own `av1` carries hardware configurations, so hardware sessions
1953/// look through all of them.
1954pub(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
1964/// The first decoder `FFmpeg` would pick for a software session, skipping hardware-only ones.
1965pub(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
1994/// libvpx's VP9 decoder (the one that reads alpha), when present.
1995fn 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/// Whether this runtime decodes VP9's alpha: it has libvpx's VP9 decoder.
2004#[must_use]
2005pub fn decodes_vp9_alpha() -> bool {
2006    libvpx_vp9().is_some()
2007}
2008
2009/// Why a software session would decode `stream` without its alpha, for conform reports.
2010#[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
2019/// The software decoder for `parameters` carrying `alpha`, and what it leaves out.
2020///
2021/// VP9 alpha in block additions needs libvpx's decoder; HEVC's auxiliary alpha layer and MV-HEVC
2022/// views have no decoder here, so the base layer decodes and the loss is reported.
2023fn 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
2059/// How `stream` carries alpha: VP9's `alpha_mode` tag, an HEVC auxiliary layer, or a pixel
2060/// format with an alpha plane.
2061fn 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/// Why this runtime cannot decode `stream` without a hardware session, or `None` when software can
2099/// (some preferred decoders are hardware-only; AV1 needs libdav1d).
2100#[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
2115/// The longer of a stream's and its container's duration.
2116pub(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
2123/// Unpadded bytes of one picture of `format`, or `None` for a format `FFmpeg` does not know.
2124fn 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/// The `FFmpeg` name a device's hardware codec list uses for `codec_id`.
2135#[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/// Refuses a stream whose SPS crops its left or top edge on a backend whose surfaces lose that crop
2150/// ([`HardwareDecoderSpec::keeps_leading_crop`]). An unreadable SPS is not refused.
2151#[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/// Rejects sample formats with no resident presentation path.
2182///
2183/// Only 8-bit 4:2:0, or 10-bit where the renderer presents it, reaches the GPU path; refusing at
2184/// open avoids a mid-export surface failure. An undeclared format is left to the import check.
2185#[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
2215/// Demuxers a source may open with, by `FFmpeg` short name. Each reads only the file it is given;
2216/// demuxers that open other files (HLS, `ffconcat`, image-sequence patterns) are excluded so an
2217/// asset cannot pull in media a request never named.
2218pub(crate) const SOURCE_CONTAINERS: &CStr =
2219    c"mov,matroska,mpegts,avi,mp3,aac,wav,flac,ogg,png_pipe,jpeg_pipe,webp_pipe,gif";
2220
2221/// Decoders a source may select, by `FFmpeg` name: the codecs alpha2 documents and tests and
2222/// mainstream production codecs. A stream of any other codec is `Unsupported`, unless the process
2223/// allowed every decoder ([`allow_every_decoder`]).
2224pub const SOURCE_DECODERS: &[&str] = &[
2225    // Video.
2226    "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    // Audio.
2247    "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
2279/// Lets sources select every decoder of the linked `FFmpeg`, not only [`SOURCE_DECODERS`], for
2280/// the rest of the process. A process setting for integrators who decode only trusted files.
2281pub 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/// Whether [`allow_every_decoder`] was called.
2291#[must_use]
2292pub fn every_decoder_allowed() -> bool {
2293    EVERY_DECODER.load(std::sync::atomic::Ordering::Relaxed)
2294}
2295
2296/// The [`SOURCE_DECODERS`] the linked `FFmpeg` has.
2297#[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
2311/// Refuses a decoder outside [`SOURCE_DECODERS`] unless every decoder is allowed.
2312pub(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
2323/// [`SOURCE_DECODERS`] as `FFmpeg`'s `codec_whitelist`, or `None` when every decoder is allowed.
2324fn 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
2334/// Opens a source with [`SOURCE_CONTAINERS`]: a file through the `file` protocol only, so nothing
2335/// reaches past a local path, or a remote object through its own reader, which may open nothing
2336/// else; probing opens [`SOURCE_DECODERS`] only.
2337pub(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
2373/// A source reader's failure as the decode error it is.
2374fn 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
2379/// A demux or seek failure on `input`: its reader's failure when it had one, else `FFmpeg`'s.
2380pub(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
2386/// The source's bytes from the first, at most `limit`.
2387fn 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
2404/// Refuses a PNG, JPEG or WebP whose header states a picture larger than alpha2 renders, since
2405/// `FFmpeg` learns a still's size only by decoding it. Anything else is left to `FFmpeg`.
2406fn refuse_oversized_still(source: &SourceLocation) -> Result<(), DecodeError> {
2407    // Holds the size field of the three formats, after any Exif and colour profile segments.
2408    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    /// How many inputs [`open_input`] has opened on this thread.
2427    pub(crate) static INPUTS_OPENED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2428    /// How many video frames the codec has given a [`NativeDecoder`] on this thread.
2429    pub(crate) static VIDEO_FRAMES_DECODED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2430}
2431
2432/// Lets `cancel` interrupt a blocking `FFmpeg` call on `input` (it returns `AVERROR_EXIT`).
2433pub(crate) fn interrupt_on_cancel(input: &DemuxInput, cancel: &CancelToken) {
2434    let cancel = cancel.clone();
2435    input.interrupt_when(move || cancel.is_cancelled());
2436}
2437
2438/// A demux or seek failure on `input`, as a cancel when the cancel stopped it and as its reader's
2439/// failure when the reader failed: neither is damage a decode policy may skip.
2440fn 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
2454/// A seek failure on `input`, as [`demux_failure`] reads it.
2455fn seek_failure(input: &DemuxInput, error: RsmpegError, cancel: &CancelToken) -> DecodeError {
2456    demux_failure(input, error, cancel).map_or_else(|failure| failure, adapter_error)
2457}
2458
2459/// Single-picture demuxers whose decoder, not the container, carries orientation (`FFmpeg` puts a
2460/// JPEG's Exif `Orientation` on the frame).
2461const 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
2467/// The orientation a still picture's decoder attaches, read by decoding it once at reduced size
2468/// when possible. `None` when there is none or the picture does not decode.
2469fn 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(&parameters).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    // One picture is one packet; a few more allow for a demuxer that splits it.
2487    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)]
2513/// Initial tail read for [`parsed_end`], matching `FFmpeg`'s `DURATION_MAX_READ_SIZE`; doubled up
2514/// to five times while no timed packet is found.
2515const PARSED_END_READ: u64 = 250_000;
2516
2517/// Where `input`'s packets end (latest `pts + duration`, `AV_TIME_BASE` units) when `FFmpeg`
2518/// estimated the duration from timestamps; `None` otherwise.
2519///
2520/// That estimate (MPEG-TS, MPEG-PS) reads unparsed packets, so one PES carrying several AAC frames
2521/// ends at the first frame, up to 0.19 s short. This rereads the tail through the parsers on a
2522/// separate input, leaving `input`'s position untouched.
2523fn 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
2580/// A stream tag's value; `None` when untagged or empty.
2581fn 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
2591/// Whether stream `index` has a decoder a source may select.
2592fn 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
2599/// The [`ProbeResult`] of an opened input, with `FFmpeg`'s best video and audio streams selected.
2600pub(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    // An audio track whose decoder is not allowed is left out like one without a decoder.
2608    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(&parameters)
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(&parameters)
2663                } else {
2664                    None
2665                },
2666                alpha: (kind == StreamKind::Video)
2667                    .then(|| source_alpha(stream.metadata(), &parameters))
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/// The desktop decoder behind the host's audio windows.
2705#[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}