Skip to main content

alpha2_native/
decode.rs

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