Skip to main content

buffering_runtime/
controller.rs

1//! The buffer controller: estimator + policy + state machine + events.
2//!
3//! **Two clock domains, kept apart.** The jitter estimator is fed the 27 MHz
4//! *PCR* through [`BufferController::on_chunk`] (when a chunk carries one).
5//! The *lead* is measured in the *playback (PTS) domain*: the caller reports
6//! the end of the last demuxed sample with [`BufferController::on_media`] and
7//! the renderer clock with [`BufferController::on_tick`], both PTS-derived
8//! (`PTS90k x 300`, see [`crate::pts90k_to_clock27`]). PCR typically runs ahead
9//! of PTS by the mux/decoder delay, so a lead taken from PCR would overstate
10//! what can play; every position in an [`Event`] is in the PTS domain.
11//!
12//! **PCR-less fallback.** If no chunk with a PCR has ever been fed, the
13//! estimator is fed from `on_media` (its `media_end` is the media time), one
14//! track's own series: the first track to deliver, until it is removed or
15//! silent. Never the minimum over tracks, which jumps whenever a track joins
16//! behind or the limiting track changes. The first PCR seen switches the estimator to PCR for good (its baseline is
17//! reset once because the two clocks differ); from then on `on_media` never
18//! feeds the estimator.
19//!
20//! **Several tracks.** A TS mux sends video well ahead of play time and audio
21//! close to real time, so the media that can be *played* ends at the least
22//! advanced rendered track. The lead is therefore measured against the
23//! **minimum media end over the rendered tracks**: either the caller reduces
24//! them and calls [`BufferController::on_media`] with that minimum, or it
25//! reports each track with [`BufferController::on_track_media`] and the
26//! controller does it (see [`crate::tracks`] for the active/silent rules).
27
28use core::time::Duration;
29
30use crate::config::{ControllerConfig, REARM_DEN, REARM_NUM, TICKS_PER_US};
31use crate::error::Error;
32use crate::events::{Event, EventQueue, Hint, Reason, State, Stats};
33use crate::jitter::{DeliveryJitter, SampleOutcome};
34use crate::policy::Policy;
35use crate::stall_memory::StallMemorySnapshot;
36use crate::time::{Clock27, duration_between, instant_micros, micros_as_duration, window_micros};
37use crate::tracks::{DEFAULT_TRACK, Effective, StepRules, TrackSet};
38
39fn dur(us: u64) -> Duration {
40    Duration::from_micros(us)
41}
42use broadcast_common::clock33::pcr_signed_distance;
43
44const TICKS_PER_US_I: i64 = TICKS_PER_US as i64;
45
46/// Signed lead in microseconds of `media_end` over `from` (PTS domain).
47fn lead_between(from: Clock27, media_end: Clock27) -> i64 {
48    pcr_signed_distance(from.ticks(), media_end.ticks()) / TICKS_PER_US_I
49}
50
51fn to_u64(v: i64) -> u64 {
52    u64::try_from(v.max(0)).unwrap_or(0)
53}
54
55/// The decision engine. Sans-IO: the caller passes every clock reading.
56#[derive(Clone, Debug)]
57pub struct BufferController {
58    cfg: ControllerConfig,
59    jitter: DeliveryJitter,
60    policy: Policy,
61    events: EventQueue,
62    state: State,
63    reason: Reason,
64    started: bool,
65    neutral_pause: bool,
66    last_tick: Duration,
67    latest: Duration,
68    last_chunk_at: Option<Duration>,
69    gap_end_at: Option<Duration>,
70    chunks: u64,
71    tracks: TrackSet,
72    queue_start: Option<Clock27>,
73    last_playback: Option<Clock27>,
74    fill_from: Option<Clock27>,
75    pause_at: Duration,
76    source_down: bool,
77    degraded: bool,
78    pcr_seen: bool,
79    fed_media: bool,
80    media_ref: Option<u32>,
81    below_since: Option<Duration>,
82    over_armed: bool,
83    reported_target: u64,
84    lead: i64,
85    stalls: u32,
86    reprimes: u32,
87    last_stall_depth: Duration,
88    longest_freeze: Duration,
89    regressions: u32,
90    discontinuities: u32,
91    hints: u32,
92}
93
94impl BufferController {
95    /// Build a controller, optionally seeded with a persisted stall memory
96    /// (age it with [`StallMemorySnapshot::aged`] first).
97    ///
98    /// # Errors
99    /// Any [`ControllerConfig::validate`] failure.
100    pub fn new(cfg: ControllerConfig, seed: Option<StallMemorySnapshot>) -> Result<Self, Error> {
101        cfg.validate()?;
102        let mut c = Self {
103            jitter: DeliveryJitter::new(cfg.jitter)?,
104            policy: Policy::new(cfg.policy),
105            events: EventQueue::new(),
106            state: State::Buffering,
107            reason: Reason::Startup,
108            started: false,
109            neutral_pause: false,
110            last_tick: Duration::ZERO,
111            latest: Duration::ZERO,
112            last_chunk_at: None,
113            gap_end_at: None,
114            chunks: 0,
115            tracks: TrackSet::new(cfg.granularity_hold, cfg.granularity_decay),
116            queue_start: None,
117            last_playback: None,
118            fill_from: None,
119            pause_at: Duration::ZERO,
120            source_down: false,
121            degraded: false,
122            pcr_seen: false,
123            fed_media: false,
124            media_ref: None,
125            below_since: None,
126            over_armed: true,
127            reported_target: window_micros(cfg.policy.min),
128            lead: 0,
129            stalls: 0,
130            reprimes: 0,
131            last_stall_depth: Duration::ZERO,
132            longest_freeze: Duration::ZERO,
133            regressions: 0,
134            discontinuities: 0,
135            hints: 0,
136            cfg,
137        };
138        if let Some(s) = seed {
139            c.restore_memory(s);
140        }
141        Ok(c)
142    }
143
144    /// The validated configuration in force.
145    #[must_use]
146    pub fn config(&self) -> &ControllerConfig {
147        &self.cfg
148    }
149
150    /// One chunk arrived. `pcr_27mhz` is the chunk's last PCR (raw, wrapped)
151    /// if it has one. Call this BEFORE [`on_media`](Self::on_media) for the
152    /// same chunk.
153    ///
154    /// **Delivery instant.** A chunk boundary is the delivery instant of the
155    /// per-track granularity floor: every
156    /// [`on_track_media`](Self::on_track_media) call for a track between two
157    /// `on_chunk` calls is ONE delivery (step = end after the last call - end
158    /// before the first). Reporting once per delivered chunk or once per
159    /// demuxed sample gives the same floor. A caller that never calls
160    /// `on_chunk` gets calls less than [`COALESCE`](crate::COALESCE)
161    /// apart coalesced instead. The step is folded in (and the target
162    /// re-evaluated) at the next `on_chunk`.
163    pub fn on_chunk(&mut self, arrival: Duration, bytes: u32, pcr_27mhz: Option<Clock27>) {
164        self.latest = self.latest.max(arrival);
165        // the previous chunk's deliveries are complete: fold their steps before
166        // this chunk's arrival can mark a gap
167        self.tracks.close_windows(self.step_rules());
168        if self.cfg.track_granularity && self.granularity_need(arrival) > self.policy.target() {
169            self.after_sample(arrival);
170        }
171        self.chunks = self.chunks.wrapping_add(1).max(1);
172        if self
173            .last_chunk_at
174            .is_some_and(|t| duration_between(t, arrival) >= self.cfg.nodata_after)
175        {
176            self.gap_end_at = Some(arrival);
177        }
178        self.last_chunk_at = Some(self.last_chunk_at.map_or(arrival, |t| t.max(arrival)));
179        if let Some(pcr) = pcr_27mhz {
180            if !self.pcr_seen {
181                self.pcr_seen = true;
182                if self.fed_media {
183                    self.jitter.reset_baseline();
184                    self.fed_media = false;
185                }
186            }
187            self.feed(arrival, pcr, bytes);
188        }
189    }
190
191    /// The demuxer's media position advanced: `media_end_27mhz` is the end of
192    /// the last demuxed sample in the **playback (PTS) domain** (27 MHz ticks;
193    /// `PTS90k x 300`). The first value after (re)start is taken as the oldest
194    /// buffered position; report the first sample's *start* PTS as a
195    /// zero-length first report so that sample is not skipped.
196    ///
197    /// **Caller contract (join point).** The first end reported is the start
198    /// origin (with several tracks, the earliest first report). Report the
199    /// first end only from the join point (the first video random-access
200    /// point) and never report an end for media before it: audio reported
201    /// before the join point (normal in a TS mux, audio is ~1 s behind video)
202    /// anchors the origin that much early and the start loses that much audio
203    /// cushion. The controller cannot see RAPs, so the caller must withhold
204    /// ends before the join point.
205    ///
206    /// `media_end_27mhz` means **the end of the media playable on ALL rendered
207    /// tracks**: when audio and video are both rendered the caller must pass
208    /// the *minimum* of their ends (video is typically ~1 s ahead of audio in a
209    /// TS mux; judging the lead on video alone makes audio arrive after its
210    /// play time). Or use [`on_track_media`](Self::on_track_media) and let the
211    /// controller take the minimum.
212    ///
213    /// Mixing: this is shorthand for
214    /// `on_track_media(now, DEFAULT_TRACK, media_end)` (track 0), so
215    /// it participates in the same per-track minimum as any explicit track.
216    pub fn on_media(&mut self, now: Duration, media_end: Clock27) {
217        self.on_track_media(now, DEFAULT_TRACK, media_end);
218    }
219
220    /// Announce that `track` will be rendered, so a start or resume waits for
221    /// it before its first delivery. A registered track that never delivers is
222    /// excluded once other tracks have delivered for
223    /// [`ControllerConfig::track_silence_timeout`] without it (never after a
224    /// global delivery gap). Optional:
225    /// an unregistered track becomes active on its first delivery (join-point
226    /// contract: see [`on_media`](Self::on_media), report only from the join
227    /// point). At most
228    /// [`MAX_TRACKS`](crate::MAX_TRACKS) distinct tracks are kept.
229    pub fn register_track(&mut self, track: u32) {
230        self.tracks.register(track, self.latest);
231    }
232
233    /// Remove `track` (a replaced or dead audio/video track) so it can no
234    /// longer hold back the lead: its end and any registration are forgotten
235    /// at once, so the minimum is taken over the remaining tracks and a
236    /// start/resume that was waiting on it is released on the next tick.
237    /// [`Stats::limiting_track`] and the track named by a later `Pause` follow
238    /// the remaining set. An unknown `track` is a no-op. If no track is left
239    /// there is no effective end (ticks do nothing, as before the first
240    /// delivery) until a track delivers or is registered again. The track may
241    /// be reported again later; it then rejoins as a new one.
242    pub fn unregister_track(&mut self, track: u32) {
243        self.tracks.unregister(track);
244    }
245
246    /// Per-track media position: `media_end_27mhz` is the end of the last
247    /// demuxed sample of `track` in the playback (PTS) domain (same units and
248    /// first-report rule and join-point caller contract as
249    /// [`on_media`](Self::on_media)). The controller keeps
250    /// every track's end and measures the lead against the **minimum over the
251    /// active tracks**. A track is excluded only when it is silent *relative to
252    /// the other tracks*: its last delivery is at least
253    /// [`ControllerConfig::track_silence_timeout`] before the most recent
254    /// delivery on any track. A global delivery gap (nothing delivered
255    /// anywhere) excludes nobody: the minimum of the last ends is kept, so a
256    /// reconnect does not make the controller resume on stale data. A `Pause` for starvation names the
257    /// limiting track in [`Event::Pause::track`] and [`Stats::limiting_track`].
258    ///
259    /// A `now` earlier than the latest instant seen on any call is clamped to it, as
260    /// [`on_hint`](Self::on_hint) does, so a stepped-back clock cannot stamp a delivery in the past.
261    pub fn on_track_media(&mut self, now: Duration, track: u32, media_end: Clock27) {
262        let now = now.max(self.latest);
263        self.latest = now;
264        self.jitter.anchor(now);
265        let rules = self.step_rules();
266        let Some(first) = self.tracks.deliver(track, now, media_end, rules) else {
267            return;
268        };
269        if self.granularity_need(now) > self.policy.target() {
270            // a coarser delivery cadence than the target covers: raise it now,
271            // not at the next PCR chunk
272            self.after_sample(now);
273        }
274        if !self.pcr_seen && self.effective().is_some() && self.feeds_estimator(track) {
275            self.fed_media = true;
276            self.feed(now, media_end, 0);
277        }
278        match self.queue_start {
279            None => self.queue_start = Some(media_end),
280            Some(q) if first && pcr_signed_distance(q.ticks(), media_end.ticks()) < 0 => {
281                self.queue_start = Some(media_end);
282            }
283            Some(_) => {}
284        }
285    }
286
287    /// A track taking over the PCR-less feed starts a fresh baseline: its
288    /// media clock is offset from the previous track's.
289    fn feeds_estimator(&mut self, track: u32) -> bool {
290        if self.media_ref == Some(track) {
291            return true;
292        }
293        if let Some(r) = self.media_ref {
294            if self
295                .tracks
296                .is_live(r, self.latest, self.cfg.track_silence_timeout)
297            {
298                return false;
299            }
300            if self.fed_media {
301                self.jitter.reset_baseline();
302            }
303        }
304        self.media_ref = Some(track);
305        true
306    }
307
308    fn step_rules(&self) -> StepRules {
309        StepRules {
310            max_interval: self.cfg.track_silence_timeout,
311            max_excess: self.cfg.nodata_after,
312            gap_end_at: self.gap_end_at,
313            epoch: self.chunks,
314        }
315    }
316
317    fn effective(&self) -> Option<Effective> {
318        self.tracks.effective(
319            self.latest,
320            self.cfg.track_silence_timeout,
321            self.state != State::Playing,
322        )
323    }
324
325    /// The limiting track, only meaningful with two or more tracks known.
326    fn limiting(&self) -> Option<u32> {
327        if self.tracks.len() < 2 {
328            return None;
329        }
330        self.effective().map(|e| e.limiting)
331    }
332
333    /// Delivery-granularity floor (`step + margin`), 0 when disabled or unknown.
334    fn granularity_need(&self, now: Duration) -> Duration {
335        if !self.cfg.track_granularity {
336            return Duration::ZERO;
337        }
338        let g = self.tracks.granularity(now, self.cfg.track_silence_timeout);
339        micros_as_duration(self.policy.granularity_need_us(instant_micros(g)))
340    }
341
342    fn feed(&mut self, arrival: Duration, media: Clock27, bytes: u32) {
343        match self.jitter.on_chunk(arrival, media, bytes) {
344            SampleOutcome::Accepted => self.after_sample(arrival),
345            SampleOutcome::Discontinuity => {
346                self.rebaseline(arrival, false);
347                self.after_sample(arrival);
348            }
349            SampleOutcome::NonMonotonicArrival => {
350                self.regressions = self.regressions.saturating_add(1);
351            }
352            SampleOutcome::Duplicate => {}
353        }
354    }
355
356    fn after_sample(&mut self, now: Duration) {
357        let base = instant_micros(self.jitter.baseline());
358        let peak = instant_micros(self.jitter.stall_peak_at(now));
359        let gran = if self.cfg.track_granularity {
360            instant_micros(self.tracks.granularity(now, self.cfg.track_silence_timeout))
361        } else {
362            0
363        };
364        let need = self.policy.need_with_granularity_us(base, peak, gran);
365        let max = instant_micros(self.cfg.policy.max);
366        if need > max {
367            if self.over_armed {
368                self.over_armed = false;
369                self.events.push(Event::OverMax {
370                    need: dur(need),
371                    max: dur(max),
372                });
373            }
374        } else if u128::from(need) * u128::from(REARM_DEN)
375            <= u128::from(max) * u128::from(REARM_NUM)
376        {
377            self.over_armed = true;
378        }
379        let new = self.policy.follow(need, instant_micros(now));
380        let old = self.reported_target;
381        if new != old {
382            let bound = new == instant_micros(self.cfg.policy.min) || new == max;
383            let moved = new.max(old) - new.min(old);
384            if moved >= instant_micros(self.cfg.jitter.bucket) || bound {
385                self.reported_target = new;
386                self.events.push(Event::TargetChanged {
387                    old: dur(old),
388                    new: dur(new),
389                });
390            }
391        }
392    }
393
394    /// Periodic tick (recommended 50 ms). `playback_27mhz` is the renderer
395    /// clock in the PTS domain, `None` while it is not running; it is only
396    /// read while `Playing` (while paused the controller uses the position it
397    /// told the caller to hold).
398    pub fn on_tick(&mut self, now: Duration, playback_27mhz: Option<Clock27>) {
399        let now = if now < self.last_tick {
400            self.regressions = self.regressions.saturating_add(1);
401            self.last_tick
402        } else {
403            self.last_tick = now;
404            now
405        };
406        self.latest = self.latest.max(now);
407        self.jitter.anchor(now);
408        if playback_27mhz.is_some() {
409            self.last_playback = playback_27mhz;
410        }
411        let Some(media_end) = self.effective().map(|e| e.end) else {
412            return;
413        };
414        if self.state == State::Playing {
415            let Some(p) = playback_27mhz else { return };
416            let lead = lead_between(p, media_end);
417            self.lead = lead;
418            if lead <= i64::try_from(instant_micros(self.cfg.starve_threshold)).unwrap_or(i64::MAX)
419            {
420                self.pause_starved(now, p, media_end, lead);
421            } else {
422                self.maybe_reprime(now, p, media_end, lead);
423            }
424            return;
425        }
426        let Some(origin) = self.fill_from.or(self.queue_start) else {
427            return;
428        };
429        let lead = lead_between(origin, media_end);
430        self.lead = lead;
431        let need = instant_micros(self.exit_target(now));
432        if lead >= i64::try_from(need).unwrap_or(i64::MAX) && self.granularity_ready(now) {
433            self.begin_playing(now, origin, lead);
434        }
435    }
436
437    /// Start/resume gate on the delivery granularity (see the module docs of
438    /// [`crate::tracks`]): every delivering track must have shown enough
439    /// deliveries to know its cadence, bounded by the start fill so a slow
440    /// track cannot block forever.
441    fn granularity_ready(&self, now: Duration) -> bool {
442        !self.cfg.track_granularity
443            || self.tracks.granularity_known(
444                now,
445                self.cfg.track_silence_timeout,
446                self.policy.start(),
447            )
448    }
449
450    fn exit_target(&self, now: Duration) -> Duration {
451        if !self.started {
452            self.policy.start()
453        } else if self.neutral_pause {
454            self.policy.target()
455        } else {
456            self.policy.resume(self.jitter.stall_peak_at(now))
457        }
458    }
459
460    fn begin_playing(&mut self, now: Duration, origin: Clock27, lead: i64) {
461        let lead = dur(to_u64(lead));
462        if self.started {
463            let freeze = now.saturating_sub(self.pause_at);
464            self.longest_freeze = self.longest_freeze.max(freeze);
465            if !self.neutral_pause {
466                self.last_stall_depth = self.jitter.stall_peak_at(now);
467            }
468            self.events.push(Event::Resume {
469                media_27mhz: origin,
470                lead,
471            });
472        } else {
473            self.started = true;
474            self.events.push(Event::StartPlaying {
475                media_27mhz: origin,
476                lead,
477            });
478        }
479        self.state = State::Playing;
480        self.fill_from = None;
481        self.neutral_pause = false;
482        self.below_since = None;
483    }
484
485    fn enter_pause(
486        &mut self,
487        now: Duration,
488        hold_at: Clock27,
489        reason: Reason,
490        neutral: bool,
491        lead: i64,
492        track: Option<u32>,
493    ) {
494        self.reason = reason;
495        self.neutral_pause = neutral;
496        self.pause_at = now;
497        self.below_since = None;
498        let resume_target = if neutral {
499            self.policy.target()
500        } else {
501            self.policy.resume(self.jitter.stall_peak_at(now))
502        };
503        self.events.push(Event::Pause {
504            hold_at_27mhz: hold_at,
505            reason,
506            depth: dur(to_u64(lead)),
507            resume_target,
508            track,
509        });
510    }
511
512    fn pause_starved(&mut self, now: Duration, playback: Clock27, media_end: Clock27, lead: i64) {
513        let hold_at = if lead < 0 { media_end } else { playback };
514        let silent = self
515            .last_chunk_at
516            .is_none_or(|t| duration_between(t, now) >= self.cfg.nodata_after);
517        let reason = if self.source_down || silent {
518            Reason::NoData
519        } else {
520            Reason::DataArriving
521        };
522        self.stalls = self.stalls.saturating_add(1);
523        if reason == Reason::DataArriving {
524            // Starved with data flowing (track-limited delivery, no gap): the
525            // PDV never saw it, so charge the failed target to the stall memory
526            // (a repeat then ratchets the target and the resume bar).
527            self.jitter.note_starvation(now, self.policy.target());
528        }
529        let track = self.limiting();
530        self.enter_pause(now, hold_at, reason, false, lead, track);
531        if reason == Reason::DataArriving {
532            // after the Pause event: the target follows the new stall memory now
533            self.after_sample(now);
534        }
535        self.state = State::Starved;
536        self.fill_from = Some(hold_at);
537    }
538
539    fn maybe_reprime(&mut self, now: Duration, playback: Clock27, media_end: Clock27, lead: i64) {
540        let floor = self.cfg.policy.reprime_floor;
541        if floor == Duration::ZERO {
542            return;
543        }
544        if lead < i64::try_from(instant_micros(floor)).unwrap_or(i64::MAX) {
545            let since = *self.below_since.get_or_insert(now);
546            if duration_between(since, now) >= self.cfg.policy.reprime_hold {
547                let hold_at = if lead < 0 { media_end } else { playback };
548                self.reprimes = self.reprimes.saturating_add(1);
549                let track = self.limiting();
550                self.enter_pause(now, hold_at, Reason::Reprime, true, lead, track);
551                self.state = State::Starved;
552                self.fill_from = Some(hold_at);
553            }
554        } else {
555            self.below_since = None;
556        }
557    }
558
559    /// Report an out-of-band hint. `Reconnected` must be sent before the
560    /// first chunk of the new connection is fed.
561    pub fn on_hint(&mut self, now: Duration, hint: Hint) {
562        let now = now.max(self.latest);
563        self.latest = now;
564        self.jitter.anchor(now);
565        self.hints = self.hints.saturating_add(1);
566        match hint {
567            Hint::InputDegraded => self.degraded = true,
568            Hint::InputRecovered => self.degraded = false,
569            Hint::SourceEnded | Hint::SourceError => self.source_down = true,
570            Hint::Reconnected => {
571                self.source_down = false;
572                self.rebaseline(now, true);
573            }
574            Hint::SyncLoss | Hint::PcrDiscontinuity => self.rebaseline(now, true),
575        }
576    }
577
578    fn rebaseline(&mut self, now: Duration, reset_jitter: bool) {
579        if reset_jitter {
580            self.jitter.reset_baseline();
581        }
582        self.discontinuities = self.discontinuities.saturating_add(1);
583        let old_end = self.effective().map(|e| e.end);
584        self.tracks.rebaseline(now);
585        self.queue_start = None;
586        match self.state {
587            State::Playing => {
588                let hold_at = match (self.last_playback, old_end) {
589                    (Some(p), Some(e)) => {
590                        if lead_between(p, e) >= 0 {
591                            p
592                        } else {
593                            e
594                        }
595                    }
596                    (None, Some(e)) => e,
597                    (Some(p), None) => p,
598                    (None, None) => Clock27::from_27mhz(0).expect("zero is on the clock"),
599                };
600                let lead = self.lead;
601                self.enter_pause(now, hold_at, Reason::Discontinuity, true, lead, None);
602                self.state = State::Buffering;
603                self.fill_from = None;
604            }
605            State::Starved => {
606                self.state = State::Buffering;
607                self.reason = Reason::Discontinuity;
608                self.neutral_pause = true;
609                self.fill_from = None;
610            }
611            State::Buffering => self.fill_from = None,
612        }
613        self.events.push(Event::Rebaselined);
614    }
615
616    /// Next pending event, oldest first. An `EventsDropped` precedes the
617    /// survivors after an overflow.
618    pub fn poll_event(&mut self) -> Option<Event> {
619        self.events.poll()
620    }
621
622    /// Current state.
623    #[must_use]
624    pub fn state(&self) -> State {
625        self.state
626    }
627
628    /// Current desired lead; always within `[min, max]`.
629    #[must_use]
630    pub fn target(&self) -> Duration {
631        self.policy.target()
632    }
633
634    /// Statistics snapshot.
635    #[must_use]
636    pub fn stats(&self) -> Stats {
637        let lead = dur(to_u64(self.lead));
638        Stats {
639            state: self.state,
640            reason: self.reason,
641            lead,
642            target: self.policy.target(),
643            stalls: self.stalls,
644            reprimes: self.reprimes,
645            last_stall_depth: self.last_stall_depth,
646            longest_freeze: self.longest_freeze,
647            est: self.jitter.estimate(),
648            clock_regressions: self.regressions,
649            discontinuities: self.discontinuities,
650            hints_seen: self.hints,
651            events_dropped: self.events.dropped_total(),
652            input_degraded: self.degraded,
653            window_overflows: self.jitter.window_overflows(),
654            limiting_track: self.limiting(),
655        }
656    }
657
658    /// The stall memory, for persistence (age it on restore with
659    /// [`StallMemorySnapshot::aged`]).
660    #[must_use]
661    pub fn snapshot_memory(&self) -> StallMemorySnapshot {
662        self.jitter.snapshot_at(self.latest)
663    }
664
665    /// Install a stall memory and lift the target to what it implies.
666    pub fn restore_memory(&mut self, snapshot: StallMemorySnapshot) {
667        self.jitter.restore(snapshot);
668        self.reseed();
669    }
670
671    fn reseed(&mut self) {
672        let peak = instant_micros(self.jitter.stall_peak_at(self.latest));
673        self.policy.raise(self.policy.need_us(0, peak));
674        self.reported_target = self.policy.target_us();
675    }
676
677    /// New channel (`keep_memory = false`) or reconnect-style restart
678    /// (`keep_memory = true`): back to the first fill; counters are kept.
679    pub fn reset(&mut self, keep_memory: bool) {
680        let kept = keep_memory.then(|| self.jitter.snapshot_at(self.latest));
681        self.jitter.reset();
682        self.policy.reset();
683        self.events.clear();
684        self.state = State::Buffering;
685        self.reason = Reason::Startup;
686        self.started = false;
687        self.neutral_pause = false;
688        self.last_chunk_at = None;
689        self.gap_end_at = None;
690        self.tracks.clear();
691        self.queue_start = None;
692        self.last_playback = None;
693        self.fill_from = None;
694        self.source_down = false;
695        self.degraded = false;
696        self.pcr_seen = false;
697        self.fed_media = false;
698        self.media_ref = None;
699        self.below_since = None;
700        self.over_armed = true;
701        self.lead = 0;
702        self.reported_target = instant_micros(self.cfg.policy.min);
703        if let Some(s) = kept {
704            self.restore_memory(s);
705        }
706    }
707}