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