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