Skip to main content

alpha2_host_core/
recovery.rs

1//! Bounded recovery shared by software and hardware-backed native decoders.
2use alpha2_media::{CancelToken, DecodeError};
3use std::time::Duration;
4
5/// Damaged input handling. Initialization and resource errors are always fatal.
6#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
7pub enum DecodePolicy {
8    /// Fail on the first reported corruption.
9    #[default]
10    Strict,
11    /// Skip damaged input, retaining diagnostics; fail when recovery is unbounded.
12    Tolerant,
13}
14
15impl DecodePolicy {
16    /// The policy's name as `ALPHA2_DECODE_POLICY` and `--decode-policy` spell it.
17    #[must_use]
18    pub const fn as_str(self) -> &'static str {
19        match self {
20            Self::Strict => "strict",
21            Self::Tolerant => "tolerant",
22        }
23    }
24
25    /// The policy `value` names ([`Self::as_str`]); any other value is none.
26    #[must_use]
27    pub fn parse(value: &str) -> Option<Self> {
28        [Self::Strict, Self::Tolerant]
29            .into_iter()
30            .find(|policy| policy.as_str() == value)
31    }
32
33    /// The policy `ALPHA2_DECODE_POLICY` selects; Strict when unset.
34    ///
35    /// # Errors
36    /// Any other value, including non-Unicode, is an error rather than a silent fallback.
37    pub fn from_env() -> Result<Self, String> {
38        match std::env::var("ALPHA2_DECODE_POLICY") {
39            Err(std::env::VarError::NotPresent) => Some(Self::Strict),
40            Ok(value) => Self::parse(&value),
41            Err(std::env::VarError::NotUnicode(_)) => None,
42        }
43        .ok_or_else(|| "ALPHA2_DECODE_POLICY must be strict or tolerant".to_owned())
44    }
45}
46
47/// Counts of what decoders reported: damage Tolerant decoding skipped and silence it inserted.
48/// Samples are at the reporting decoder's output rate.
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub struct DecodeDiagnosticCounts {
51    /// Corruption observations; one damaged packet can be observed at more than one stage.
52    pub corrupt_packets: u64,
53    /// Runs of dropped video between healthy frames, an unrecovered tail included.
54    pub video_gaps: u64,
55    /// Audio samples decoded as silence in place of damaged input.
56    pub concealed_audio_samples: u64,
57    /// Audio samples decoded as silence where a clean stream's timestamps jump.
58    pub timestamp_gap_samples: u64,
59    /// Audio samples dropped because their timestamps repeated samples already decoded.
60    pub dropped_audio_samples: u64,
61}
62
63impl DecodeDiagnosticCounts {
64    /// Counts one report.
65    pub fn record(&mut self, diagnostic: &DecodeDiagnostic) {
66        let samples = |start: i64, end: i64| u64::try_from(end.saturating_sub(start)).unwrap_or(0);
67        match diagnostic {
68            DecodeDiagnostic::Corruption(_) => {
69                self.corrupt_packets = self.corrupt_packets.saturating_add(1);
70            }
71            DecodeDiagnostic::VideoGap(_) => self.video_gaps = self.video_gaps.saturating_add(1),
72            DecodeDiagnostic::AudioGap(gap) => {
73                let count = samples(gap.start_sample, gap.end_sample);
74                let total = if gap.reason == "timestamp gap" {
75                    &mut self.timestamp_gap_samples
76                } else {
77                    &mut self.concealed_audio_samples
78                };
79                *total = total.saturating_add(count);
80            }
81            DecodeDiagnostic::AudioOverlap(overlap) => {
82                self.dropped_audio_samples = self
83                    .dropped_audio_samples
84                    .saturating_add(samples(overlap.start_sample, overlap.end_sample));
85            }
86        }
87    }
88
89    /// Whether nothing was reported.
90    #[must_use]
91    pub fn is_empty(&self) -> bool {
92        *self == Self::default()
93    }
94}
95
96/// One observed corruption. Timestamps use the selected stream's time base.
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct CorruptPacket {
99    /// Pipeline stage reporting damage (may be a frame or demux error).
100    pub stage: &'static str,
101    /// Best available timestamp, absent when `FFmpeg` cannot identify it.
102    pub pts: Option<i64>,
103    /// Numerator and denominator of the timestamp time base.
104    pub time_base: (i32, i32),
105    /// What the decoder said about the damage, when it said anything.
106    pub detail: Option<String>,
107}
108
109const MAX_AUDIO_RECORDS: usize = 1024;
110
111/// An interval decoded as silence at the decoder's output rate, where damaged input was
112/// dropped or timestamps jump.
113#[derive(Clone, Debug, PartialEq, Eq)]
114pub struct ConcealedAudioGap {
115    /// Inclusive source sample position.
116    pub start_sample: i64,
117    /// Exclusive source sample position.
118    pub end_sample: i64,
119    /// Output samples per second.
120    pub sample_rate: u32,
121    /// Why silence was inserted: `"corrupt input"` or `"timestamp gap"`.
122    pub reason: &'static str,
123}
124
125/// Samples dropped because their timestamps overlapped samples already decoded, at
126/// the decoder's output rate.
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct DroppedAudioOverlap {
129    /// Inclusive source sample position.
130    pub start_sample: i64,
131    /// Exclusive source sample position.
132    pub end_sample: i64,
133    /// Output samples per second.
134    pub sample_rate: u32,
135}
136
137/// Healthy video boundaries surrounding dropped data. Unknown endpoints remain absent.
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct VideoRecoveryGap {
140    /// Last healthy frame before damage; may be held by a containing-frame reader.
141    pub previous_pts: Option<i64>,
142    /// First healthy frame after damage, absent at EOF or seek reset.
143    pub recovered_pts: Option<i64>,
144    /// Numerator and denominator of both timestamps' time base.
145    pub time_base: (i32, i32),
146}
147
148/// Cumulative diagnostics. Records are bounded; overflow fails decoding.
149#[derive(Clone, Debug, Default, PartialEq, Eq)]
150pub struct DecodeDiagnostics {
151    /// Corruption observations, not necessarily distinct encoded packets.
152    pub corrupt_packets: Vec<CorruptPacket>,
153    /// Concealed audio intervals with original source positions.
154    pub audio_gaps: Vec<ConcealedAudioGap>,
155    /// Repeated audio intervals dropped, with original source positions.
156    pub audio_overlaps: Vec<DroppedAudioOverlap>,
157    /// Healthy boundaries around dropped video data; not a guessed CFR interval.
158    pub video_gaps: Vec<VideoRecoveryGap>,
159}
160
161/// A recovery observation emitted synchronously before decoding continues.
162#[derive(Clone, Debug, PartialEq, Eq)]
163pub enum DecodeDiagnostic {
164    /// Damage reported by the demuxer or decoder.
165    Corruption(CorruptPacket),
166    /// Explicitly inserted silence at source sample positions.
167    AudioGap(ConcealedAudioGap),
168    /// Repeated samples dropped at source sample positions.
169    AudioOverlap(DroppedAudioOverlap),
170    /// Video recovery boundaries without rewriting frame PTS.
171    VideoGap(VideoRecoveryGap),
172}
173
174/// How a backend classifies a failed decode call for [`Recovery::counts_as_damage`].
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub enum DecodeFailure {
177    /// The decoder reported corrupt input.
178    InvalidData,
179    /// A hardware session could not decode a picture. Hardware decoders report damage this way,
180    /// never as corrupt input.
181    HardwarePicture,
182    /// Anything else: resource, configuration or internal errors.
183    Other,
184}
185
186/// Largest distance of an audio timestamp from zero (2^31 s). Sample counts at the fastest
187/// accepted rate then stay below 2^51, so placement cannot overflow; anything further is damage.
188const AUDIO_TIMESTAMP_LIMIT_SECONDS: i128 = 1 << 31;
189
190/// Whether an audio timestamp of `pts` units of `num / den` seconds lies within 2^31 s of zero.
191/// Decoders record one outside as corruption ([`Recovery::corrupt`]) and drop its samples.
192#[must_use]
193pub fn audio_timestamp_in_range(pts: i64, num: i64, den: i64) -> bool {
194    let (num, den) = (i128::from(num), i128::from(den));
195    num > 0 && den > 0 && (i128::from(pts) * num).abs() <= AUDIO_TIMESTAMP_LIMIT_SECONDS * den
196}
197
198/// Corruption, timestamp and progress budgets for one decoder, with the diagnostics it collected.
199#[derive(Default)]
200pub struct Recovery {
201    /// How damaged input is handled.
202    pub policy: DecodePolicy,
203    /// Receives each diagnostic as it is recorded.
204    pub reporter: Option<Box<dyn Fn(DecodeDiagnostic) + Send + Sync>>,
205    /// Everything recorded so far.
206    pub diagnostics: DecodeDiagnostics,
207    consecutive: usize,
208    last_pts: Option<i64>,
209    stalled: usize,
210    video_damage: bool,
211    time_base: (i32, i32),
212    healthy_frames: usize,
213    /// The decoder is a hardware session (see [`Self::error`]).
214    hardware: bool,
215}
216impl Recovery {
217    /// Recovery for a software decoder whose timestamps count `time_base` = `(num, den)` seconds.
218    #[must_use]
219    pub fn new(time_base: (i32, i32)) -> Self {
220        Self {
221            time_base,
222            ..Self::default()
223        }
224    }
225    /// Recovery for a hardware decode session.
226    #[must_use]
227    pub fn hardware(time_base: (i32, i32)) -> Self {
228        Self {
229            hardware: true,
230            ..Self::new(time_base)
231        }
232    }
233    /// Marks the decoder as a hardware session or not, keeping what was recorded so far.
234    pub fn set_hardware(&mut self, hardware: bool) {
235        self.hardware = hardware;
236    }
237    /// Closes an open video recovery gap at `recovered_pts`.
238    pub fn finish_video_gap(&mut self, recovered_pts: Option<i64>) {
239        if !self.video_damage {
240            return;
241        }
242        self.video_damage = false;
243        let gap = VideoRecoveryGap {
244            previous_pts: self.last_pts,
245            recovered_pts,
246            time_base: self.time_base,
247        };
248        self.diagnostics.video_gaps.push(gap.clone());
249        if let Some(report) = &self.reporter {
250            report(DecodeDiagnostic::VideoGap(gap));
251        }
252    }
253
254    /// Whether a failed decode call counts as damaged input, which [`Self::corrupt`] then records,
255    /// rather than a fatal error. Hardware sessions' picture failures count only under
256    /// [`DecodePolicy::Tolerant`]; Strict fails them so a host can retry in software.
257    #[must_use]
258    pub fn counts_as_damage(&self, failure: DecodeFailure) -> bool {
259        match failure {
260            DecodeFailure::InvalidData => true,
261            DecodeFailure::HardwarePicture => {
262                self.hardware && self.policy == DecodePolicy::Tolerant
263            }
264            DecodeFailure::Other => false,
265        }
266    }
267    /// Records damaged input at `stage` and `pts`, failing under Strict or past a budget.
268    ///
269    /// # Errors
270    /// Strict policy, the diagnostic budget, or too many consecutive corruptions.
271    pub fn corrupt(&mut self, stage: &'static str, pts: Option<i64>) -> Result<(), DecodeError> {
272        self.corrupt_with_detail(stage, pts, None)
273    }
274
275    /// [`Self::corrupt`], keeping what the decoder said about the damage.
276    ///
277    /// # Errors
278    /// As [`Self::corrupt`].
279    ///
280    /// # Panics
281    /// Never: the record it reports was just pushed.
282    pub fn corrupt_with_detail(
283        &mut self,
284        stage: &'static str,
285        pts: Option<i64>,
286        detail: Option<String>,
287    ) -> Result<(), DecodeError> {
288        if self.diagnostics.corrupt_packets.len() >= 1024 {
289            return Err(DecodeError::Adapter(
290                "corruption diagnostic budget exceeded".into(),
291            ));
292        }
293        self.diagnostics.corrupt_packets.push(CorruptPacket {
294            stage,
295            pts,
296            time_base: self.time_base,
297            detail,
298        });
299        if let Some(report) = &self.reporter {
300            report(DecodeDiagnostic::Corruption(
301                self.diagnostics.corrupt_packets.last().unwrap().clone(),
302            ));
303        }
304        self.video_damage |= stage.starts_with("video");
305        self.consecutive += 1;
306        if self.policy == DecodePolicy::Strict {
307            return Err(DecodeError::Adapter(format!(
308                "corrupt input at {stage} (strict decode policy)"
309            )));
310        }
311        if self.consecutive > 32 {
312            return Err(DecodeError::Adapter(
313                "consecutive corruption budget exceeded".into(),
314            ));
315        }
316        Ok(())
317    }
318    /// The video stream ended.
319    ///
320    /// # Errors
321    /// The stream ended in damage with no healthy frame since the open or seek.
322    pub fn video_eof(&mut self) -> Result<(), DecodeError> {
323        self.finish_video_gap(None);
324        if self.consecutive != 0 {
325            self.damaged_tail("video")?;
326        }
327        Ok(())
328    }
329    /// The stream ended in damage. It ends at its last healthy frame, unless none was decoded since
330    /// the open or seek, since damaged input cannot succeed with empty output.
331    ///
332    /// # Errors
333    /// No healthy frame since the open or seek.
334    pub fn damaged_tail(&self, kind: &str) -> Result<(), DecodeError> {
335        if self.healthy_frames == 0 {
336            return Err(DecodeError::Adapter(format!(
337                "damaged {kind} has no recoverable frames"
338            )));
339        }
340        Ok(())
341    }
342    /// A healthy frame decoded at `pts`, which is `None` when the frame has no timestamp.
343    ///
344    /// # Errors
345    /// Timestamps stopped advancing for too many frames.
346    pub fn progress(&mut self, pts: Option<i64>) -> Result<(), DecodeError> {
347        self.healthy_frames = self.healthy_frames.saturating_add(1);
348        self.finish_video_gap(pts);
349        self.consecutive = 0;
350        if let Some(pts) = pts
351            && self.last_pts.is_none_or(|previous| pts > previous)
352        {
353            self.last_pts = Some(pts);
354            self.stalled = 0;
355        } else {
356            self.stalled += 1;
357        }
358        if self.stalled > 256 {
359            return Err(DecodeError::Adapter(
360                "decoder PTS progress budget exceeded".into(),
361            ));
362        }
363        Ok(())
364    }
365    /// Forgets progress after a seek or reopen.
366    pub fn reset_progress(&mut self) {
367        self.finish_video_gap(None);
368        self.last_pts = None;
369        self.healthy_frames = 0;
370        self.stalled = 0;
371        self.consecutive = 0;
372    }
373    /// Audio concealed over damage from `start_sample` to `end_sample`.
374    ///
375    /// # Errors
376    /// The audio gap record budget is spent.
377    pub fn audio_gap(
378        &mut self,
379        start_sample: i64,
380        end_sample: i64,
381        sample_rate: u32,
382        reason: &'static str,
383    ) -> Result<(), DecodeError> {
384        if self.diagnostics.audio_gaps.len() >= MAX_AUDIO_RECORDS {
385            return Err(DecodeError::Adapter(
386                "audio gap diagnostic budget exceeded".into(),
387            ));
388        }
389        self.timestamp_audio_gap(start_sample, end_sample, sample_rate, reason);
390        Ok(())
391    }
392    /// A gap the stream's own timestamps leave: not damage, so never fatal. Past the record budget
393    /// it is reported but not recorded.
394    pub fn timestamp_gap(&mut self, start_sample: i64, end_sample: i64, sample_rate: u32) {
395        self.timestamp_audio_gap(start_sample, end_sample, sample_rate, "timestamp gap");
396    }
397    fn timestamp_audio_gap(
398        &mut self,
399        start_sample: i64,
400        end_sample: i64,
401        sample_rate: u32,
402        reason: &'static str,
403    ) {
404        let gap = ConcealedAudioGap {
405            start_sample,
406            end_sample,
407            sample_rate,
408            reason,
409        };
410        if let Some(report) = &self.reporter {
411            report(DecodeDiagnostic::AudioGap(gap.clone()));
412        }
413        if self.diagnostics.audio_gaps.len() < MAX_AUDIO_RECORDS {
414            self.diagnostics.audio_gaps.push(gap);
415        }
416    }
417    /// Samples a frame repeated over ones already placed, which were dropped.
418    pub fn timestamp_overlap(&mut self, start_sample: i64, end_sample: i64, sample_rate: u32) {
419        let overlap = DroppedAudioOverlap {
420            start_sample,
421            end_sample,
422            sample_rate,
423        };
424        if let Some(report) = &self.reporter {
425            report(DecodeDiagnostic::AudioOverlap(overlap.clone()));
426        }
427        if self.diagnostics.audio_overlaps.len() < MAX_AUDIO_RECORDS {
428            self.diagnostics.audio_overlaps.push(overlap);
429        }
430    }
431}
432
433/// The longest a decoder operation (seek, next frame, open) may go without a step forward (a packet
434/// of its stream read, a packet accepted, or a frame) before failing with "decode progress budget
435/// exceeded".
436///
437/// A call that blocks and then returns is such a step, so a slow read does not fail a decode that
438/// advances. A call that never returns is the stall watcher's, which allows this plus its own GPU
439/// wait limit from the last [`watch_decode_progress`] report.
440pub const DECODE_WORK_LIMIT: Duration = Duration::from_secs(10);
441
442/// The most loop steps a decoder operation takes without producing a frame.
443const DECODE_WORK_STEPS: usize = 65_536;
444
445thread_local! {
446    static DECODE_PROGRESS_WATCH: std::cell::RefCell<Option<Box<dyn Fn()>>> =
447        const { std::cell::RefCell::new(None) };
448    static INPUT_WAIT: std::cell::Cell<Duration> = const { std::cell::Cell::new(Duration::ZERO) };
449}
450
451/// Tells this thread's work budgets that a read waited `waited` for its input (a remote source's
452/// bytes). The wait has its own bound, so a budget does not count it.
453pub fn report_input_wait(waited: Duration) {
454    INPUT_WAIT.with(|total| total.set(total.get().saturating_add(waited)));
455}
456
457fn input_wait() -> Duration {
458    INPUT_WAIT.with(std::cell::Cell::get)
459}
460
461#[cfg(any(test, feature = "test-hooks"))]
462thread_local! {
463    /// [`DECODE_WORK_LIMIT`] as a test on this thread sets it, else
464    /// `ALPHA2_TEST_DECODE_WORK_LIMIT_MS` (longer under valgrind). Test builds only.
465    pub static WORK_LIMIT: std::cell::Cell<Duration> =
466        std::cell::Cell::new(test_work_limit(std::env::var("ALPHA2_TEST_DECODE_WORK_LIMIT_MS").ok().as_deref()));
467    /// [`DECODE_WORK_STEPS`] as a test on this thread sets it.
468    pub static WORK_STEPS: std::cell::Cell<usize> =
469        const { std::cell::Cell::new(DECODE_WORK_STEPS) };
470    /// Delay a seek on this thread takes after each decoded frame, slept or added to
471    /// [`VIRTUAL_CLOCK`] when set.
472    pub static FRAME_DELAY: std::cell::Cell<Duration> =
473        const { std::cell::Cell::new(Duration::ZERO) };
474    /// When set, the clock work budgets on this thread measure, advanced only by [`FRAME_DELAY`],
475    /// so tests do not depend on real decode speed.
476    pub static VIRTUAL_CLOCK: std::cell::Cell<Option<Duration>> =
477        const { std::cell::Cell::new(None) };
478}
479
480/// The test builds' default [`WORK_LIMIT`]: `setting` milliseconds when positive.
481#[cfg(any(test, feature = "test-hooks"))]
482fn test_work_limit(setting: Option<&str>) -> Duration {
483    setting
484        .and_then(|value| value.parse::<u64>().ok())
485        .filter(|millis| *millis > 0)
486        .map_or(DECODE_WORK_LIMIT, Duration::from_millis)
487}
488
489/// Takes [`FRAME_DELAY`] after a decoded frame. Test builds only.
490#[cfg(any(test, feature = "test-hooks"))]
491pub fn take_frame_delay() {
492    let delay = FRAME_DELAY.with(std::cell::Cell::get);
493    match VIRTUAL_CLOCK.with(std::cell::Cell::get) {
494        Some(now) => VIRTUAL_CLOCK.with(|clock| clock.set(Some(now.saturating_add(delay)))),
495        None => std::thread::sleep(delay),
496    }
497}
498
499/// Calls `progressed` on this thread each time a decoder operation produces a frame or a packet
500/// copy plan reads a source packet, until the guard drops.
501///
502/// Lets an outside stall watcher see a long seek as alive rather than blocked.
503#[must_use = "the watch ends when the guard drops"]
504pub fn watch_decode_progress(progressed: impl Fn() + 'static) -> DecodeProgressWatch {
505    let previous = DECODE_PROGRESS_WATCH.with(|watch| watch.replace(Some(Box::new(progressed))));
506    DecodeProgressWatch {
507        previous,
508        thread: std::marker::PhantomData,
509    }
510}
511
512/// Tells this thread's [`watch_decode_progress`] watch, if any, that the current operation
513/// produced a frame or packet.
514pub fn report_decode_progress() {
515    DECODE_PROGRESS_WATCH.with(|watch| {
516        if let Some(progressed) = watch.borrow().as_ref() {
517            progressed();
518        }
519    });
520}
521
522/// Ends a [`watch_decode_progress`] watch, restoring the one before it.
523pub struct DecodeProgressWatch {
524    previous: Option<Box<dyn Fn()>>,
525    thread: std::marker::PhantomData<*const ()>,
526}
527
528impl Drop for DecodeProgressWatch {
529    fn drop(&mut self) {
530        let previous = self.previous.take();
531        DECODE_PROGRESS_WATCH.with(|watch| {
532            watch.replace(previous);
533        });
534    }
535}
536
537/// Time since a decoder operation started or last stepped forward, and loop steps since it started
538/// or last produced a frame, checked against [`DECODE_WORK_LIMIT`] and a bound of 65,536 steps.
539pub struct WorkBudget {
540    /// On the awake clock, so system sleep does not count.
541    started: alpha2_os::AwakeInstant,
542    input_wait_at_start: Duration,
543    /// Where [`VIRTUAL_CLOCK`] stood at `started`, when it is set.
544    #[cfg(any(test, feature = "test-hooks"))]
545    started_virtual: Option<Duration>,
546    steps: usize,
547}
548impl Default for WorkBudget {
549    fn default() -> Self {
550        Self::new()
551    }
552}
553
554impl WorkBudget {
555    /// A budget starting now.
556    #[must_use]
557    pub fn new() -> Self {
558        Self {
559            started: alpha2_os::AwakeInstant::now(),
560            input_wait_at_start: input_wait(),
561            #[cfg(any(test, feature = "test-hooks"))]
562            started_virtual: VIRTUAL_CLOCK.with(std::cell::Cell::get),
563            steps: 0,
564        }
565    }
566
567    fn elapsed(&self) -> Duration {
568        #[cfg(any(test, feature = "test-hooks"))]
569        if let (Some(now), Some(started)) = (
570            VIRTUAL_CLOCK.with(std::cell::Cell::get),
571            self.started_virtual,
572        ) {
573            return now.saturating_sub(started);
574        }
575        self.started
576            .elapsed()
577            .saturating_sub(input_wait().saturating_sub(self.input_wait_at_start))
578    }
579    /// One loop step of the operation.
580    ///
581    /// # Errors
582    /// Cancellation, or the operation's time or step limit is spent.
583    pub fn step(&mut self, cancel: &CancelToken) -> Result<(), DecodeError> {
584        if cancel.is_cancelled() {
585            return Err(DecodeError::Cancelled);
586        }
587        self.steps += 1;
588        #[cfg(any(test, feature = "test-hooks"))]
589        let (limit, steps) = (
590            WORK_LIMIT.with(std::cell::Cell::get),
591            WORK_STEPS.with(std::cell::Cell::get),
592        );
593        #[cfg(not(any(test, feature = "test-hooks")))]
594        let (limit, steps) = (DECODE_WORK_LIMIT, DECODE_WORK_STEPS);
595        if self.steps > steps || self.elapsed() > limit {
596            return Err(DecodeError::Adapter(
597                "decode progress budget exceeded".into(),
598            ));
599        }
600        Ok(())
601    }
602    /// The operation read a packet of its stream or the decoder accepted one: the time limit starts
603    /// again from now. The step count does not, so a stream that never gives a frame still ends.
604    pub fn advanced(&mut self) {
605        self.started = alpha2_os::AwakeInstant::now();
606        self.input_wait_at_start = input_wait();
607        #[cfg(any(test, feature = "test-hooks"))]
608        {
609            self.started_virtual = VIRTUAL_CLOCK.with(std::cell::Cell::get);
610        }
611    }
612
613    /// The operation produced a frame: its limits start again from now.
614    pub fn progressed(&mut self) {
615        self.started = alpha2_os::AwakeInstant::now();
616        self.input_wait_at_start = input_wait();
617        #[cfg(any(test, feature = "test-hooks"))]
618        {
619            self.started_virtual = VIRTUAL_CLOCK.with(std::cell::Cell::get);
620        }
621        self.steps = 0;
622        report_decode_progress();
623    }
624}
625
626/// The closure refers to the same packet until send accepts it: `true` requests receive/drain,
627/// `false` send; its result means progress.
628///
629/// # Errors
630/// The step's error, cancellation, a spent budget, or no progress.
631pub fn submit_packet(
632    mut step: impl FnMut(bool) -> Result<bool, DecodeError>,
633    budget: &mut WorkBudget,
634    cancel: &CancelToken,
635) -> Result<(), DecodeError> {
636    for _ in 0..64 {
637        budget.step(cancel)?;
638        if step(false)? {
639            budget.advanced();
640            return Ok(());
641        }
642        budget.step(cancel)?;
643        if !step(true)? {
644            return Err(DecodeError::Adapter(
645                "decoder send/receive made no progress".into(),
646            ));
647        }
648    }
649    Err(DecodeError::Adapter("packet retry budget exceeded".into()))
650}
651
652#[cfg(test)]
653mod tests {
654    use super::*;
655
656    #[test]
657    fn a_reported_input_wait_is_not_counted_against_a_work_budget() {
658        const LIMIT: Duration = Duration::from_millis(50);
659        WORK_LIMIT.with(|limit| limit.set(LIMIT));
660        let cancel = CancelToken::default();
661        let mut budget = WorkBudget::new();
662        std::thread::sleep(LIMIT * 2);
663        report_input_wait(LIMIT * 2);
664        assert!(budget.step(&cancel).is_ok(), "a wait for input is not work");
665        std::thread::sleep(LIMIT * 2);
666        assert!(
667            budget.step(&cancel).is_err(),
668            "time past the wait still counts"
669        );
670        WORK_LIMIT.with(|limit| limit.set(DECODE_WORK_LIMIT));
671    }
672
673    #[test]
674    fn a_policy_is_named_as_the_host_names_it() {
675        for policy in [DecodePolicy::Strict, DecodePolicy::Tolerant] {
676            assert_eq!(DecodePolicy::parse(policy.as_str()), Some(policy));
677        }
678        assert_eq!(DecodePolicy::Tolerant.as_str(), "tolerant");
679        assert_eq!(DecodePolicy::parse("Tolerant"), None);
680        assert_eq!(DecodePolicy::parse(""), None);
681    }
682
683    #[test]
684    fn an_audio_timestamp_is_in_range_up_to_two_to_the_31_seconds() {
685        let limit = (1_i64 << 31) * 48_000;
686        assert!(audio_timestamp_in_range(limit, 1, 48_000));
687        assert!(audio_timestamp_in_range(-limit, 1, 48_000));
688        assert!(!audio_timestamp_in_range(limit + 1, 1, 48_000));
689        assert!(!audio_timestamp_in_range(i64::MIN, 1, 48_000));
690        assert!(!audio_timestamp_in_range(i64::MAX, 1, 1));
691        assert!(audio_timestamp_in_range(1 << 31, 1, 1));
692        assert!(!audio_timestamp_in_range(0, 0, 1));
693        assert!(!audio_timestamp_in_range(0, 1, 0));
694    }
695
696    #[test]
697    fn counts_tell_concealed_damage_from_a_timestamp_gap() {
698        let mut counts = DecodeDiagnosticCounts::default();
699        assert!(counts.is_empty());
700        let gap = |start_sample, end_sample, reason| {
701            DecodeDiagnostic::AudioGap(ConcealedAudioGap {
702                start_sample,
703                end_sample,
704                sample_rate: 48_000,
705                reason,
706            })
707        };
708        for diagnostic in [
709            DecodeDiagnostic::Corruption(CorruptPacket {
710                stage: "audio send",
711                pts: None,
712                time_base: (1, 48_000),
713                detail: None,
714            }),
715            gap(1024, 2048, "corrupt input"),
716            gap(4096, 4196, "timestamp gap"),
717            DecodeDiagnostic::AudioOverlap(DroppedAudioOverlap {
718                start_sample: 10,
719                end_sample: 15,
720                sample_rate: 48_000,
721            }),
722            DecodeDiagnostic::VideoGap(VideoRecoveryGap {
723                previous_pts: Some(1),
724                recovered_pts: None,
725                time_base: (1, 10),
726            }),
727        ] {
728            counts.record(&diagnostic);
729        }
730        assert_eq!(
731            counts,
732            DecodeDiagnosticCounts {
733                corrupt_packets: 1,
734                video_gaps: 1,
735                concealed_audio_samples: 1024,
736                timestamp_gap_samples: 100,
737                dropped_audio_samples: 5,
738            }
739        );
740        assert!(!counts.is_empty());
741    }
742    /// Under Tolerant a hardware session's undecodable picture counts as damage, since hardware
743    /// sessions never report corrupt input.
744    #[test]
745    fn a_hardware_sessions_picture_failure_is_damage_only_when_tolerant() {
746        let mut tolerant = Recovery::hardware((1, 30));
747        tolerant.policy = DecodePolicy::Tolerant;
748        assert!(tolerant.counts_as_damage(DecodeFailure::HardwarePicture));
749        assert!(!Recovery::hardware((1, 30)).counts_as_damage(DecodeFailure::HardwarePicture));
750        let mut software = Recovery::new((1, 30));
751        software.policy = DecodePolicy::Tolerant;
752        assert!(!software.counts_as_damage(DecodeFailure::HardwarePicture));
753        assert!(software.counts_as_damage(DecodeFailure::InvalidData));
754        assert!(!software.counts_as_damage(DecodeFailure::Other));
755    }
756
757    #[test]
758    fn strict_tolerant_and_fatal_errors() {
759        let mut state = Recovery::default();
760        assert!(state.corrupt("send", Some(12)).is_err());
761        state.policy = DecodePolicy::Tolerant;
762        state.reset_progress();
763        assert!(state.counts_as_damage(DecodeFailure::InvalidData));
764        assert!(state.corrupt("send", Some(13)).is_ok());
765        assert_eq!(state.diagnostics.corrupt_packets.len(), 2);
766        for _ in 0..31 {
767            state.corrupt("receive", None).unwrap();
768        }
769        assert!(state.corrupt("receive", None).is_err());
770    }
771    #[test]
772    fn progress_and_cancellation_are_bounded() {
773        let mut state = Recovery::default();
774        state.progress(Some(10)).unwrap();
775        for _ in 0..256 {
776            state.progress(Some(10)).unwrap();
777        }
778        assert!(state.progress(Some(10)).is_err());
779        state.reset_progress();
780        state.progress(Some(0)).unwrap();
781        let cancel = CancelToken::default();
782        let mut budget = WorkBudget::new();
783        for _ in 0..65_536 {
784            budget.step(&cancel).unwrap();
785        }
786        assert!(budget.step(&cancel).is_err());
787        // The production limit, whatever `ALPHA2_TEST_DECODE_WORK_LIMIT_MS` gives this run.
788        WORK_LIMIT.with(|limit| limit.set(DECODE_WORK_LIMIT));
789        let mut budget = WorkBudget::new();
790        budget.started = budget
791            .started
792            .checked_sub(Duration::from_secs(11))
793            .expect("the clock reaches back 11 s");
794        assert!(budget.step(&cancel).is_err());
795        cancel.cancel();
796        assert_eq!(WorkBudget::new().step(&cancel), Err(DecodeError::Cancelled));
797    }
798    #[test]
799    fn eagain_drains_and_retries_the_same_packet_until_accepted() {
800        let mut actions = Vec::new();
801        let mut sends = 0;
802        submit_packet(
803            |drain| {
804                actions.push(drain);
805                if drain {
806                    return Ok(true);
807                }
808                sends += 1;
809                Ok(sends == 3)
810            },
811            &mut WorkBudget::new(),
812            &CancelToken::default(),
813        )
814        .unwrap();
815        assert_eq!(actions, [false, true, false, true, false]);
816        assert!(
817            submit_packet(
818                |_| Ok(false),
819                &mut WorkBudget::new(),
820                &CancelToken::default()
821            )
822            .is_err()
823        );
824        assert!(submit_packet(Ok, &mut WorkBudget::new(), &CancelToken::default()).is_err());
825        let cancel = CancelToken::default();
826        let result = submit_packet(
827            |drain| {
828                if drain {
829                    cancel.cancel();
830                }
831                Ok(drain)
832            },
833            &mut WorkBudget::new(),
834            &cancel,
835        );
836        assert_eq!(result, Err(DecodeError::Cancelled));
837    }
838
839    #[test]
840    fn the_time_limit_runs_from_the_last_step_forward_and_the_step_limit_from_the_last_frame() {
841        let cancel = CancelToken::default();
842        let limit = Duration::from_secs(10);
843        WORK_LIMIT.with(|cell| cell.set(limit));
844        VIRTUAL_CLOCK.with(|clock| clock.set(Some(Duration::ZERO)));
845        let advance = |by: Duration| {
846            VIRTUAL_CLOCK.with(|clock| clock.set(clock.get().map(|now| now + by)));
847        };
848        // A read that blocks past the limit and returns its packet is a step forward.
849        let mut budget = WorkBudget::new();
850        budget.step(&cancel).unwrap();
851        advance(Duration::from_secs(11));
852        budget.advanced();
853        budget.step(&cancel).expect("a slow read that returned");
854        // Nothing read or accepted for the limit still fails.
855        advance(Duration::from_secs(11));
856        assert!(budget.step(&cancel).is_err());
857        // Packets that never give a frame still end at the step limit.
858        WORK_STEPS.with(|cell| cell.set(100));
859        let mut budget = WorkBudget::new();
860        for _ in 0..100 {
861            budget.step(&cancel).unwrap();
862            budget.advanced();
863        }
864        assert!(budget.step(&cancel).is_err());
865        WORK_STEPS.with(|cell| cell.set(DECODE_WORK_STEPS));
866        VIRTUAL_CLOCK.with(|clock| clock.set(None));
867    }
868
869    #[test]
870    fn an_accepted_packet_restarts_the_time_limit() {
871        let cancel = CancelToken::default();
872        WORK_LIMIT.with(|cell| cell.set(Duration::from_secs(10)));
873        VIRTUAL_CLOCK.with(|clock| clock.set(Some(Duration::ZERO)));
874        let mut budget = WorkBudget::new();
875        submit_packet(
876            |_| {
877                // The send blocks for 11 s, then accepts.
878                VIRTUAL_CLOCK.with(|clock| {
879                    clock.set(clock.get().map(|now| now + Duration::from_secs(11)));
880                });
881                Ok(true)
882            },
883            &mut budget,
884            &cancel,
885        )
886        .unwrap();
887        budget
888            .step(&cancel)
889            .expect("the accepted packet was a step forward");
890        VIRTUAL_CLOCK.with(|clock| clock.set(None));
891    }
892}