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::alpha::{AlphaCompanion, RawFrame};
10use crate::recovery::{
11    DecodeDiagnostics, DecodePolicy, FfmpegRecovery, Recovery, WorkBudget,
12    audio_timestamp_in_range, submit_packet,
13};
14use alpha2_host_core::audio_timeline::SourceTimeline;
15use alpha2_host_core::{probe_still, still_format};
16
17use crate::convert::{
18    adapter_error, check_frame_size, codec_thread_budget, color_metadata, convert_video_frame,
19    declared_sar, frame_color_metadata, guess_sar, orientation_from_display,
20    reject_unused_decode_options, stream_rotation, tick_base, timestamp, video_decoder_options,
21};
22#[cfg(all(
23    any(target_os = "linux", target_os = "macos", target_os = "windows"),
24    feature = "hwdecode"
25))]
26use crate::video_frame::{HardwareDecoderSpec, HardwareOpenError};
27use alpha2_ffmpeg_bridge::{
28    CustomInput, DecodedFrame, DemuxInput, InputLocation, InputReader, OpenInputError,
29};
30use alpha2_media::{
31    AudioBlock, CancelToken, ColorMetadata, DecodeError, DecodeEvent, DecodeRequest, DecodeResult,
32    DecodedVideoFrame, Decoder, MAX_AUDIO_CHANNELS, Orientation, SampleAspectRatio, SourceAlpha,
33    Speaker, SpeakerLayout, StreamInfo, StreamKind,
34};
35use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND};
36use rsmpeg::avcodec::{AVCodec, AVCodecContext, AVCodecRef, AVPacket};
37#[cfg(all(
38    any(target_os = "linux", target_os = "macos", target_os = "windows"),
39    feature = "hwdecode"
40))]
41use rsmpeg::avutil::AVHWDeviceContext;
42use rsmpeg::avutil::{AVChannelLayout, AVFrame, AVRational, av_rescale_q, av_rescale_q_rnd, ra};
43use rsmpeg::error::RsmpegError;
44use rsmpeg::ffi;
45use rsmpeg::swresample::SwrContext;
46
47/// Container-level probe and deterministic stream selection.
48#[derive(Clone, Debug, PartialEq)]
49pub struct ProbeResult {
50    /// Demuxer name.
51    pub format: String,
52    /// Container duration from the first presentation to the end of the last; media
53    /// ends at `start + duration`.
54    pub duration: Option<MediaTime>,
55    /// The container's first presentation on the media's own timeline: zero for most files, later
56    /// for a transport stream or a delayed start.
57    pub start: Option<MediaTime>,
58    /// Every audio/video stream in demuxer order, other streams left out; look one up by
59    /// [`StreamInfo::index`], not by position.
60    pub streams: Vec<StreamInfo>,
61    /// The `AVStream` index of the video stream a reader shows (never an attached picture), `None`
62    /// when no video stream decodes.
63    pub selected_video: Option<usize>,
64    /// The `AVStream` index of the audio stream a reader plays, `None` when none decodes.
65    pub selected_audio: Option<usize>,
66}
67
68impl ProbeResult {
69    /// The entry of `streams` with `AVStream` index `index`.
70    #[must_use]
71    pub fn stream(&self, index: usize) -> Option<&StreamInfo> {
72        self.streams.iter().find(|stream| stream.index == index)
73    }
74
75    /// The selected video stream's entry.
76    #[must_use]
77    pub fn selected_video_stream(&self) -> Option<&StreamInfo> {
78        self.selected_video.and_then(|index| self.stream(index))
79    }
80
81    /// The selected audio stream's entry.
82    #[must_use]
83    pub fn selected_audio_stream(&self) -> Option<&StreamInfo> {
84        self.selected_audio.and_then(|index| self.stream(index))
85    }
86
87    /// The audio streams, in demuxer order; a clip's `audio.stream` counts over these.
88    pub fn audio_streams(&self) -> impl Iterator<Item = &StreamInfo> {
89        self.streams
90            .iter()
91            .filter(|stream| stream.kind == StreamKind::Audio)
92    }
93
94    /// The audio stream a clip's `audio.stream` of `ordinal` names.
95    #[must_use]
96    pub fn audio_stream(&self, ordinal: u32) -> Option<&StreamInfo> {
97        self.audio_streams().nth(usize::try_from(ordinal).ok()?)
98    }
99
100    /// The selected audio stream's position among [`Self::audio_streams`].
101    #[must_use]
102    pub fn selected_audio_ordinal(&self) -> Option<u32> {
103        let selected = self.selected_audio?;
104        let position = self
105            .audio_streams()
106            .position(|stream| stream.index == selected)?;
107        u32::try_from(position).ok()
108    }
109}
110
111/// Opens a local resource using the system `FFmpeg` 8 shared libraries.
112///
113/// # Errors
114/// Returns a platform-neutral adapter error for invalid paths or demux failures.
115pub fn probe(source: impl Into<SourceLocation>) -> Result<ProbeResult, DecodeError> {
116    let source = source.into();
117    let input = open_input(&source)?;
118    probe_context(&input, &source)
119}
120
121/// Visits each packet time (seconds) of `AVStream` index `stream` in file order until `visit`
122/// returns false. Falls back to decode time; packets with neither are skipped. Nothing is decoded.
123///
124/// # Errors
125/// Returns why the file cannot be opened or read.
126pub fn visit_packet_times(
127    source: impl Into<SourceLocation>,
128    stream: usize,
129    mut visit: impl FnMut(f64) -> bool,
130) -> Result<(), DecodeError> {
131    let mut input = open_input(&source.into())?;
132    let time_base = input
133        .streams()
134        .get(stream)
135        .map(|found| found.time_base)
136        .ok_or_else(|| DecodeError::Unsupported(format!("the file has no stream {stream}")))?;
137    input.discard_all_but(stream);
138    while let Some(packet) = input
139        .read_packet()
140        .map_err(|error| demux_error(&input, error))?
141    {
142        if usize::try_from(packet.stream_index).ok() != Some(stream) {
143            continue;
144        }
145        let time = [packet.pts, packet.dts]
146            .into_iter()
147            .find(|time| *time != ffi::AV_NOPTS_VALUE);
148        let Some(time) = time else { continue };
149        #[allow(clippy::cast_precision_loss)] // A packet time is far below 2^52 time-base units.
150        let seconds = time as f64 * f64::from(time_base.num) / f64::from(time_base.den);
151        if !visit(seconds) {
152            break;
153        }
154    }
155    Ok(())
156}
157
158/// Software video decoder with exact timestamp conversion and drain semantics.
159pub struct NativeDecoder {
160    pub(crate) input: DemuxInput,
161    pub(crate) streams: Vec<StreamInfo>,
162    pub(crate) container_duration: Option<MediaTime>,
163    pub(crate) video_index: usize,
164    pub(crate) time_base: AVRational,
165    pub(crate) decoder: AVCodecContext,
166    pub(crate) orientation: Orientation,
167    /// The probed pixel aspect ratio: the container's declaration, else the codec parameters'.
168    pub(crate) sample_aspect_ratio: SampleAspectRatio,
169    /// The color the stream's tags describe, as probed.
170    pub(crate) color: Option<ColorMetadata>,
171    /// The project's declared color, which overrides every tag ([`Self::declare_color`]).
172    pub(crate) declared_color: Option<ColorMetadata>,
173    pub(crate) video_scaler: crate::convert::FrameScaler,
174    pub(crate) pending: VecDeque<RawFrame>,
175    pub(crate) demux_eof: bool,
176    pub(crate) decoder_flushed: bool,
177    pub(crate) stages: DecodeStageTimings,
178    /// When the stream's first frame is presented, once a seek from its first packet decoded it.
179    first_video_pts: Option<MediaTime>,
180    recovery: Recovery,
181    /// How late a frame's timestamp may be and still be shown at a time
182    /// ([`Self::presentation_deadline`]).
183    slack: MediaTime,
184    /// Packets read ahead for [`Self::slack`], consumed before the demuxer until a seek drops them.
185    prefetched: Prefetched,
186    /// What this decoder does not decode of its stream (an alpha channel, extra layers).
187    dropped_layer: Option<DroppedLayer>,
188    alpha: Option<AlphaCompanion>,
189}
190
191/// Something a decoder leaves out of its stream (the frames still decode), for reports.
192#[derive(Clone, Debug, Eq, PartialEq)]
193pub struct DroppedLayer {
194    /// `alpha-dropped` or `extra-layers-dropped`.
195    pub code: &'static str,
196    /// Human-readable explanation.
197    pub reason: String,
198}
199
200#[cfg(test)]
201thread_local! {
202    /// How long the next video packet read on this thread takes, slept or added to the virtual
203    /// clock (`recovery::VIRTUAL_CLOCK`) when set.
204    pub(crate) static READ_DELAY: std::cell::Cell<std::time::Duration> =
205        const { std::cell::Cell::new(std::time::Duration::ZERO) };
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    /// How many times the input was sought.
290    pub seeks: u64,
291    /// How many pictures were turned into host frames.
292    pub conversions: u64,
293}
294
295impl DecodeStageTimings {
296    /// Adds another session's spans to these, saturating on overflow.
297    #[must_use]
298    pub fn merged(self, other: Self) -> Self {
299        Self {
300            demux: self.demux.saturating_add(other.demux),
301            send_packet: self.send_packet.saturating_add(other.send_packet),
302            receive_frame: self.receive_frame.saturating_add(other.receive_frame),
303            convert: self.convert.saturating_add(other.convert),
304            seek: self.seek.saturating_add(other.seek),
305            seeks: self.seeks.saturating_add(other.seeks),
306            conversions: self.conversions.saturating_add(other.conversions),
307        }
308    }
309}
310
311#[derive(Clone, Copy, PartialEq, Eq)]
312enum InputPosition {
313    /// Opened, with no read or seek since.
314    Opened,
315    Moved,
316}
317
318#[derive(Clone, Copy, PartialEq, Eq)]
319enum AudioContinuity {
320    Continuous,
321    Damaged,
322}
323
324/// Streaming `FFmpeg` audio decoder normalized to project-rate planar `f32`.
325///
326/// Blocks keep the stream's channel order ([`NativeAudioDecoder::speakers`]). `swresample` converts
327/// each frame to `f32` at its own rate, rematrixing only a frame whose layout differs from the
328/// stream's; the source timeline places it by timestamp and `alpha2_audio::Resampler` (shared with
329/// the browser host) brings it to the project rate.
330pub struct NativeAudioDecoder {
331    pub(crate) source: SourceLocation,
332    pub(crate) input: DemuxInput,
333    input_position: InputPosition,
334    pub(crate) streams: Vec<StreamInfo>,
335    pub(crate) container_duration: Option<MediaTime>,
336    pub(crate) audio_index: usize,
337    pub(crate) time_base: AVRational,
338    pub(crate) decoder: AVCodecContext,
339    /// Converts sample format, and the layout of a frame unlike the stream's; never the rate.
340    converter: Option<SwrContext>,
341    pub(crate) sample_rate: u32,
342    pub(crate) channel_count: usize,
343    /// The speakers the stream declares, or its count's default.
344    speakers: SpeakerLayout,
345    /// Whether the stream declared no speaker and `speakers` is assumed.
346    speakers_assumed: bool,
347    /// `speakers` as `FFmpeg`'s layout: what every frame is converted to.
348    output_layout: AVChannelLayout,
349    /// The decoded source, placed and not yet resampled.
350    timeline: SourceTimeline,
351    pub(crate) pending: Vec<VecDeque<f32>>,
352    /// Source-timeline index, at the output rate, of the first pending sample; `None` until a
353    /// frame's timestamp places it.
354    pub(crate) next_sample: Option<i64>,
355    pub(crate) block_frames: usize,
356    pub(crate) demux_eof: bool,
357    pub(crate) decoder_flushed: bool,
358    recovery: Recovery,
359    repair_audio: AudioContinuity,
360    /// How a demuxer's made-up timestamps (raw ADTS) compare with the audio; `None` when
361    /// the container has real ones.
362    made_up: Option<MadeUpTimestamps>,
363    /// The source rate and frame grid of the stream's first timestamps
364    /// ([`alpha2_time::audio_frame_grid`]), used to place the first frame after an open or seek.
365    grid: Option<(u32, alpha2_time::AudioFrameGrid)>,
366    /// Packets read ahead for [`Self::grid`], consumed before the demuxer until a seek drops them.
367    prefetched: Prefetched,
368    /// Frames placed since open; placing one counts as progress before the target is reached.
369    frames_placed: u64,
370    /// The codec's seek pre-roll, in ticks.
371    seek_preroll: i64,
372}
373
374/// The `AVStream` index of audio stream `stream` ([`ProbeResult::audio_stream`]), or of the
375/// selected one for `None`.
376fn audio_stream_index(probe: &ProbeResult, stream: Option<u32>) -> Result<usize, DecodeError> {
377    match stream {
378        None => probe.selected_audio.ok_or_else(|| {
379            DecodeError::Unsupported("source has no audio stream this runtime decodes".into())
380        }),
381        Some(ordinal) => probe
382            .audio_stream(ordinal)
383            .map(|info| info.index)
384            .ok_or_else(|| {
385                DecodeError::Unsupported(format!(
386                    "source has no audio stream {ordinal}; it has {}",
387                    probe.audio_streams().count()
388                ))
389            }),
390    }
391}
392
393/// Timestamps a demuxer made up by counting each packet's samples at one rate.
394struct MadeUpTimestamps {
395    /// The stream's first rate, which every packet is counted at.
396    rate: u32,
397    /// How far the timestamps have run ahead of the decoded frames since the last restart,
398    /// in the stream's time base.
399    drift: i64,
400    /// Whether a frame came at another rate, after which the timestamps no longer match the audio.
401    rate_changed: bool,
402}
403
404/// How far before a seek target decoding restarts.
405///
406/// A decoder resuming mid-stream lacks history (AAC's first frame misses the previous overlap), so
407/// decoding from 100 ms early and discarding up to the target matches a straight decode.
408const AUDIO_SEEK_PREROLL_TICKS: i64 = TICKS_PER_SECOND / 10;
409
410/// How far before a seek target decoding restarts in Opus (400 ms).
411///
412/// RFC 7845 asks for at least 80 ms, but the decoder converges slowly: the target's samples are
413/// still 2e-2 off from 100 ms, 1e-4 from 250 ms and under 1e-6 from 400 ms.
414const OPUS_SEEK_PREROLL_TICKS: i64 = TICKS_PER_SECOND * 2 / 5;
415
416impl NativeAudioDecoder {
417    /// Selects strict failure (default) or bounded, reported recovery.
418    pub fn set_decode_policy(&mut self, policy: DecodePolicy) {
419        self.recovery.policy = policy;
420    }
421
422    /// Receives each diagnostic before recovery continues, including before errors.
423    pub fn set_decode_reporter(
424        &mut self,
425        reporter: impl Fn(crate::DecodeDiagnostic) + Send + Sync + 'static,
426    ) {
427        self.recovery.reporter = Some(Box::new(reporter));
428    }
429
430    /// Cumulative corruption and concealment diagnostics, including seeks.
431    #[must_use]
432    pub fn decode_diagnostics(&self) -> &DecodeDiagnostics {
433        &self.recovery.diagnostics
434    }
435
436    /// Decodes the selected audio stream through the linked `FFmpeg` 8 libraries.
437    ///
438    /// # Errors
439    /// Returns a platform-neutral error for invalid rates, missing streams, unsupported layouts,
440    /// codec failures, or malformed decoded audio.
441    pub fn open(
442        source: impl Into<SourceLocation>,
443        project_sample_rate: u32,
444    ) -> Result<Self, DecodeError> {
445        Self::open_stream(source, project_sample_rate, None)
446    }
447
448    /// Decodes audio stream `stream`, counted over the file's audio streams in demuxer order
449    /// ([`ProbeResult::audio_stream`]); `None` decodes the selected one, as [`Self::open`] does.
450    ///
451    /// # Errors
452    /// As [`Self::open`], and `Unsupported` when the file has no such audio stream.
453    pub fn open_stream(
454        source: impl Into<SourceLocation>,
455        project_sample_rate: u32,
456        stream: Option<u32>,
457    ) -> Result<Self, DecodeError> {
458        if project_sample_rate == 0 {
459            return Err(DecodeError::OutOfRange);
460        }
461        let source = source.into();
462        let mut input = open_input(&source)?;
463        let probe = probe_context(&input, &source)?;
464        let selected = audio_stream_index(&probe, stream)?;
465        let stream = probe
466            .stream(selected)
467            .ok_or_else(|| DecodeError::Adapter("selected audio stream disappeared".into()))?;
468        check_source_sample_rate(i64::from(stream.sample_rate.unwrap_or(0)))?;
469        let source_channels =
470            usize::try_from(stream.channels.unwrap_or(0)).map_err(|_| DecodeError::OutOfRange)?;
471        if source_channels == 0 {
472            return Err(DecodeError::Unsupported(
473                "audio stream declares no channels".into(),
474            ));
475        }
476        check_audio_channels(source_channels)?;
477        let decoder = open_audio_decoder(&mut input, selected)?;
478        let (prefetched, timestamps) = read_first_packets(&mut input, selected);
479        let stream = input
480            .streams()
481            .get(selected)
482            .ok_or(DecodeError::OutOfRange)?;
483        let time_base = stream.time_base;
484        let seek_preroll = if stream.codecpar().codec_id == ffi::AV_CODEC_ID_OPUS {
485            OPUS_SEEK_PREROLL_TICKS
486        } else {
487            AUDIO_SEEK_PREROLL_TICKS
488        };
489        // ADTS has no timestamps: the `aac` demuxer counts each packet as `frame_size` samples at
490        // the starting rate, whatever rate a later header names.
491        let made_up = (input.iformat().name() == c"aac")
492            .then(|| u32::try_from(stream.codecpar().sample_rate).ok())
493            .flatten()
494            .filter(|rate| *rate > 0)
495            .map(|rate| MadeUpTimestamps {
496                rate,
497                drift: 0,
498                rate_changed: false,
499            });
500        // Made-up timestamps count samples exactly, so there is no rounding grid.
501        let grid = u32::try_from(stream.codecpar().sample_rate)
502            .ok()
503            .filter(|_| made_up.is_none())
504            .and_then(|rate| {
505                alpha2_time::audio_frame_grid(
506                    &timestamps,
507                    i64::from(time_base.num),
508                    i64::from(time_base.den),
509                    rate,
510                )
511                .map(|grid| (rate, grid))
512            });
513        // Channels keep the stream's layout; the engine folds them by speaker. The layout comes
514        // from the decoder, else the container, else the count's default.
515        let declared = [decoder.ch_layout(), stream.codecpar().ch_layout()]
516            .into_iter()
517            .find(|layout| {
518                layout.order != ffi::AV_CHANNEL_ORDER_UNSPEC
519                    && usize::try_from(layout.nb_channels).ok() == Some(source_channels)
520            })
521            .map_or_else(
522                || vec![Speaker::Unnamed; source_channels],
523                |layout| layout_speakers(&layout),
524            );
525        let (speakers, speakers_assumed) = SpeakerLayout::declared_or_default(&declared)
526            .ok_or_else(|| unsupported_channels(source_channels))?;
527        let channel_count = speakers.channels();
528        let output_layout = ffmpeg_layout(&speakers)?;
529        Ok(Self {
530            source,
531            input,
532            input_position: InputPosition::Opened,
533            container_duration: probe.duration,
534            streams: probe.streams,
535            audio_index: selected,
536            time_base,
537            decoder,
538            converter: None,
539            sample_rate: project_sample_rate,
540            channel_count,
541            speakers,
542            speakers_assumed,
543            output_layout,
544            timeline: SourceTimeline::new(project_sample_rate, channel_count, None),
545            pending: (0..channel_count).map(|_| VecDeque::new()).collect(),
546            next_sample: None,
547            block_frames: 1_024,
548            demux_eof: false,
549            decoder_flushed: false,
550            recovery: Recovery::new(crate::recovery::time_base(time_base)),
551            repair_audio: AudioContinuity::Continuous,
552            made_up,
553            grid,
554            prefetched,
555            frames_placed: 0,
556            seek_preroll,
557        })
558    }
559
560    /// Sets the maximum observable block size returned by `decode_next`.
561    ///
562    /// # Errors
563    /// Returns [`DecodeError::OutOfRange`] for zero frames.
564    pub fn set_block_frames(&mut self, frames: usize) -> Result<(), DecodeError> {
565        if frames == 0 {
566            return Err(DecodeError::OutOfRange);
567        }
568        self.block_frames = frames;
569        Ok(())
570    }
571
572    /// Channels of every block this decoder returns: the source's, 1 to [`MAX_AUDIO_CHANNELS`].
573    #[must_use]
574    pub const fn channels(&self) -> usize {
575        self.channel_count
576    }
577
578    /// The speaker each plane feeds: the stream's declared layout, or its count's default.
579    #[must_use]
580    pub const fn speakers(&self) -> SpeakerLayout {
581        self.speakers
582    }
583
584    /// Whether the stream declares no layout, so [`Self::speakers`] is a default.
585    #[must_use]
586    pub const fn speakers_assumed(&self) -> bool {
587        self.speakers_assumed
588    }
589
590    /// Effective end of the selected audio source.
591    ///
592    /// Containers often declare a slightly longer duration than the stream (priming,
593    /// time-base rounding). Projects authored in a browser use the container duration, so it
594    /// is kept as the source boundary.
595    #[must_use]
596    pub fn audio_duration(&self) -> Option<MediaTime> {
597        effective_media_duration(
598            self.streams
599                .iter()
600                .find(|stream| stream.index == self.audio_index)
601                .and_then(|stream| stream.duration),
602            self.container_duration,
603        )
604    }
605
606    /// The selected stream's first timestamp in its time base, or zero when unknown.
607    fn stream_start(&self) -> i64 {
608        self.input
609            .streams()
610            .get(self.audio_index)
611            .map(|stream| stream.start_time)
612            .filter(|start| *start != ffi::AV_NOPTS_VALUE)
613            .unwrap_or(0)
614    }
615
616    /// The most decoded samples per channel held at once since the last open or seek.
617    #[cfg(test)]
618    pub(crate) const fn peak_held_samples(&self) -> usize {
619        self.timeline.peak_held()
620    }
621
622    /// Goes back to the stream's first packet. An untouched input replays [`Self::prefetched`]; any
623    /// other is reopened, since a raw elementary stream cannot seek before its first packet.
624    pub(crate) fn reset_to_start(&mut self) -> Result<(), DecodeError> {
625        if self.input_position == InputPosition::Opened {
626            self.decoder.flush_buffers();
627        } else {
628            let mut input = open_input(&self.source)?;
629            self.decoder = open_audio_decoder(&mut input, self.audio_index)?;
630            self.input = input;
631            self.input_position = InputPosition::Opened;
632            self.prefetched.clear();
633        }
634        self.restart(None);
635        Ok(())
636    }
637
638    /// Forgets everything decoded; the next output is no earlier than `first`.
639    fn restart(&mut self, first: Option<i64>) {
640        self.converter = None;
641        self.timeline = SourceTimeline::new(self.sample_rate, self.channel_count, first);
642        self.pending.iter_mut().for_each(VecDeque::clear);
643        self.next_sample = None;
644        self.demux_eof = false;
645        self.decoder_flushed = false;
646        self.repair_audio = AudioContinuity::Continuous;
647        self.recovery.reset_progress();
648        if let Some(made_up) = &mut self.made_up {
649            made_up.drift = 0;
650        }
651    }
652
653    fn made_up_rate_changed(&self) -> bool {
654        self.made_up
655            .as_ref()
656            .is_some_and(|made_up| made_up.rate_changed)
657    }
658
659    /// The real time of a frame whose demuxer made up `pts` by counting every earlier packet at the
660    /// stream's first rate. Other streams return `pts` unchanged.
661    fn true_timestamp(&mut self, pts: Option<i64>, rate: u32, samples: i32) -> Option<i64> {
662        let time_base = self.time_base;
663        let Some(made_up) = &mut self.made_up else {
664            return pts;
665        };
666        let declared = made_up.rate;
667        made_up.rate_changed |= rate != declared;
668        let corrected = pts.map(|pts| pts.saturating_sub(made_up.drift));
669        let (num, den) = (
670            i128::from(time_base.num.max(1)),
671            i128::from(time_base.den.max(1)),
672        );
673        let samples = i128::from(samples.max(0));
674        // The demuxer's duration rounds down (`compute_pkt_fields`); the
675        // frame's own rounds to nearest.
676        let counted = samples * den / (i128::from(declared) * num);
677        let lasted = (2 * samples * den + i128::from(rate) * num) / (2 * i128::from(rate) * num);
678        made_up.drift = made_up
679            .drift
680            .saturating_add(i64::try_from(counted - lasted).unwrap_or(0));
681        corrected
682    }
683
684    pub(crate) fn receive_audio_frame(&mut self) -> Result<bool, DecodeError> {
685        let mut frame = match self.decoder.receive_frame() {
686            Ok(frame) => frame,
687            Err(RsmpegError::DecoderDrainError | RsmpegError::DecoderFlushedError) => {
688                return Ok(false);
689            }
690            Err(error) => {
691                self.recovery.error(error, "audio receive", None)?;
692                self.repair_audio = AudioContinuity::Damaged;
693                return Ok(true);
694            }
695        };
696        if frame.flags & i32::try_from(ffi::AV_FRAME_FLAG_CORRUPT).expect("flag fits i32") != 0
697            || frame.decode_error_flags != 0
698        {
699            self.recovery
700                .corrupt("audio frame", crate::recovery::pts(frame.pts))?;
701            self.repair_audio = AudioContinuity::Damaged;
702            return Ok(true);
703        }
704        let pts = Some(if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
705            frame.pts
706        } else {
707            frame.best_effort_timestamp
708        })
709        .filter(|pts| *pts != ffi::AV_NOPTS_VALUE);
710        let (num, den) = (self.time_base.num.into(), self.time_base.den.into());
711        if pts.is_some_and(|pts| !audio_timestamp_in_range(pts, num, den)) {
712            self.recovery.corrupt("audio timestamp", pts)?;
713            self.repair_audio = AudioContinuity::Damaged;
714            return Ok(true);
715        }
716        self.recovery.progress(pts)?;
717        normalize_audio_frame_layout(&mut frame, &self.output_layout)?;
718        // A decoder may change rate mid-stream, so check the frame's own rate.
719        check_source_sample_rate(i64::from(frame.sample_rate))?;
720        let rate = u32::try_from(frame.sample_rate).map_err(|_| DecodeError::OutOfRange)?;
721        let pts = self.true_timestamp(pts, rate, frame.nb_samples);
722        let planes = self.convert_audio_frame(&frame)?;
723        self.place_audio(rate, pts, planes)?;
724        Ok(true)
725    }
726
727    /// The frame as `f32` planes feeding [`Self::speakers`], at its own rate.
728    fn convert_audio_frame(&mut self, frame: &AVFrame) -> Result<Vec<Vec<f32>>, DecodeError> {
729        let mut packed = audio_output_frame(frame.sample_rate, &self.output_layout);
730        let mut converter = match self.converter.take() {
731            Some(converter) => converter,
732            None => audio_converter(frame, &self.output_layout)?,
733        };
734        if let Err(error) = converter.convert_frame(Some(frame), &mut packed) {
735            if error.raw_error() != Some(ffi::AVERROR_INPUT_CHANGED) {
736                return Err(adapter_error(error));
737            }
738            converter = audio_converter(frame, &self.output_layout)?;
739            packed = audio_output_frame(frame.sample_rate, &self.output_layout);
740            converter
741                .convert_frame(Some(frame), &mut packed)
742                .map_err(adapter_error)?;
743        }
744        self.converter = Some(converter);
745        // At one rate `swresample` holds nothing back: what goes in comes out.
746        if packed.nb_samples != frame.nb_samples {
747            return Err(DecodeError::Adapter(format!(
748                "converting {} decoded audio samples gave {}",
749                frame.nb_samples, packed.nb_samples
750            )));
751        }
752        let mut planes = (0..self.channel_count)
753            .map(|_| VecDeque::new())
754            .collect::<Vec<_>>();
755        append_interleaved_audio(&packed, &mut planes)?;
756        Ok(planes.into_iter().map(Vec::from).collect())
757    }
758
759    /// Places one decoded frame where its timestamp says.
760    ///
761    /// A timestamp within a frame duration, 2 ms, or two time-base units of the previous end
762    /// continues it, since containers round timestamps (Matroska to the millisecond) and the
763    /// browser demuxer ignores sub-frame jumps. Further ahead is a silent gap; further back repeats
764    /// samples, which are dropped. After damage the timestamp is trusted exactly.
765    fn place_audio(
766        &mut self,
767        rate: u32,
768        pts: Option<i64>,
769        mut planes: Vec<Vec<f32>>,
770    ) -> Result<(), DecodeError> {
771        let rate_i32 = i32::try_from(rate).map_err(|_| DecodeError::OutOfRange)?;
772        let at = pts.map(|pts| {
773            av_rescale_q_rnd(
774                pts,
775                self.time_base,
776                ra(1, rate_i32),
777                ffi::AV_ROUND_NEAR_INF | ffi::AV_ROUND_PASS_MINMAX,
778            )
779        });
780        let damaged = self.repair_audio == AudioContinuity::Damaged;
781        self.repair_audio = AudioContinuity::Continuous;
782        self.frames_placed = self.frames_placed.wrapping_add(1);
783        let frames = i64::try_from(planes.first().map_or(0, Vec::len)).unwrap_or(i64::MAX);
784        let Some(expected) = self.timeline.expected(rate) else {
785            // Snap the first frame after an open or seek to the stream's grid, so it lands where
786            // a straight decode puts it.
787            let at = match (at, self.grid) {
788                (Some(at), Some((grid_rate, grid))) if !damaged && grid_rate == rate => {
789                    grid.place(at, frames)
790                }
791                (at, _) => at.unwrap_or(0),
792            };
793            return self.timeline.place(rate, at, planes);
794        };
795        let Some(at) = at else {
796            if damaged {
797                return Err(DecodeError::Adapter(
798                    "cannot locate damaged audio gap without PTS".into(),
799                ));
800            }
801            return self.timeline.place(rate, expected, planes);
802        };
803        let ahead = at
804            .checked_sub(expected)
805            .ok_or_else(|| DecodeError::Adapter("audio timestamps are out of range".into()))?;
806        if damaged {
807            if ahead < 0 || ahead > i64::from(rate) * 10 {
808                return Err(DecodeError::Adapter(
809                    "damaged audio gap is ambiguous or exceeds 10 seconds".into(),
810                ));
811            }
812            if ahead > 0 {
813                self.recovery.audio_gap(
814                    self.timeline.output_at(rate, expected),
815                    self.timeline.output_at(rate, at),
816                    self.sample_rate,
817                    "corrupt input",
818                )?;
819            }
820            return self.timeline.place(rate, at, planes);
821        }
822        // One time-base unit in source samples, rounded up; 2 ms likewise.
823        let den = i64::from(self.time_base.den.max(1));
824        let unit = (i64::from(rate) * i64::from(self.time_base.num) + den - 1) / den;
825        let tolerance = frames
826            .max((i64::from(rate) + 499) / 500)
827            .max(unit.saturating_mul(2));
828        if ahead.abs() < tolerance {
829            return self.timeline.place(rate, expected, planes);
830        }
831        if ahead > 0 {
832            self.recovery.timestamp_gap(
833                self.timeline.output_at(rate, expected),
834                self.timeline.output_at(rate, at),
835                self.sample_rate,
836            );
837            return self.timeline.place(rate, at, planes);
838        }
839        let repeated = usize::try_from(-ahead).unwrap_or(usize::MAX);
840        self.recovery.timestamp_overlap(
841            self.timeline.output_at(rate, at),
842            self.timeline
843                .output_at(rate, at.saturating_add(frames.min(-ahead))),
844            self.sample_rate,
845        );
846        for plane in &mut planes {
847            plane.drain(..repeated.min(plane.len()));
848        }
849        self.timeline.place(rate, expected, planes)
850    }
851
852    pub(crate) fn fill_pending(
853        &mut self,
854        frames: usize,
855        cancel: &CancelToken,
856    ) -> Result<(), DecodeError> {
857        interrupt_on_cancel(&self.input, cancel);
858        let mut budget = WorkBudget::new();
859        let mut foreign = false;
860        let mut placed = self.frames_placed;
861        loop {
862            let held = self.pending.first().map_or(0, VecDeque::len);
863            if held >= frames {
864                return Ok(());
865            }
866            // A placed frame is progress even before it reaches the output, so a long
867            // seek decode is not cut short.
868            if self.frames_placed != placed {
869                placed = self.frames_placed;
870                budget.progressed();
871            }
872            // Skipped packets of other streams are not progress: a demuxer that ignores the
873            // discard still reads them.
874            if std::mem::take(&mut foreign) {
875                if cancel.is_cancelled() {
876                    return Err(DecodeError::Cancelled);
877                }
878            } else {
879                budget.step(cancel)?;
880            }
881            if let Some((start, _)) = self.timeline.produce(&mut self.pending, frames - held) {
882                if held == 0 {
883                    self.next_sample = Some(start);
884                }
885                continue;
886            }
887            if self.receive_audio_frame()? {
888                continue;
889            }
890            if self.demux_eof {
891                if !self.decoder_flushed {
892                    match self.decoder.send_packet(None) {
893                        Ok(()) | Err(RsmpegError::DecoderFlushedError) => {}
894                        Err(RsmpegError::DecoderFullError) => continue,
895                        Err(error) => {
896                            self.recovery.error(error, "flush", None)?;
897                            continue;
898                        }
899                    }
900                    self.decoder_flushed = true;
901                    continue;
902                }
903                if self.repair_audio == AudioContinuity::Damaged {
904                    // Damage running to the end (Tolerant only) ends the stream at its last healthy
905                    // frame; the damage is already reported.
906                    self.recovery.damaged_tail("audio")?;
907                    self.repair_audio = AudioContinuity::Continuous;
908                }
909                if !self.timeline.finished() {
910                    self.timeline.finish();
911                    continue;
912                }
913                return Ok(());
914            }
915            self.input_position = InputPosition::Moved;
916            let packet = match self
917                .prefetched
918                .pop_front()
919                .unwrap_or_else(|| self.input.read_packet())
920            {
921                Ok(Some(packet)) => packet,
922                Ok(None) => {
923                    self.demux_eof = true;
924                    continue;
925                }
926                Err(error) => {
927                    let error = demux_failure(&self.input, error, cancel)?;
928                    self.recovery.error(error, "audio demux", None)?;
929                    self.repair_audio = AudioContinuity::Damaged;
930                    continue;
931                }
932            };
933            if usize::try_from(packet.stream_index).ok() != Some(self.audio_index) {
934                foreign = true;
935                continue;
936            }
937            budget.advanced();
938            if packet.flags & i32::try_from(ffi::AV_PKT_FLAG_CORRUPT).expect("flag fits i32") != 0 {
939                self.recovery
940                    .corrupt("audio packet", crate::recovery::pts(packet.pts))?;
941                self.repair_audio = AudioContinuity::Damaged;
942                continue;
943            }
944            submit_packet(
945                |drain| {
946                    if drain {
947                        return self.receive_audio_frame();
948                    }
949                    match self.decoder.send_packet(Some(&packet)) {
950                        Ok(()) => Ok(true),
951                        Err(RsmpegError::DecoderFullError) => Ok(false),
952                        Err(error) => {
953                            self.recovery.error(error, "audio send", Some(packet.pts))?;
954                            self.repair_audio = AudioContinuity::Damaged;
955                            Ok(true)
956                        }
957                    }
958                },
959                &mut budget,
960                cancel,
961            )?;
962        }
963    }
964}
965
966impl Decoder for NativeAudioDecoder {
967    fn streams(&self) -> &[StreamInfo] {
968        &self.streams
969    }
970    fn flush(&mut self) -> Result<(), DecodeError> {
971        self.reset_to_start()
972    }
973    fn seek(
974        &mut self,
975        request: DecodeRequest,
976        cancel: &CancelToken,
977    ) -> Result<DecodeResult, DecodeError> {
978        if cancel.is_cancelled() {
979            return Err(DecodeError::Cancelled);
980        }
981        let target = request
982            .time
983            .ticks()
984            .saturating_mul(i64::from(self.sample_rate))
985            .div_euclid(TICKS_PER_SECOND);
986        let timestamp = av_rescale_q(
987            request.time.ticks().saturating_sub(self.seek_preroll),
988            tick_base(),
989            self.time_base,
990        );
991        // Raw elementary streams (MP3, ADTS AAC, AC-3) index from the first packet, so a pre-roll
992        // seek before the start fails with -1 (EPERM); reopen instead. The same applies when a rate
993        // change has put the made-up timestamps off the audio.
994        let rate_changed = self.made_up_rate_changed();
995        let from_start = timestamp <= self.stream_start() || rate_changed;
996        if from_start {
997            self.reset_to_start()?;
998        } else {
999            interrupt_on_cancel(&self.input, cancel);
1000            self.input_position = InputPosition::Moved;
1001            self.prefetched.clear();
1002            self.input
1003                .seek(
1004                    i32::try_from(self.audio_index).map_err(|_| DecodeError::OutOfRange)?,
1005                    timestamp,
1006                    i32::try_from(ffi::AVSEEK_FLAG_BACKWARD).expect("seek flag fits i32"),
1007                )
1008                .map_err(|error| seek_failure(&self.input, error, cancel))?;
1009        }
1010        self.decoder.flush_buffers();
1011        self.restart(Some(target));
1012        let mut event = self.decode_next(cancel)?;
1013        if !from_start && !rate_changed && self.made_up_rate_changed() {
1014            // The seek landed past a rate change the made-up timestamps hide.
1015            self.reset_to_start()?;
1016            self.decoder.flush_buffers();
1017            self.restart(Some(target));
1018            event = self.decode_next(cancel)?;
1019        }
1020        if matches!(event, DecodeEvent::EndOfStream) {
1021            return Err(DecodeError::OutOfRange);
1022        }
1023        Ok(DecodeResult { request, event })
1024    }
1025    fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError> {
1026        if cancel.is_cancelled() {
1027            return Err(DecodeError::Cancelled);
1028        }
1029        self.fill_pending(self.block_frames, cancel)?;
1030        let frames = self
1031            .pending
1032            .first()
1033            .map_or(0, VecDeque::len)
1034            .min(self.block_frames);
1035        if frames == 0 {
1036            return Ok(DecodeEvent::EndOfStream);
1037        }
1038        let start_sample = self.next_sample.unwrap_or(0);
1039        let block = AudioBlock {
1040            start_sample,
1041            sample_rate: self.sample_rate,
1042            speakers: self.speakers,
1043            channels: self
1044                .pending
1045                .iter_mut()
1046                .map(|channel| channel.drain(..frames).collect())
1047                .collect(),
1048        };
1049        self.next_sample =
1050            Some(start_sample.saturating_add(i64::try_from(frames).unwrap_or(i64::MAX)));
1051        Ok(DecodeEvent::Audio(block))
1052    }
1053}
1054
1055/// Opens the decoder for stream `stream_index` and discards every other stream.
1056fn open_audio_decoder(
1057    input: &mut DemuxInput,
1058    stream_index: usize,
1059) -> Result<AVCodecContext, DecodeError> {
1060    input.discard_all_but(stream_index);
1061    let stream = input
1062        .streams()
1063        .get(stream_index)
1064        .ok_or(DecodeError::OutOfRange)?;
1065    let parameters = stream.codecpar();
1066    let codec = AVCodec::find_decoder(parameters.codec_id)
1067        .ok_or_else(|| DecodeError::Unsupported("audio decoder is unavailable".into()))?;
1068    allowed_decoder(&codec)?;
1069    let mut decoder = AVCodecContext::new(&codec);
1070    decoder.apply_codecpar(&parameters).map_err(adapter_error)?;
1071    decoder.set_pkt_timebase(stream.time_base);
1072    decoder.open(None).map_err(adapter_error)?;
1073    Ok(decoder)
1074}
1075
1076/// Accepted source sample rates (1 kHz to 768 kHz, the `alpha2_audio::Resampler` range).
1077pub const SOURCE_SAMPLE_RATES: std::ops::RangeInclusive<u32> = 1_000..=768_000;
1078
1079fn check_source_sample_rate(rate: i64) -> Result<(), DecodeError> {
1080    if u32::try_from(rate).is_ok_and(|rate| SOURCE_SAMPLE_RATES.contains(&rate)) {
1081        return Ok(());
1082    }
1083    Err(DecodeError::Unsupported(format!(
1084        "the source's audio is {rate} Hz, and alpha2 reads audio from {} Hz to {} Hz",
1085        SOURCE_SAMPLE_RATES.start(),
1086        SOURCE_SAMPLE_RATES.end()
1087    )))
1088}
1089
1090/// Converts a frame to packed `f32` in the stream's layout `output`, keeping its rate; a frame with
1091/// a different layout is rematrixed.
1092pub(crate) fn audio_converter(
1093    frame: &AVFrame,
1094    output: &AVChannelLayout,
1095) -> Result<SwrContext, DecodeError> {
1096    if frame.sample_rate <= 0 || frame.format == ffi::AV_SAMPLE_FMT_NONE {
1097        return Err(DecodeError::Adapter(
1098            "decoded audio frame has an incomplete format".into(),
1099        ));
1100    }
1101    // Borrowed, never cloned: rsmpeg 0.18's `AVChannelLayout::clone` copies into uninitialized
1102    // memory that `av_channel_layout_copy` first frees.
1103    let input_layout = frame.ch_layout();
1104    let mut converter = SwrContext::new(
1105        output,
1106        ffi::AV_SAMPLE_FMT_FLT,
1107        frame.sample_rate,
1108        &input_layout,
1109        frame.format,
1110        frame.sample_rate,
1111    )
1112    .map_err(adapter_error)?;
1113    converter.init().map_err(adapter_error)?;
1114    Ok(converter)
1115}
1116
1117/// The speaker each channel of `layout` feeds; all [`Speaker::Unnamed`] for a count-only layout.
1118pub(crate) fn layout_speakers(layout: &AVChannelLayout) -> Vec<Speaker> {
1119    let channels = alpha2_ffmpeg_bridge::channel_layout_channels(layout);
1120    if channels.is_empty() {
1121        return vec![Speaker::Unnamed; usize::try_from(layout.nb_channels).unwrap_or(0)];
1122    }
1123    channels
1124        .into_iter()
1125        .map(|channel| Speaker::from_ffmpeg_channel(i64::from(channel)))
1126        .collect()
1127}
1128
1129/// `speakers` as an `FFmpeg` layout: native order when possible, custom otherwise.
1130pub(crate) fn ffmpeg_layout(speakers: &SpeakerLayout) -> Result<AVChannelLayout, DecodeError> {
1131    let channels = speakers
1132        .speakers()
1133        .iter()
1134        .map(|speaker| {
1135            ffi::AVChannel::try_from(speaker.ffmpeg_channel()).unwrap_or(ffi::AV_CHAN_UNKNOWN)
1136        })
1137        .collect::<Vec<_>>();
1138    alpha2_ffmpeg_bridge::channel_layout_of(&channels).map_err(|error| {
1139        DecodeError::Adapter(format!(
1140            "could not lay out audio channels {}: {error:?}",
1141            speakers.describe()
1142        ))
1143    })
1144}
1145
1146fn unsupported_channels(channels: usize) -> DecodeError {
1147    DecodeError::Unsupported(format!(
1148        "audio with {channels} channels is unsupported: the engine takes 1 to {MAX_AUDIO_CHANNELS}"
1149    ))
1150}
1151
1152fn check_audio_channels(channels: usize) -> Result<(), DecodeError> {
1153    if (1..=MAX_AUDIO_CHANNELS).contains(&channels) {
1154        Ok(())
1155    } else {
1156        Err(unsupported_channels(channels))
1157    }
1158}
1159
1160/// Gives a frame whose layout names no speakers (`UNSPEC`, `AMBISONIC`, or a custom order with
1161/// unknown channels) the layout it is converted to, so `swresample` copies it channel for channel.
1162///
1163/// With the stream's count that is the stream's layout; with another count it is that count's
1164/// default, rematrixed where possible. Left `UNSPEC`, `swresample` would resolve the input itself,
1165/// see a format change and return `AVERROR_INPUT_CHANGED` on every retry.
1166pub(crate) fn normalize_audio_frame_layout(
1167    frame: &mut AVFrame,
1168    stream: &AVChannelLayout,
1169) -> Result<(), DecodeError> {
1170    let (channels, named) = {
1171        let layout = frame.ch_layout();
1172        let named = matches!(
1173            layout.order,
1174            ffi::AV_CHANNEL_ORDER_NATIVE | ffi::AV_CHANNEL_ORDER_CUSTOM
1175        ) && !layout_speakers(&layout).contains(&Speaker::Unnamed);
1176        (layout.nb_channels, named)
1177    };
1178    if channels <= 0 {
1179        return Err(DecodeError::Adapter(
1180            "decoded audio frame has no channels".into(),
1181        ));
1182    }
1183    if named {
1184        return Ok(());
1185    }
1186    if channels == stream.nb_channels {
1187        let mut owned = AVChannelLayout::from_nb_channels(1);
1188        owned.copy(stream);
1189        frame.set_ch_layout(owned.into_inner());
1190        return Ok(());
1191    }
1192    let count = usize::try_from(channels).map_err(|_| DecodeError::OutOfRange)?;
1193    let speakers = SpeakerLayout::default_for(count).ok_or_else(|| unsupported_channels(count))?;
1194    frame.set_ch_layout(ffmpeg_layout(&speakers)?.into_inner());
1195    Ok(())
1196}
1197
1198pub(crate) fn audio_output_frame(sample_rate: i32, layout: &AVChannelLayout) -> AVFrame {
1199    let mut frame = AVFrame::new();
1200    frame.set_format(ffi::AV_SAMPLE_FMT_FLT);
1201    frame.set_sample_rate(sample_rate);
1202    let mut owned = AVChannelLayout::from_nb_channels(1);
1203    owned.copy(layout);
1204    frame.set_ch_layout(owned.into_inner());
1205    frame
1206}
1207
1208pub(crate) fn append_interleaved_audio(
1209    frame: &AVFrame,
1210    output: &mut [VecDeque<f32>],
1211) -> Result<(), DecodeError> {
1212    let packed = alpha2_ffmpeg_bridge::audio_f32_interleaved(frame).map_err(adapter_error)?;
1213    if output.is_empty() || packed.len() % output.len() != 0 {
1214        return Err(DecodeError::Adapter(
1215            "FFmpeg returned a partial audio frame".into(),
1216        ));
1217    }
1218    for frame in packed.chunks_exact(output.len()) {
1219        for (channel, sample) in output.iter_mut().zip(frame) {
1220            channel.push_back(*sample);
1221        }
1222    }
1223    Ok(())
1224}
1225
1226/// Whether an `AVCodecHWConfig`'s `methods` include `method`.
1227///
1228/// `bindgen` types the enum constants unsigned on Linux, macOS and `MinGW` and `int` on MSVC,
1229/// so both sides are widened.
1230pub(crate) fn has_hw_config_method(methods: i32, method: impl Into<i64>) -> bool {
1231    i64::from(methods) & method.into() != 0
1232}
1233
1234/// A seek position below any indexed timestamp, for reading from a stream's first packet.
1235///
1236/// MPEG-TS needs it because its first packet's decode time precedes the stream start time. A
1237/// demuxer that refuses such a time (the generic search AVI uses) is sought to the start time.
1238const STREAM_START_SEEK: i64 = i64::MIN / 2;
1239
1240enum Landing {
1241    /// The frame presented at the time.
1242    Presented(RawFrame),
1243    /// The first frame decoded was already later than the time.
1244    Late(RawFrame),
1245    /// No frame before the end of the stream.
1246    Empty,
1247}
1248
1249impl NativeDecoder {
1250    /// Selects strict failure (default) or bounded, reported recovery.
1251    pub fn set_decode_policy(&mut self, policy: DecodePolicy) {
1252        self.recovery.policy = policy;
1253    }
1254
1255    /// Sets the project's declared color for this source, which replaces the frame and stream tags.
1256    /// `None` leaves the tags in charge.
1257    pub fn declare_color(&mut self, color: Option<ColorMetadata>) {
1258        self.declared_color = color;
1259    }
1260
1261    /// Where `frame`'s chroma sits as its codec defines it; only hardware sessions report it.
1262    #[cfg(all(
1263        any(target_os = "linux", target_os = "macos", target_os = "windows"),
1264        feature = "hwdecode"
1265    ))]
1266    pub(crate) fn picture_chroma_location(&self, frame: &AVFrame) -> alpha2_media::ChromaLocation {
1267        crate::convert::decoded_chroma_location(self.decoder.codec_id, frame.chroma_location)
1268    }
1269
1270    /// The color `frame` is shown with: the declaration, else the frame's tags, else the stream's.
1271    pub(crate) fn picture_color(&self, frame: &AVFrame) -> Option<ColorMetadata> {
1272        self.declared_color
1273            .or_else(|| frame_color_metadata(frame))
1274            .or(self.color)
1275    }
1276
1277    /// Receives each diagnostic before recovery continues, including before errors.
1278    pub fn set_decode_reporter(
1279        &mut self,
1280        reporter: impl Fn(crate::DecodeDiagnostic) + Send + Sync + 'static,
1281    ) {
1282        self.recovery.reporter = Some(Box::new(reporter));
1283    }
1284
1285    /// Cumulative corruption and concealment diagnostics, including seeks.
1286    #[must_use]
1287    pub fn decode_diagnostics(&self) -> &DecodeDiagnostics {
1288        &self.recovery.diagnostics
1289    }
1290
1291    /// Opens the deterministically selected video stream.
1292    ///
1293    /// # Errors
1294    /// Returns an error when no decodable video stream exists.
1295    pub fn open(source: impl Into<SourceLocation>) -> Result<Self, DecodeError> {
1296        Self::open_with_threads(source, codec_thread_budget())
1297    }
1298
1299    /// Opens the selected stream with an explicit `FFmpeg` worker allocation.
1300    ///
1301    /// # Errors
1302    /// Returns an error when no decodable video stream exists.
1303    pub fn open_with_threads(
1304        source: impl Into<SourceLocation>,
1305        threads: i64,
1306    ) -> Result<Self, DecodeError> {
1307        if !(1..=64).contains(&threads) {
1308            return Err(DecodeError::OutOfRange);
1309        }
1310        let source = source.into();
1311        let mut input = open_input(&source)?;
1312        let probed = probe_context(&input, &source)?;
1313        let video_index = probed.selected_video.ok_or_else(|| {
1314            DecodeError::Unsupported("resource has no decodable video stream".into())
1315        })?;
1316        input.discard_all_but(video_index);
1317        let selected = probed
1318            .streams
1319            .iter()
1320            .find(|stream| stream.index == video_index)
1321            .ok_or(DecodeError::OutOfRange)?;
1322        if let Some((width, height)) = selected.dimensions {
1323            check_frame_size(width, height)?;
1324        }
1325        let orientation = selected.orientation;
1326        let sample_aspect_ratio = selected.sample_aspect_ratio;
1327        // HDR decodes like any 10-bit stream; the renderer tone-maps it or the project refuses it.
1328        let color = selected.color;
1329        let alpha = selected.alpha;
1330        let (time_base, decoder, dropped_layer) = {
1331            let stream = &input.streams()[video_index];
1332            let parameters = stream.codecpar();
1333            let codec = software_video_decoder(parameters.codec_id)?;
1334            let dropped_layer = session_dropped_layer(&parameters, alpha);
1335            let mut decoder = AVCodecContext::new(&codec);
1336            decoder.apply_codecpar(&parameters).map_err(adapter_error)?;
1337            decoder.set_pkt_timebase(stream.time_base);
1338            let unused = alpha2_ffmpeg_bridge::open_codec_context(
1339                &mut decoder,
1340                video_decoder_options(threads),
1341            )
1342            .map_err(adapter_error)?;
1343            reject_unused_decode_options(unused)?;
1344            (stream.time_base, decoder, dropped_layer)
1345        };
1346        let (prefetched, slack) = read_presentation_slack(&mut input, video_index, time_base);
1347        let (alpha, alpha_dropped) =
1348            alpha_companion(alpha, &prefetched, video_index, threads, time_base)?;
1349        Ok(Self {
1350            time_base,
1351            input,
1352            container_duration: probed.duration,
1353            streams: probed.streams,
1354            video_index,
1355            decoder,
1356            orientation,
1357            sample_aspect_ratio,
1358            color,
1359            declared_color: None,
1360            video_scaler: crate::convert::FrameScaler::default(),
1361            pending: VecDeque::new(),
1362            demux_eof: false,
1363            decoder_flushed: false,
1364            stages: DecodeStageTimings::default(),
1365            first_video_pts: None,
1366            recovery: Recovery::new(crate::recovery::time_base(time_base)),
1367            slack,
1368            prefetched,
1369            dropped_layer: alpha_dropped.or(dropped_layer),
1370            alpha,
1371        })
1372    }
1373
1374    /// Opens one hardware decode session for `spec` on an existing device.
1375    ///
1376    /// Failures carry a typed reason so callers can record why a source fell back.
1377    #[cfg(all(
1378        any(target_os = "linux", target_os = "macos", target_os = "windows"),
1379        feature = "hwdecode"
1380    ))]
1381    #[allow(clippy::too_many_lines)]
1382    pub(crate) fn open_hardware(
1383        source: impl Into<SourceLocation>,
1384        threads: i64,
1385        device: AVHWDeviceContext,
1386        spec: &HardwareDecoderSpec<'_>,
1387    ) -> Result<Self, HardwareOpenError> {
1388        use crate::video_frame::HardwareDecodeFallback::{
1389            DecoderOpenFailed, NoHardwareConfig, SourceUnavailable, UnsupportedColor,
1390        };
1391
1392        let unavailable = |error| HardwareOpenError::new(SourceUnavailable, error);
1393        let source = source.into();
1394        let mut input = open_input(&source).map_err(unavailable)?;
1395        let probed = probe_context(&input, &source).map_err(unavailable)?;
1396        let video_index = probed.selected_video.ok_or_else(|| {
1397            HardwareOpenError::new(
1398                SourceUnavailable,
1399                DecodeError::Unsupported("resource has no decodable video stream".into()),
1400            )
1401        })?;
1402        input.discard_all_but(video_index);
1403        let selected = probed
1404            .streams
1405            .iter()
1406            .find(|stream| stream.index == video_index)
1407            .ok_or_else(|| HardwareOpenError::new(SourceUnavailable, DecodeError::OutOfRange))?;
1408        if let Some((width, height)) = selected.dimensions {
1409            check_frame_size(width, height).map_err(unavailable)?;
1410        }
1411        let orientation = selected.orientation;
1412        let sample_aspect_ratio = selected.sample_aspect_ratio;
1413        let color = selected.color;
1414        if selected.color.is_some_and(ColorMetadata::is_hdr) {
1415            return Err(HardwareOpenError::new(
1416                UnsupportedColor,
1417                DecodeError::Unsupported("hardware export currently supports SDR only".into()),
1418            ));
1419        }
1420        let (time_base, decoder, dropped_layer) = {
1421            let stream = &input.streams()[video_index];
1422            let parameters = stream.codecpar();
1423            let dropped_layer = session_dropped_layer(&parameters, selected.alpha);
1424            if selected.alpha == Some(SourceAlpha::HevcAuxiliaryLayer)
1425                && spec.hevc_alpha_base_layer != crate::video_frame::HevcAlphaBaseLayer::AsCoded
1426            {
1427                return Err(HardwareOpenError::new(
1428                    crate::video_frame::HardwareDecodeFallback::AlphaChannel,
1429                    DecodeError::Unsupported(format!(
1430                        "{} decode changes the range of an HEVC stream with an alpha layer",
1431                        spec.backend
1432                    )),
1433                ));
1434            }
1435            // FFmpeg's hwaccels output no plane of a format's own alpha.
1436            if let Some(alpha @ SourceAlpha::Planar) = selected.alpha {
1437                return Err(HardwareOpenError::new(
1438                    crate::video_frame::HardwareDecodeFallback::AlphaChannel,
1439                    DecodeError::Unsupported(format!(
1440                        "the stream carries alpha ({}), which {} decode drops",
1441                        alpha.as_str(),
1442                        spec.backend
1443                    )),
1444                ));
1445            }
1446            let preferred = AVCodec::find_decoder(parameters.codec_id).ok_or_else(|| {
1447                HardwareOpenError::new(
1448                    NoHardwareConfig,
1449                    DecodeError::Unsupported("selected video codec has no decoder".into()),
1450                )
1451            })?;
1452            allowed_decoder(&preferred)
1453                .map_err(|error| HardwareOpenError::new(NoHardwareConfig, error))?;
1454            if let Some(codecs) = spec.hardware_codecs {
1455                let listed = hardware_codec_name(parameters.codec_id);
1456                if !listed.is_some_and(|name| codecs.contains(&name)) {
1457                    let name = listed.map_or_else(
1458                        || preferred.name().to_string_lossy().into_owned(),
1459                        str::to_owned,
1460                    );
1461                    return Err(HardwareOpenError::new(
1462                        NoHardwareConfig,
1463                        DecodeError::Unsupported(format!(
1464                            "{} has no hardware decoder for {name} here",
1465                            spec.backend
1466                        )),
1467                    ));
1468                }
1469            }
1470            let supported = |codec: &AVCodecRef<'_>| {
1471                (0..)
1472                    .map_while(|index| codec.hw_config(index))
1473                    .any(|config| {
1474                        config.device_type == spec.device_type
1475                            && config.pix_fmt == spec.pixel_format
1476                            && (!spec.require_device_context
1477                                || has_hw_config_method(
1478                                    config.methods,
1479                                    ffi::AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX,
1480                                ))
1481                    })
1482            };
1483            let Some(codec) =
1484                registered_video_decoders(parameters.codec_id).find(|codec| supported(codec))
1485            else {
1486                return Err(HardwareOpenError::new(
1487                    NoHardwareConfig,
1488                    DecodeError::Unsupported(format!(
1489                        "decoder {} has no {} hardware configuration",
1490                        preferred.name().to_string_lossy(),
1491                        spec.backend
1492                    )),
1493                ));
1494            };
1495            check_hardware_sample_profile(parameters.format, spec)?;
1496            check_hardware_crop(&parameters, spec)?;
1497            let open_failed = |error| HardwareOpenError::new(DecoderOpenFailed, error);
1498            let mut decoder = AVCodecContext::new(&codec);
1499            decoder
1500                .apply_codecpar(&parameters)
1501                .map_err(adapter_error)
1502                .map_err(open_failed)?;
1503            decoder.set_pkt_timebase(stream.time_base);
1504            decoder.set_get_format(Some(spec.get_format));
1505            decoder.set_hw_device_ctx(device);
1506            // Hardware decoders failing to open is expected here, so the open must fail cleanly.
1507            let unused = alpha2_ffmpeg_bridge::open_codec_context(
1508                &mut decoder,
1509                video_decoder_options(threads),
1510            )
1511            .map_err(adapter_error)
1512            .map_err(open_failed)?;
1513            reject_unused_decode_options(unused).map_err(open_failed)?;
1514            (stream.time_base, decoder, dropped_layer)
1515        };
1516        let (prefetched, slack) = read_presentation_slack(&mut input, video_index, time_base);
1517        let (alpha, alpha_dropped) =
1518            alpha_companion(selected.alpha, &prefetched, video_index, threads, time_base)
1519                .map_err(|error| HardwareOpenError::new(DecoderOpenFailed, error))?;
1520        Ok(Self {
1521            time_base,
1522            input,
1523            container_duration: probed.duration,
1524            streams: probed.streams,
1525            video_index,
1526            decoder,
1527            orientation,
1528            sample_aspect_ratio,
1529            color,
1530            declared_color: None,
1531            video_scaler: crate::convert::FrameScaler::default(),
1532            pending: VecDeque::new(),
1533            demux_eof: false,
1534            decoder_flushed: false,
1535            stages: DecodeStageTimings::default(),
1536            first_video_pts: None,
1537            recovery: Recovery::hardware(crate::recovery::time_base(time_base)),
1538            slack,
1539            prefetched,
1540            dropped_layer: alpha_dropped.or(dropped_layer),
1541            alpha,
1542        })
1543    }
1544
1545    /// Whether this decoder decodes an alpha stream beside its pictures (VP9 alpha).
1546    #[must_use]
1547    pub const fn decodes_alpha_stream(&self) -> bool {
1548        self.alpha.is_some()
1549    }
1550
1551    /// What this decoder leaves out (unreadable alpha, extra HEVC layers), or `None`.
1552    #[must_use]
1553    pub const fn dropped_layer(&self) -> Option<&DroppedLayer> {
1554        self.dropped_layer.as_ref()
1555    }
1556
1557    /// Effective end of the selected video source.
1558    ///
1559    /// Includes the container duration, which browser APIs expose, since the stream can end a few
1560    /// ticks earlier from time-base rounding.
1561    #[must_use]
1562    pub fn video_duration(&self) -> Option<MediaTime> {
1563        effective_media_duration(
1564            self.streams
1565                .iter()
1566                .find(|stream| stream.index == self.video_index)
1567                .and_then(|stream| stream.duration),
1568            self.container_duration,
1569        )
1570    }
1571
1572    /// Takes the spans accumulated since the last call.
1573    pub(crate) fn take_stage_timings(&mut self) -> DecodeStageTimings {
1574        std::mem::take(&mut self.stages)
1575    }
1576
1577    pub(crate) fn receive_available_raw(
1578        &mut self,
1579        cancel: &CancelToken,
1580    ) -> Result<Option<RawFrame>, DecodeError> {
1581        if self.alpha.is_none() {
1582            let Some(picture) = self.receive_picture(cancel)? else {
1583                return Ok(None);
1584            };
1585            self.recovery.progress(shown_pts(&picture))?;
1586            return Ok(Some(RawFrame::opaque(picture)));
1587        }
1588        loop {
1589            let companion = self.alpha.as_mut().expect("an alpha companion");
1590            if let Some(pair) = companion.next_pair(&mut self.recovery)? {
1591                self.recovery.progress(shown_pts(&pair))?;
1592                return Ok(Some(pair));
1593            }
1594            let Some(picture) = self.receive_picture(cancel)? else {
1595                return Ok(None);
1596            };
1597            self.alpha
1598                .as_mut()
1599                .expect("an alpha companion")
1600                .hold_picture(picture);
1601        }
1602    }
1603
1604    fn receive_picture(
1605        &mut self,
1606        cancel: &CancelToken,
1607    ) -> Result<Option<DecodedFrame>, DecodeError> {
1608        let mut budget = WorkBudget::new();
1609        loop {
1610            budget.step(cancel)?;
1611            let started = Instant::now();
1612            let received = DecodedFrame::receive(&mut self.decoder);
1613            self.stages.receive_frame = self.stages.receive_frame.saturating_add(started.elapsed());
1614            match received {
1615                Ok(frame) => {
1616                    if frame.flags
1617                        & i32::try_from(ffi::AV_FRAME_FLAG_CORRUPT).expect("flag fits i32")
1618                        != 0
1619                        || frame.decode_error_flags != 0
1620                    {
1621                        self.recovery
1622                            .corrupt("video frame", crate::recovery::pts(frame.pts))?;
1623                        continue;
1624                    }
1625                    #[cfg(test)]
1626                    VIDEO_FRAMES_DECODED.with(|decoded| decoded.set(decoded.get() + 1));
1627                    return Ok(Some(frame));
1628                }
1629                Err(RsmpegError::DecoderDrainError | RsmpegError::DecoderFlushedError) => {
1630                    return Ok(None);
1631                }
1632                Err(error) => {
1633                    self.recovery.error(error, "video receive", None)?;
1634                }
1635            }
1636        }
1637    }
1638
1639    pub(crate) fn convert_received(
1640        &mut self,
1641        frame: &RawFrame,
1642    ) -> Result<DecodedVideoFrame, DecodeError> {
1643        // HDR frames keep their components and color for the renderer to tone-map or refuse.
1644        let declared = self.picture_color(frame);
1645        let started = Instant::now();
1646        let converted = convert_video_frame(
1647            frame,
1648            frame.alpha().map(crate::alpha::FrameAlpha::Decoded),
1649            self.decoder.codec_id,
1650            self.time_base,
1651            declared.unwrap_or(ColorMetadata::UNDECLARED),
1652            &mut self.video_scaler,
1653        );
1654        self.stages.convert = self.stages.convert.saturating_add(started.elapsed());
1655        self.stages.conversions = self.stages.conversions.saturating_add(1);
1656        let mut converted = converted?;
1657        // With no declared color the frame goes untagged, so the renderer applies and reports the
1658        // same fallback. A repack to the identity matrix keeps the color it names.
1659        if declared.is_none() && converted.color == Some(ColorMetadata::UNDECLARED) {
1660            converted.color = None;
1661        }
1662        converted.orientation = self.orientation;
1663        converted.sample_aspect_ratio = self.picture_sample_aspect_ratio(frame);
1664        Ok(converted)
1665    }
1666
1667    /// The pixel aspect ratio `frame` is shown with: the container's declaration, else the
1668    /// picture's own (broadcast streams may change it), else the probed one.
1669    pub(crate) fn picture_sample_aspect_ratio(&self, frame: &AVFrame) -> SampleAspectRatio {
1670        // A ratio the container declares is the probed one, and overrides the picture's.
1671        if declared_sar(self.input.streams()[self.video_index].sample_aspect_ratio).is_some() {
1672            return self.sample_aspect_ratio;
1673        }
1674        declared_sar(frame.sample_aspect_ratio).unwrap_or(self.sample_aspect_ratio)
1675    }
1676
1677    pub(crate) fn raw_frame_pts(&self, frame: &AVFrame) -> Result<MediaTime, DecodeError> {
1678        let pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1679            frame.pts
1680        } else {
1681            frame.best_effort_timestamp
1682        };
1683        timestamp(pts, self.time_base).ok_or(DecodeError::OutOfRange)
1684    }
1685
1686    /// Drops queued packets and frames, keeping the stream selection.
1687    pub(crate) fn flush_video(&mut self) {
1688        let started = Instant::now();
1689        self.recovery.reset_progress();
1690        self.decoder.flush_buffers();
1691        if let Some(companion) = &mut self.alpha {
1692            companion.flush();
1693        }
1694        self.stages.seek = self.stages.seek.saturating_add(started.elapsed());
1695        self.pending.clear();
1696        self.prefetched.clear();
1697        self.demux_eof = false;
1698        self.decoder_flushed = false;
1699    }
1700
1701    /// Seeks to `target` and returns the raw frame presented there: the last frame at or before its
1702    /// presentation deadline ([`Self::presentation_deadline`]).
1703    ///
1704    /// The frame after it is kept for the next `decode_raw_next`. A stream starting after `target`
1705    /// answers with its first frame, one ending before it with its last.
1706    ///
1707    /// The landing is checked, not trusted: MPEG-TS/PS index every packet as a keyframe, and an
1708    /// open GOP's leading frames cannot decode from the I-frame. When the first decoded frame is
1709    /// past the deadline and not the stream's first, the seek restarts 1 s, 2 s, 4 s, ... earlier.
1710    ///
1711    /// # Errors
1712    /// Returns cancellation, seek, and decode failures, and [`DecodeError::OutOfRange`] for a
1713    /// stream with no frame at all.
1714    pub(crate) fn seek_raw(
1715        &mut self,
1716        target: MediaTime,
1717        cancel: &CancelToken,
1718    ) -> Result<RawFrame, DecodeError> {
1719        if cancel.is_cancelled() {
1720            return Err(DecodeError::Cancelled);
1721        }
1722        let start_time = self.input.streams()[self.video_index].start_time;
1723        let stream_start = timestamp(start_time, self.time_base).unwrap_or(MediaTime::ZERO);
1724        let deadline = self.presentation_deadline(target);
1725        let mut back_off = 0_i64;
1726        loop {
1727            // Seek from the deadline: a keyframe within the slack after the target
1728            // is the frame shown there.
1729            let from = MediaTime::from_ticks(deadline.ticks().saturating_sub(back_off));
1730            let from_start =
1731                from <= stream_start || self.first_video_pts.is_some_and(|first| deadline < first);
1732            if !from_start {
1733                // Rounded down, so a time just before a keyframe never seeks onto it.
1734                let position = av_rescale_q_rnd(
1735                    from.ticks(),
1736                    tick_base(),
1737                    self.time_base,
1738                    ffi::AV_ROUND_DOWN,
1739                );
1740                self.seek_video_to(position, cancel)?;
1741            } else if let Err(error) = self.seek_video_to(STREAM_START_SEEK, cancel) {
1742                if error == DecodeError::Cancelled {
1743                    return Err(error);
1744                }
1745                let start = if start_time == ffi::AV_NOPTS_VALUE {
1746                    0
1747                } else {
1748                    start_time
1749                };
1750                self.seek_video_to(start, cancel)?;
1751            }
1752            if let Some(companion) = &mut self.alpha {
1753                companion.restarted_from_stream_start(from_start);
1754            }
1755            let mut first = None;
1756            let landing = self.present_after_seek(target, &mut first, cancel)?;
1757            if from_start {
1758                // Read from the first packet, the first frame out is the stream's first frame.
1759                self.first_video_pts = first.or(self.first_video_pts);
1760            }
1761            match landing {
1762                Landing::Presented(frame) => return Ok(frame),
1763                Landing::Late(frame) if from_start || first == self.first_video_pts => {
1764                    return Ok(frame);
1765                }
1766                Landing::Empty if from_start => return Err(DecodeError::OutOfRange),
1767                Landing::Late(_) | Landing::Empty => {}
1768            }
1769            back_off = if back_off == 0 {
1770                TICKS_PER_SECOND
1771            } else {
1772                back_off.saturating_mul(2)
1773            };
1774        }
1775    }
1776
1777    fn seek_video_to(&mut self, position: i64, cancel: &CancelToken) -> Result<(), DecodeError> {
1778        interrupt_on_cancel(&self.input, cancel);
1779        let seek_started = Instant::now();
1780        let sought = self.input.seek(
1781            i32::try_from(self.video_index).map_err(|_| DecodeError::OutOfRange)?,
1782            position,
1783            i32::try_from(ffi::AVSEEK_FLAG_BACKWARD).expect("seek flag fits i32"),
1784        );
1785        self.stages.seek = self.stages.seek.saturating_add(seek_started.elapsed());
1786        self.stages.seeks = self.stages.seeks.saturating_add(1);
1787        sought.map_err(|error| seek_failure(&self.input, error, cancel))?;
1788        self.flush_video();
1789        Ok(())
1790    }
1791
1792    /// Decodes from a seek's landing to the frame presented at `target`, noting in `first` when the
1793    /// first decoded frame is presented.
1794    fn present_after_seek(
1795        &mut self,
1796        target: MediaTime,
1797        first: &mut Option<MediaTime>,
1798        cancel: &CancelToken,
1799    ) -> Result<Landing, DecodeError> {
1800        let deadline = self.presentation_deadline(target);
1801        let mut presented: Option<RawFrame> = None;
1802        let mut budget = WorkBudget::new();
1803        loop {
1804            budget.step(cancel)?;
1805            let Some(raw) = self.decode_raw_next(cancel)? else {
1806                return Ok(presented.map_or(Landing::Empty, Landing::Presented));
1807            };
1808            // A keyframe far before the target takes long to decode from, and is still progress.
1809            budget.progressed();
1810            #[cfg(test)]
1811            crate::recovery::take_frame_delay();
1812            let pts = self.raw_frame_pts(&raw)?;
1813            first.get_or_insert(pts);
1814            if pts > deadline {
1815                return Ok(match presented {
1816                    Some(frame) => {
1817                        self.pending.push_front(raw);
1818                        Landing::Presented(frame)
1819                    }
1820                    None => Landing::Late(raw),
1821                });
1822            }
1823            // A frame between the target and its deadline is the one shown.
1824            if pts >= target {
1825                return Ok(Landing::Presented(raw));
1826            }
1827            presented = Some(raw);
1828        }
1829    }
1830
1831    /// The latest timestamp a frame may carry and still be shown at `time`: `time` plus
1832    /// the stream's [`alpha2_time::presentation_slack`].
1833    #[must_use]
1834    pub fn presentation_deadline(&self, time: MediaTime) -> MediaTime {
1835        time.presentation_deadline(self.slack)
1836    }
1837
1838    /// When the frame the next [`Decoder::decode_next`] returns is presented, or `None` at the end.
1839    ///
1840    /// The frame is decoded now and kept for that call, so a caller can find the frame shown at a
1841    /// time without consuming the next one.
1842    ///
1843    /// # Errors
1844    /// Returns cancellation and decode failures.
1845    pub fn peek_video_pts(
1846        &mut self,
1847        cancel: &CancelToken,
1848    ) -> Result<Option<MediaTime>, DecodeError> {
1849        self.peek_raw_pts(cancel)
1850    }
1851
1852    /// The presentation time of the frame `decode_raw_next` returns next (decoded now and
1853    /// kept); `None` at the end.
1854    ///
1855    /// # Errors
1856    /// Returns cancellation and decode failures.
1857    pub(crate) fn peek_raw_pts(
1858        &mut self,
1859        cancel: &CancelToken,
1860    ) -> Result<Option<MediaTime>, DecodeError> {
1861        let Some(raw) = self.decode_raw_next(cancel)? else {
1862            return Ok(None);
1863        };
1864        let pts = self.raw_frame_pts(&raw);
1865        self.pending.push_front(raw);
1866        pts.map(Some)
1867    }
1868
1869    pub(crate) fn decode_raw_next(
1870        &mut self,
1871        cancel: &CancelToken,
1872    ) -> Result<Option<RawFrame>, DecodeError> {
1873        if cancel.is_cancelled() {
1874            return Err(DecodeError::Cancelled);
1875        }
1876        if let Some(frame) = self.pending.pop_front() {
1877            return Ok(Some(frame));
1878        }
1879        interrupt_on_cancel(&self.input, cancel);
1880        let mut budget = WorkBudget::new();
1881        let mut foreign = false;
1882        loop {
1883            // Another stream's packet is skipped, not work (see `fill_pending`).
1884            if std::mem::take(&mut foreign) {
1885                if cancel.is_cancelled() {
1886                    return Err(DecodeError::Cancelled);
1887                }
1888            } else {
1889                budget.step(cancel)?;
1890            }
1891            if let Some(frame) = self.pending.pop_front() {
1892                return Ok(Some(frame));
1893            }
1894            if let Some(frame) = self.receive_available_raw(cancel)? {
1895                return Ok(Some(frame));
1896            }
1897            if self.demux_eof {
1898                if !self.decoder_flushed {
1899                    match self.decoder.send_packet(None) {
1900                        Ok(()) | Err(RsmpegError::DecoderFlushedError) => {}
1901                        Err(RsmpegError::DecoderFullError) => continue,
1902                        Err(error) => {
1903                            self.recovery.error(error, "flush", None)?;
1904                            continue;
1905                        }
1906                    }
1907                    if let Some(companion) = &mut self.alpha {
1908                        companion.send_end(&mut self.recovery)?;
1909                    }
1910                    self.decoder_flushed = true;
1911                    continue;
1912                }
1913                self.recovery.video_eof()?;
1914                return Ok(None);
1915            }
1916            let demux_started = Instant::now();
1917            let packet = self
1918                .prefetched
1919                .pop_front()
1920                .unwrap_or_else(|| self.input.read_packet());
1921            self.stages.demux = self.stages.demux.saturating_add(demux_started.elapsed());
1922            #[cfg(test)]
1923            take_read_delay();
1924            let packet = match packet {
1925                Ok(Some(packet)) => packet,
1926                Ok(None) => {
1927                    self.demux_eof = true;
1928                    continue;
1929                }
1930                Err(error) => {
1931                    let error = demux_failure(&self.input, error, cancel)?;
1932                    self.recovery.error(error, "video demux", None)?;
1933                    continue;
1934                }
1935            };
1936            if usize::try_from(packet.stream_index).ok() != Some(self.video_index) {
1937                foreign = true;
1938                continue;
1939            }
1940            budget.advanced();
1941            if packet.flags & i32::try_from(ffi::AV_PKT_FLAG_CORRUPT).expect("flag fits i32") != 0 {
1942                self.recovery
1943                    .corrupt("video packet", crate::recovery::pts(packet.pts))?;
1944                continue;
1945            }
1946            submit_packet(
1947                |drain| {
1948                    if drain {
1949                        return self.drain_into_pending(cancel);
1950                    }
1951                    let started = Instant::now();
1952                    let sent = self.decoder.send_packet(Some(&packet));
1953                    self.stages.send_packet += started.elapsed();
1954                    match sent {
1955                        Ok(()) => Ok(true),
1956                        Err(RsmpegError::DecoderFullError) => Ok(false),
1957                        Err(error) => {
1958                            self.recovery.error(error, "video send", Some(packet.pts))?;
1959                            Ok(true)
1960                        }
1961                    }
1962                },
1963                &mut budget,
1964                cancel,
1965            )?;
1966            if let Some(companion) = &mut self.alpha {
1967                companion.send(&packet, &mut self.recovery)?;
1968            }
1969        }
1970    }
1971}
1972
1973impl NativeDecoder {
1974    fn drain_into_pending(&mut self, cancel: &CancelToken) -> Result<bool, DecodeError> {
1975        let corrupt_before = self.recovery.diagnostics.corrupt_packets.len();
1976        let taken_before = self.alpha.as_ref().map(AlphaCompanion::pictures_taken);
1977        if let Some(frame) = self.receive_available_raw(cancel)? {
1978            self.pending.push_back(frame);
1979            return Ok(true);
1980        }
1981        Ok(
1982            self.recovery.diagnostics.corrupt_packets.len() > corrupt_before
1983                || self.alpha.as_ref().map(AlphaCompanion::pictures_taken) != taken_before,
1984        )
1985    }
1986}
1987
1988impl Decoder for NativeDecoder {
1989    fn streams(&self) -> &[StreamInfo] {
1990        &self.streams
1991    }
1992
1993    fn flush(&mut self) -> Result<(), DecodeError> {
1994        self.flush_video();
1995        Ok(())
1996    }
1997
1998    fn seek(
1999        &mut self,
2000        request: DecodeRequest,
2001        cancel: &CancelToken,
2002    ) -> Result<DecodeResult, DecodeError> {
2003        let raw = self.seek_raw(request.time, cancel)?;
2004        let frame = self.convert_received(&raw)?;
2005        Ok(DecodeResult {
2006            request,
2007            event: DecodeEvent::Video(frame),
2008        })
2009    }
2010
2011    fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError> {
2012        if cancel.is_cancelled() {
2013            return Err(DecodeError::Cancelled);
2014        }
2015        match self.decode_raw_next(cancel)? {
2016            Some(frame) => Ok(DecodeEvent::Video(self.convert_received(&frame)?)),
2017            None => Ok(DecodeEvent::EndOfStream),
2018        }
2019    }
2020}
2021
2022/// Decoders that open without a hardware session and then fail every packet (`FFmpeg`'s own `av1`
2023/// answers `ENOSYS`). The pinned SDK decodes AV1 with libdav1d instead.
2024const HWACCEL_ONLY_DECODERS: &[&str] = &["av1"];
2025
2026/// Every decoder registered for `codec_id`, preferred first. External software decoders are
2027/// preferred, yet only `FFmpeg`'s own `av1` carries hardware configurations, so hardware sessions
2028/// look through all of them.
2029pub(crate) fn registered_video_decoders(
2030    codec_id: ffi::AVCodecID,
2031) -> impl Iterator<Item = AVCodecRef<'static>> {
2032    AVCodec::iterate().filter(move |codec| {
2033        codec.id == codec_id
2034            && AVCodec::find_decoder_by_name(codec.name())
2035                .is_some_and(|found| found.as_ptr() == codec.as_ptr())
2036    })
2037}
2038
2039/// The first decoder `FFmpeg` would pick for a software session, skipping hardware-only ones.
2040pub(crate) fn software_video_decoder(
2041    codec_id: ffi::AVCodecID,
2042) -> Result<AVCodecRef<'static>, DecodeError> {
2043    let Some(preferred) = AVCodec::find_decoder(codec_id) else {
2044        return Err(DecodeError::Unsupported(
2045            "selected video codec has no decoder".into(),
2046        ));
2047    };
2048    allowed_decoder(&preferred)?;
2049    let hardware_only =
2050        |codec: &AVCodecRef<'_>| HWACCEL_ONLY_DECODERS.contains(&&*codec.name().to_string_lossy());
2051    if !hardware_only(&preferred) {
2052        return Ok(preferred);
2053    }
2054    let experimental = i32::try_from(ffi::AV_CODEC_CAP_EXPERIMENTAL).unwrap_or(0);
2055    AVCodec::iterate()
2056        .find(|codec| {
2057            codec.id == codec_id
2058                && AVCodec::find_decoder_by_name(codec.name())
2059                    .is_some_and(|found| found.as_ptr() == codec.as_ptr())
2060                && codec.capabilities & experimental == 0
2061                && !hardware_only(codec)
2062        })
2063        .ok_or_else(|| DecodeError::Unsupported(hardware_only_reason(&preferred)))
2064}
2065
2066const HEVC_ALPHA_NOT_DECODED: &str = "alpha in an HEVC auxiliary layer is not decoded";
2067const NO_ALPHA_STREAM: &str = "its blocks carry no alpha data";
2068
2069/// Why a software session would decode `stream` without its alpha, for conform reports.
2070#[must_use]
2071pub fn alpha_dropped_reason(stream: &StreamInfo) -> Option<&'static str> {
2072    match stream.alpha? {
2073        SourceAlpha::HevcAuxiliaryLayer => Some(HEVC_ALPHA_NOT_DECODED),
2074        SourceAlpha::Vp9SideData | SourceAlpha::Planar => None,
2075    }
2076}
2077
2078fn shown_pts(frame: &AVFrame) -> Option<i64> {
2079    crate::recovery::pts(if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
2080        frame.pts
2081    } else {
2082        frame.best_effort_timestamp
2083    })
2084}
2085
2086fn alpha_companion(
2087    alpha: Option<SourceAlpha>,
2088    prefetched: &Prefetched,
2089    video_index: usize,
2090    threads: i64,
2091    time_base: AVRational,
2092) -> Result<(Option<AlphaCompanion>, Option<DroppedLayer>), DecodeError> {
2093    if alpha != Some(SourceAlpha::Vp9SideData) {
2094        return Ok((None, None));
2095    }
2096    let first = prefetched.iter().find_map(|packet| match packet {
2097        Ok(Some(packet)) if usize::try_from(packet.stream_index).ok() == Some(video_index) => {
2098            Some(packet)
2099        }
2100        _ => None,
2101    });
2102    if !first.is_some_and(crate::alpha::carries_alpha_stream) {
2103        return Ok((
2104            None,
2105            Some(DroppedLayer {
2106                code: "alpha-dropped",
2107                reason: NO_ALPHA_STREAM.to_owned(),
2108            }),
2109        ));
2110    }
2111    Ok((Some(AlphaCompanion::open(threads, time_base)?), None))
2112}
2113
2114/// `FFmpeg` decodes no HEVC auxiliary alpha layer or MV-HEVC view.
2115fn session_dropped_layer(
2116    parameters: &rsmpeg::avcodec::AVCodecParameters,
2117    alpha: Option<SourceAlpha>,
2118) -> Option<DroppedLayer> {
2119    let dropped = |code, reason: &str| {
2120        Some(DroppedLayer {
2121            code,
2122            reason: reason.to_owned(),
2123        })
2124    };
2125    match alpha {
2126        Some(SourceAlpha::HevcAuxiliaryLayer) => dropped("alpha-dropped", HEVC_ALPHA_NOT_DECODED),
2127        None if parameters.codec_id == ffi::AV_CODEC_ID_HEVC
2128            && alpha2_host_core::parameter_sets::hevc_layers(
2129                &alpha2_ffmpeg_bridge::codec_parameters_extradata(parameters),
2130            ) == Some(alpha2_host_core::parameter_sets::HevcLayers::Extra) =>
2131        {
2132            dropped(
2133                "extra-layers-dropped",
2134                "the HEVC layers besides the base layer are not decoded",
2135            )
2136        }
2137        _ => None,
2138    }
2139}
2140
2141/// How `stream` carries alpha: VP9's `alpha_mode` tag, an HEVC auxiliary layer, or a pixel
2142/// format with an alpha plane.
2143fn source_alpha(
2144    metadata: Option<rsmpeg::avutil::AVDictionaryRef<'_>>,
2145    parameters: &rsmpeg::avcodec::AVCodecParameters,
2146) -> Option<SourceAlpha> {
2147    let tagged = || {
2148        metadata
2149            .and_then(|metadata| {
2150                metadata
2151                    .get(c"alpha_mode", None, 0)
2152                    .map(|entry| entry.value().to_bytes() == b"1")
2153            })
2154            .unwrap_or(false)
2155    };
2156    match parameters.codec_id {
2157        ffi::AV_CODEC_ID_VP9 if tagged() => return Some(SourceAlpha::Vp9SideData),
2158        ffi::AV_CODEC_ID_HEVC
2159            if alpha2_host_core::parameter_sets::hevc_layers(
2160                &alpha2_ffmpeg_bridge::codec_parameters_extradata(parameters),
2161            ) == Some(alpha2_host_core::parameter_sets::HevcLayers::AuxiliaryAlpha) =>
2162        {
2163            return Some(SourceAlpha::HevcAuxiliaryLayer);
2164        }
2165        _ => {}
2166    }
2167    alpha2_ffmpeg_bridge::sample_profile(parameters.format)
2168        .filter(|profile| profile.has_alpha)
2169        .map(|_| SourceAlpha::Planar)
2170}
2171
2172fn hardware_only_reason(decoder: &AVCodecRef<'_>) -> String {
2173    let name = decoder.name().to_string_lossy();
2174    format!(
2175        "{name} needs a hardware decoder; this runtime has no software {} decoder",
2176        name.to_uppercase()
2177    )
2178}
2179
2180/// Why this runtime cannot decode `stream` without a hardware session, or `None` when software can
2181/// (some preferred decoders are hardware-only; AV1 needs libdav1d).
2182#[must_use]
2183pub fn software_decode_unsupported(stream: &StreamInfo) -> Option<String> {
2184    if stream.kind != StreamKind::Video {
2185        return None;
2186    }
2187    let name = CString::new(stream.codec.as_str()).ok()?;
2188    let decoder = AVCodec::find_decoder_by_name(&name)?;
2189    software_video_decoder(decoder.id)
2190        .err()
2191        .map(|error| match error {
2192            DecodeError::Unsupported(reason) => reason,
2193            error => error.to_string(),
2194        })
2195}
2196
2197/// The longer of a stream's and its container's duration.
2198pub(crate) fn effective_media_duration(
2199    stream_duration: Option<MediaTime>,
2200    container_duration: Option<MediaTime>,
2201) -> Option<MediaTime> {
2202    stream_duration.into_iter().chain(container_duration).max()
2203}
2204
2205/// Unpadded bytes of one picture of `format`, or `None` for a format `FFmpeg` does not know.
2206fn decoded_frame_bytes(format: i32, (width, height): (u32, u32)) -> Option<u64> {
2207    let size = rsmpeg::avutil::AVImage::get_buffer_size(
2208        format,
2209        i32::try_from(width).ok()?,
2210        i32::try_from(height).ok()?,
2211        1,
2212    )?;
2213    u64::try_from(size).ok().filter(|bytes| *bytes > 0)
2214}
2215
2216/// The `FFmpeg` name a device's hardware codec list uses for `codec_id`.
2217#[cfg(all(
2218    any(target_os = "linux", target_os = "macos", target_os = "windows"),
2219    feature = "hwdecode"
2220))]
2221const fn hardware_codec_name(codec_id: ffi::AVCodecID) -> Option<&'static str> {
2222    match codec_id {
2223        ffi::AV_CODEC_ID_H264 => Some("h264"),
2224        ffi::AV_CODEC_ID_HEVC => Some("hevc"),
2225        ffi::AV_CODEC_ID_VP9 => Some("vp9"),
2226        ffi::AV_CODEC_ID_AV1 => Some("av1"),
2227        _ => None,
2228    }
2229}
2230
2231/// Refuses a stream whose SPS crops its left or top edge on a backend whose surfaces lose that crop
2232/// ([`HardwareDecoderSpec::keeps_leading_crop`]). An unreadable SPS is not refused.
2233#[cfg(all(
2234    any(target_os = "linux", target_os = "macos", target_os = "windows"),
2235    feature = "hwdecode"
2236))]
2237fn check_hardware_crop(
2238    parameters: &rsmpeg::avcodec::AVCodecParameters,
2239    spec: &HardwareDecoderSpec<'_>,
2240) -> Result<(), HardwareOpenError> {
2241    if spec.keeps_leading_crop {
2242        return Ok(());
2243    }
2244    let extradata = alpha2_ffmpeg_bridge::codec_parameters_extradata(parameters);
2245    let codec = match parameters.codec_id {
2246        ffi::AV_CODEC_ID_H264 => Some(alpha2_host_core::parameter_sets::ParameterSetCodec::H264),
2247        ffi::AV_CODEC_ID_HEVC => Some(alpha2_host_core::parameter_sets::ParameterSetCodec::Hevc),
2248        _ => None,
2249    };
2250    match codec.and_then(|codec| alpha2_host_core::parameter_sets::leading_crop(codec, &extradata))
2251    {
2252        Some((left, top)) if left > 0 || top > 0 => Err(HardwareOpenError::new(
2253            crate::video_frame::HardwareDecodeFallback::UnsupportedCrop,
2254            DecodeError::Unsupported(format!(
2255                "{} decode does not show a picture cropped {left} columns from the left and {top} rows from the top",
2256                spec.backend
2257            )),
2258        )),
2259        _ => Ok(()),
2260    }
2261}
2262
2263/// Rejects sample formats with no resident presentation path.
2264///
2265/// Only 8-bit 4:2:0, or 10-bit where the renderer presents it, reaches the GPU path; refusing at
2266/// open avoids a mid-export surface failure. An undeclared format is left to the import check.
2267#[cfg(all(
2268    any(target_os = "linux", target_os = "macos", target_os = "windows"),
2269    feature = "hwdecode"
2270))]
2271fn check_hardware_sample_profile(
2272    format: ffi::AVPixelFormat,
2273    spec: &HardwareDecoderSpec<'_>,
2274) -> Result<(), HardwareOpenError> {
2275    let Some(profile) = alpha2_ffmpeg_bridge::sample_profile(format) else {
2276        return Ok(());
2277    };
2278    let maximum_depth = if spec.ten_bit { 10 } else { 8 };
2279    if profile.is_yuv_420 && !profile.has_alpha && profile.bit_depth <= maximum_depth {
2280        return Ok(());
2281    }
2282    Err(HardwareOpenError::new(
2283        crate::video_frame::HardwareDecodeFallback::UnsupportedProfile,
2284        DecodeError::Unsupported(format!(
2285            "{} decode does not present {}-bit {} input",
2286            spec.backend,
2287            profile.bit_depth,
2288            if profile.is_yuv_420 {
2289                "4:2:0"
2290            } else {
2291                "non-4:2:0"
2292            }
2293        )),
2294    ))
2295}
2296
2297/// Demuxers a source may open with, by `FFmpeg` short name. Each reads only the file it is given;
2298/// demuxers that open other files (HLS, `ffconcat`, image-sequence patterns) are excluded so an
2299/// asset cannot pull in media a request never named.
2300pub(crate) const SOURCE_CONTAINERS: &CStr =
2301    c"mov,matroska,mpegts,avi,mp3,aac,wav,flac,ogg,png_pipe,jpeg_pipe,webp_pipe,gif";
2302
2303/// Decoders a source may select, by `FFmpeg` name: the codecs alpha2 documents and tests and
2304/// mainstream production codecs. A stream of any other codec is `Unsupported`, unless the process
2305/// allowed every decoder ([`allow_every_decoder`]).
2306pub const SOURCE_DECODERS: &[&str] = &[
2307    // Video.
2308    "h264",
2309    "hevc",
2310    "vp8",
2311    "vp9",
2312    "av1",
2313    "libdav1d",
2314    "mpeg4",
2315    "mpeg2video",
2316    "mpeg1video",
2317    "prores",
2318    "dnxhd",
2319    "ffv1",
2320    "v210",
2321    "mjpeg",
2322    "qtrle",
2323    "rawvideo",
2324    "png",
2325    "webp",
2326    "gif",
2327    // Audio.
2328    "aac",
2329    "aac_latm",
2330    "mp3float",
2331    "mp3",
2332    "mp2",
2333    "mp2float",
2334    "opus",
2335    "libopus",
2336    "vorbis",
2337    "flac",
2338    "alac",
2339    "ac3",
2340    "eac3",
2341    "dca",
2342    "pcm_s16le",
2343    "pcm_s16be",
2344    "pcm_s24le",
2345    "pcm_s24be",
2346    "pcm_s32le",
2347    "pcm_s32be",
2348    "pcm_f32le",
2349    "pcm_f32be",
2350    "pcm_f64le",
2351    "pcm_f64be",
2352    "pcm_u8",
2353    "pcm_s8",
2354    "pcm_alaw",
2355    "pcm_mulaw",
2356];
2357
2358static EVERY_DECODER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
2359
2360/// Lets sources select every decoder of the linked `FFmpeg`, not only [`SOURCE_DECODERS`], for
2361/// the rest of the process. A process setting for integrators who decode only trusted files.
2362pub fn allow_every_decoder() {
2363    EVERY_DECODER.store(true, std::sync::atomic::Ordering::Relaxed);
2364}
2365
2366#[cfg(test)]
2367pub(crate) fn set_every_decoder(every: bool) {
2368    EVERY_DECODER.store(every, std::sync::atomic::Ordering::Relaxed);
2369}
2370
2371/// Whether [`allow_every_decoder`] was called.
2372#[must_use]
2373pub fn every_decoder_allowed() -> bool {
2374    EVERY_DECODER.load(std::sync::atomic::Ordering::Relaxed)
2375}
2376
2377/// The [`SOURCE_DECODERS`] the linked `FFmpeg` has.
2378#[must_use]
2379pub fn source_decoders() -> Vec<&'static str> {
2380    SOURCE_DECODERS
2381        .iter()
2382        .copied()
2383        .filter(|name| {
2384            CString::new(*name)
2385                .ok()
2386                .and_then(|name| AVCodec::find_decoder_by_name(&name))
2387                .is_some()
2388        })
2389        .collect()
2390}
2391
2392/// Refuses a decoder outside [`SOURCE_DECODERS`] unless every decoder is allowed.
2393pub(crate) fn allowed_decoder(codec: &AVCodecRef<'_>) -> Result<(), DecodeError> {
2394    let name = codec.name().to_string_lossy();
2395    if every_decoder_allowed() || SOURCE_DECODERS.contains(&&*name) {
2396        Ok(())
2397    } else {
2398        Err(DecodeError::Unsupported(format!(
2399            "the {name} decoder is not one alpha2 decodes sources with"
2400        )))
2401    }
2402}
2403
2404/// [`SOURCE_DECODERS`] as `FFmpeg`'s `codec_whitelist`, or `None` when every decoder is allowed.
2405fn decoder_whitelist() -> Option<&'static CStr> {
2406    static LIST: std::sync::OnceLock<CString> = std::sync::OnceLock::new();
2407    (!every_decoder_allowed()).then(|| {
2408        LIST.get_or_init(|| {
2409            CString::new(SOURCE_DECODERS.join(",")).expect("decoder names have no NUL")
2410        })
2411        .as_c_str()
2412    })
2413}
2414
2415/// Opens a source with [`SOURCE_CONTAINERS`]: a file through the `file` protocol only, so nothing
2416/// reaches past a local path, or a remote object through its own reader, which may open nothing
2417/// else; probing opens [`SOURCE_DECODERS`] only.
2418pub(crate) fn open_input(source: &SourceLocation) -> Result<DemuxInput, DecodeError> {
2419    #[cfg(test)]
2420    INPUTS_OPENED.with(|opened| opened.set(opened.get() + 1));
2421    refuse_oversized_still(source)?;
2422    let opened = match source {
2423        SourceLocation::File(path) => alpha2_ffmpeg_bridge::open_input(
2424            InputLocation::File(path),
2425            SOURCE_CONTAINERS,
2426            decoder_whitelist(),
2427        ),
2428        SourceLocation::Remote(object) => {
2429            let open =
2430                || -> std::io::Result<Box<dyn InputReader>> { Ok(Box::new(object.reader())) };
2431            let shown = object.shown_url();
2432            let custom = CustomInput {
2433                name: shown.rsplit('/').next().unwrap_or(shown),
2434                length: object.len(),
2435                open: &open,
2436            };
2437            alpha2_ffmpeg_bridge::open_input(
2438                InputLocation::Custom(&custom),
2439                SOURCE_CONTAINERS,
2440                decoder_whitelist(),
2441            )
2442        }
2443    };
2444    opened.map_err(|error| match error {
2445        OpenInputError::Path(error) => DecodeError::Unsupported(format!("media path {error}")),
2446        OpenInputError::Refused(format) => DecodeError::Unsupported(format!(
2447            "the file is {format} input, which is not a container alpha2 reads"
2448        )),
2449        OpenInputError::Read(error) => read_failure(&error),
2450        OpenInputError::Ffmpeg(error) => adapter_error(error),
2451    })
2452}
2453
2454/// A source reader's failure as the decode error it is.
2455fn read_failure(error: &std::io::Error) -> DecodeError {
2456    alpha2_host_core::remote::decode_error(error)
2457        .unwrap_or_else(|| DecodeError::Adapter(format!("the source could not be read: {error}")))
2458}
2459
2460/// A demux or seek failure on `input`: its reader's failure when it had one, else `FFmpeg`'s.
2461pub(crate) fn demux_error(input: &DemuxInput, error: RsmpegError) -> DecodeError {
2462    input
2463        .take_read_error()
2464        .map_or_else(|| adapter_error(error), |failure| read_failure(&failure))
2465}
2466
2467/// The source's bytes from the first, at most `limit`.
2468fn source_head(source: &SourceLocation, limit: u64) -> Option<Vec<u8>> {
2469    let mut head = Vec::new();
2470    match source {
2471        SourceLocation::File(path) => {
2472            std::fs::File::open(path)
2473                .ok()?
2474                .take(limit)
2475                .read_to_end(&mut head)
2476                .ok()?;
2477        }
2478        SourceLocation::Remote(object) => {
2479            object.reader().take(limit).read_to_end(&mut head).ok()?;
2480        }
2481    }
2482    Some(head)
2483}
2484
2485/// Refuses a PNG, JPEG or WebP whose header states a picture larger than alpha2 renders, since
2486/// `FFmpeg` learns a still's size only by decoding it. Anything else is left to `FFmpeg`.
2487fn refuse_oversized_still(source: &SourceLocation) -> Result<(), DecodeError> {
2488    // Holds the size field of the three formats, after any Exif and colour profile segments.
2489    const HEAD_BYTES: u64 = 1 << 20;
2490    let Some(signature) = source_head(source, 12) else {
2491        return Ok(());
2492    };
2493    if still_format(&signature).is_none() {
2494        return Ok(());
2495    }
2496    let Some(head) = source_head(source, HEAD_BYTES) else {
2497        return Ok(());
2498    };
2499    match probe_still(&head) {
2500        Err(error @ DecodeError::Unsupported(_)) => Err(error),
2501        _ => Ok(()),
2502    }
2503}
2504
2505#[cfg(test)]
2506thread_local! {
2507    /// How many inputs [`open_input`] has opened on this thread.
2508    pub(crate) static INPUTS_OPENED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2509    /// How many video frames the codec has given a [`NativeDecoder`] on this thread.
2510    pub(crate) static VIDEO_FRAMES_DECODED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2511}
2512
2513/// Lets `cancel` interrupt a blocking `FFmpeg` call on `input` (it returns `AVERROR_EXIT`).
2514pub(crate) fn interrupt_on_cancel(input: &DemuxInput, cancel: &CancelToken) {
2515    let cancel = cancel.clone();
2516    input.interrupt_when(move || cancel.is_cancelled());
2517}
2518
2519/// A demux or seek failure on `input`, as a cancel when the cancel stopped it and as its reader's
2520/// failure when the reader failed: neither is damage a decode policy may skip.
2521fn demux_failure(
2522    input: &DemuxInput,
2523    error: RsmpegError,
2524    cancel: &CancelToken,
2525) -> Result<RsmpegError, DecodeError> {
2526    if cancel.is_cancelled() {
2527        return Err(DecodeError::Cancelled);
2528    }
2529    match input.take_read_error() {
2530        Some(failure) => Err(read_failure(&failure)),
2531        None => Ok(error),
2532    }
2533}
2534
2535/// A seek failure on `input`, as [`demux_failure`] reads it.
2536fn seek_failure(input: &DemuxInput, error: RsmpegError, cancel: &CancelToken) -> DecodeError {
2537    demux_failure(input, error, cancel).map_or_else(|failure| failure, adapter_error)
2538}
2539
2540/// Single-picture demuxers whose decoder, not the container, carries orientation (`FFmpeg` puts a
2541/// JPEG's Exif `Orientation` on the frame).
2542const STILL_IMAGE_FORMATS: [&CStr; 3] = [c"jpeg_pipe", c"png_pipe", c"webp_pipe"];
2543
2544fn is_still_image_format(input: &DemuxInput) -> bool {
2545    STILL_IMAGE_FORMATS.contains(&input.iformat().name())
2546}
2547
2548/// The orientation a still picture's decoder attaches, read by decoding it once at reduced size
2549/// when possible. `None` when there is none or the picture does not decode.
2550fn still_image_orientation(source: &SourceLocation, index: usize) -> Option<Orientation> {
2551    let mut input = open_input(source).ok()?;
2552    let (codec, mut decoder) = {
2553        let stream = input.streams().get(index)?;
2554        let parameters = stream.codecpar();
2555        let codec = software_video_decoder(parameters.codec_id).ok()?;
2556        let mut decoder = AVCodecContext::new(&codec);
2557        decoder.apply_codecpar(&parameters).ok()?;
2558        decoder.set_pkt_timebase(stream.time_base);
2559        (codec, decoder)
2560    };
2561    let mut options = video_decoder_options(1);
2562    if codec.max_lowres > 0 {
2563        options = options.set_int(c"lowres", i64::from(codec.max_lowres), 0);
2564    }
2565    alpha2_ffmpeg_bridge::open_codec_context(&mut decoder, options).ok()?;
2566    let mut sent = false;
2567    // One picture is one packet; a few more allow for a demuxer that splits it.
2568    for _ in 0..16 {
2569        match decoder.receive_frame() {
2570            Ok(frame) => {
2571                return alpha2_ffmpeg_bridge::frame_display_rotation(&frame)
2572                    .and_then(orientation_from_display);
2573            }
2574            Err(RsmpegError::DecoderDrainError) => {}
2575            Err(_) => return None,
2576        }
2577        match input.read_packet().ok()? {
2578            Some(packet) if usize::try_from(packet.stream_index).ok() == Some(index) => {
2579                decoder.send_packet(Some(&packet)).ok()?;
2580                sent = true;
2581            }
2582            Some(_) => {}
2583            None if sent => {
2584                decoder.send_packet(None).ok()?;
2585                sent = false;
2586            }
2587            None => return None,
2588        }
2589    }
2590    None
2591}
2592
2593#[allow(clippy::too_many_lines)]
2594/// Initial tail read for [`parsed_end`], matching `FFmpeg`'s `DURATION_MAX_READ_SIZE`; doubled up
2595/// to five times while no timed packet is found.
2596const PARSED_END_READ: u64 = 250_000;
2597
2598/// Where `input`'s packets end (latest `pts + duration`, `AV_TIME_BASE` units) when `FFmpeg`
2599/// estimated the duration from timestamps; `None` otherwise.
2600///
2601/// That estimate (MPEG-TS, MPEG-PS) reads unparsed packets, so one PES carrying several AAC frames
2602/// ends at the first frame, up to 0.19 s short. This rereads the tail through the parsers on a
2603/// separate input, leaving `input`'s position untouched.
2604fn parsed_end(input: &DemuxInput, source: &SourceLocation) -> Option<i64> {
2605    if input.duration_estimation_method != ffi::AVFMT_DURATION_FROM_PTS {
2606        return None;
2607    }
2608    let size = source.byte_length().ok()?;
2609    let mut tail = open_input(source).ok()?;
2610    let streams = tail
2611        .streams()
2612        .iter()
2613        .map(|stream| {
2614            let kind = stream.codecpar().codec_type();
2615            (kind.is_audio() || kind.is_video()).then_some(stream.time_base)
2616        })
2617        .collect::<Vec<_>>();
2618    let av_time_base = ra(1, i32::try_from(ffi::AV_TIME_BASE).ok()?);
2619    for doubling in 0..6 {
2620        let from = size.saturating_sub(PARSED_END_READ << doubling);
2621        tail.seek(
2622            -1,
2623            i64::try_from(from).ok()?,
2624            i32::try_from(ffi::AVSEEK_FLAG_BYTE).ok()?,
2625        )
2626        .ok()?;
2627        let mut end = None::<i64>;
2628        while let Ok(Some(packet)) = tail.read_packet() {
2629            let Some(Some(time_base)) = usize::try_from(packet.stream_index)
2630                .ok()
2631                .and_then(|index| streams.get(index))
2632            else {
2633                continue;
2634            };
2635            if packet.pts == ffi::AV_NOPTS_VALUE {
2636                continue;
2637            }
2638            let packet_end = av_rescale_q(
2639                packet.pts.saturating_add(packet.duration.max(0)),
2640                *time_base,
2641                av_time_base,
2642            );
2643            end = Some(end.map_or(packet_end, |end: i64| end.max(packet_end)));
2644        }
2645        if end.is_some() || from == 0 {
2646            return end;
2647        }
2648    }
2649    None
2650}
2651
2652fn guessed_frame_rate(stream: &rsmpeg::avformat::AVStreamRef<'_>) -> Option<FrameRate> {
2653    stream
2654        .guess_framerate()
2655        .filter(|rate| rate.num > 0 && rate.den > 0)
2656        .and_then(|rate| {
2657            FrameRate::new(u32::try_from(rate.num).ok()?, u32::try_from(rate.den).ok()?).ok()
2658        })
2659}
2660
2661/// A stream tag's value; `None` when untagged or empty.
2662fn metadata_text(
2663    metadata: Option<rsmpeg::avutil::AVDictionaryRef<'_>>,
2664    key: &std::ffi::CStr,
2665) -> Option<String> {
2666    let metadata = metadata?;
2667    let entry = metadata.get(key, None, 0)?;
2668    let value = entry.value().to_string_lossy().trim().to_owned();
2669    (!value.is_empty()).then_some(value)
2670}
2671
2672/// Whether stream `index` has a decoder a source may select.
2673fn decoder_allowed(input: &DemuxInput, index: usize) -> bool {
2674    input.streams().get(index).is_some_and(|stream| {
2675        AVCodec::find_decoder(stream.codecpar().codec_id)
2676            .is_some_and(|codec| allowed_decoder(&codec).is_ok())
2677    })
2678}
2679
2680/// The [`ProbeResult`] of an opened input, with `FFmpeg`'s best video and audio streams selected.
2681pub(crate) fn probe_context(
2682    input: &DemuxInput,
2683    source: &SourceLocation,
2684) -> Result<ProbeResult, DecodeError> {
2685    let selected_video = input
2686        .best_stream(ffi::AVMEDIA_TYPE_VIDEO)
2687        .map_err(adapter_error)?;
2688    // An audio track whose decoder is not allowed is left out like one without a decoder.
2689    let selected_audio = input
2690        .best_stream(ffi::AVMEDIA_TYPE_AUDIO)
2691        .map_err(adapter_error)?
2692        .filter(|&index| decoder_allowed(input, index));
2693    let streams = input
2694        .streams()
2695        .iter()
2696        .enumerate()
2697        .filter_map(|(index, stream)| {
2698            let parameters = stream.codecpar();
2699            let kind = if parameters.codec_type().is_video() {
2700                StreamKind::Video
2701            } else if parameters.codec_type().is_audio() {
2702                StreamKind::Audio
2703            } else {
2704                return None;
2705            };
2706            let codec = AVCodec::find_decoder(parameters.codec_id).map_or_else(
2707                || "unknown".to_owned(),
2708                |codec| codec.name().to_string_lossy().into_owned(),
2709            );
2710            let dimensions = (kind == StreamKind::Video).then(|| {
2711                (
2712                    u32::try_from(parameters.width).unwrap_or(0),
2713                    u32::try_from(parameters.height).unwrap_or(0),
2714                )
2715            });
2716            let frame_rate = guessed_frame_rate(stream);
2717            Some(StreamInfo {
2718                index,
2719                kind,
2720                codec,
2721                duration: timestamp(stream.duration, stream.time_base),
2722                dimensions,
2723                frame_rate,
2724                sample_rate: (parameters.sample_rate > 0)
2725                    .then(|| u32::try_from(parameters.sample_rate).unwrap_or(0)),
2726                channels: (kind == StreamKind::Audio)
2727                    .then(|| u32::try_from(parameters.ch_layout.nb_channels).unwrap_or(0)),
2728                orientation: alpha2_ffmpeg_bridge::display_rotation(&parameters)
2729                    .and_then(orientation_from_display)
2730                    .or_else(|| {
2731                        (kind == StreamKind::Video
2732                            && Some(index) == selected_video
2733                            && is_still_image_format(input))
2734                        .then(|| still_image_orientation(source, index))
2735                        .flatten()
2736                    })
2737                    .unwrap_or_else(|| Orientation::rotated(stream_rotation(stream.metadata()))),
2738                sample_aspect_ratio: guess_sar(
2739                    stream.sample_aspect_ratio,
2740                    parameters.sample_aspect_ratio,
2741                ),
2742                color: if kind == StreamKind::Video {
2743                    color_metadata(&parameters)
2744                } else {
2745                    None
2746                },
2747                alpha: (kind == StreamKind::Video)
2748                    .then(|| source_alpha(stream.metadata(), &parameters))
2749                    .flatten(),
2750                frame_bytes: dimensions
2751                    .and_then(|size| decoded_frame_bytes(parameters.format, size)),
2752                language: metadata_text(stream.metadata(), c"language"),
2753                title: metadata_text(stream.metadata(), c"title"),
2754            })
2755        })
2756        .collect();
2757    let av_time_base = ra(
2758        1,
2759        i32::try_from(ffi::AV_TIME_BASE).expect("time base fits i32"),
2760    );
2761    let duration = parsed_end(input, source)
2762        .filter(|_| input.start_time != ffi::AV_NOPTS_VALUE)
2763        .map(|end| end.saturating_sub(input.start_time))
2764        .map_or(input.duration, |parsed| parsed.max(input.duration));
2765    Ok(ProbeResult {
2766        format: input.iformat().name().to_string_lossy().into_owned(),
2767        duration: (duration > 0)
2768            .then(|| MediaTime::from_ticks(av_rescale_q(duration, av_time_base, tick_base()))),
2769        start: (input.start_time != ffi::AV_NOPTS_VALUE).then(|| {
2770            MediaTime::from_ticks(av_rescale_q(
2771                input.start_time,
2772                ra(
2773                    1,
2774                    i32::try_from(ffi::AV_TIME_BASE).expect("time base fits i32"),
2775                ),
2776                tick_base(),
2777            ))
2778        }),
2779        streams,
2780        selected_video,
2781        selected_audio,
2782    })
2783}
2784
2785/// The desktop decoder behind the host's audio windows.
2786#[cfg(feature = "timeline")]
2787impl alpha2_host_core::audio_windows::WindowedAudioDecoder for NativeAudioDecoder {
2788    fn channels(&self) -> usize {
2789        Self::channels(self)
2790    }
2791
2792    fn speakers(&self) -> SpeakerLayout {
2793        Self::speakers(self)
2794    }
2795
2796    fn audio_duration(&self) -> Option<MediaTime> {
2797        Self::audio_duration(self)
2798    }
2799}