Skip to main content

buffering_runtime/
events.rs

1//! Controller states, hints, events and statistics.
2//!
3//! Every enum has a stable `u32` code (`code()`), used by the C-ABI mirror;
4//! codes are never renumbered. [`Event`] converts to the `#[repr(C)]`
5//! [`EventRecord`] with [`Event::to_record`]; the `a_us` / `b_us` meaning per
6//! kind is the table on [`EventRecord`].
7
8use crate::config::{Micros, Ticks27};
9use crate::jitter::JitterEstimate;
10use alloc::collections::VecDeque;
11
12/// Event queue capacity (oldest non-critical event dropped first).
13pub(crate) const EVENT_QUEUE_CAP: usize = 16;
14
15/// Controller state.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize))]
18#[non_exhaustive]
19pub enum State {
20    /// Filling: first fill, or refilling after a discontinuity.
21    Buffering,
22    /// Rendering; the caller's clock runs at rate 1.
23    Playing,
24    /// Paused for an underrun or a voluntary re-prime, refilling.
25    Starved,
26}
27
28impl State {
29    /// Stable label.
30    #[must_use]
31    pub fn name(&self) -> &'static str {
32        match self {
33            Self::Buffering => "buffering",
34            Self::Playing => "playing",
35            Self::Starved => "starved",
36        }
37    }
38    /// Stable ABI code.
39    #[must_use]
40    pub fn code(&self) -> u32 {
41        match self {
42            Self::Buffering => 1,
43            Self::Playing => 2,
44            Self::Starved => 3,
45        }
46    }
47}
48broadcast_common::impl_spec_display!(State);
49
50/// Why the controller is not playing.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize))]
53#[non_exhaustive]
54pub enum Reason {
55    /// First fill after construction/reset.
56    Startup,
57    /// Lead exhausted and no chunk for `nodata_after_us` (or the source ended).
58    NoData,
59    /// Lead exhausted while chunks were still arriving.
60    DataArriving,
61    /// Baseline reset (reconnect, sync loss, PCR discontinuity).
62    Discontinuity,
63    /// Voluntary re-prime (`reprime_floor_us`).
64    Reprime,
65}
66
67impl Reason {
68    /// Stable label.
69    #[must_use]
70    pub fn name(&self) -> &'static str {
71        match self {
72            Self::Startup => "startup",
73            Self::NoData => "no data",
74            Self::DataArriving => "data arriving",
75            Self::Discontinuity => "discontinuity",
76            Self::Reprime => "reprime",
77        }
78    }
79    /// Stable ABI code.
80    #[must_use]
81    pub fn code(&self) -> u32 {
82        match self {
83            Self::Startup => 1,
84            Self::NoData => 2,
85            Self::DataArriving => 3,
86            Self::Discontinuity => 4,
87            Self::Reprime => 5,
88        }
89    }
90}
91broadcast_common::impl_spec_display!(Reason);
92
93/// Out-of-band input the caller reports. Non-authoritative except where
94/// stated: starvation is only ever declared from lead and the clock.
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96#[cfg_attr(feature = "serde", derive(serde::Serialize))]
97#[non_exhaustive]
98pub enum Hint {
99    /// Continuity errors / TEI seen: recorded in `Stats::input_degraded` only.
100    InputDegraded,
101    /// The degradation ended.
102    InputRecovered,
103    /// Sync loss: re-baseline.
104    SyncLoss,
105    /// The caller saw a PCR discontinuity: re-baseline.
106    PcrDiscontinuity,
107    /// The connection ended: later pauses report `NoData`.
108    SourceEnded,
109    /// The connection failed: later pauses report `NoData`.
110    SourceError,
111    /// First chunk of a new connection follows (send BEFORE feeding it):
112    /// re-baseline, keep the stall memory, resume at the target.
113    Reconnected,
114}
115
116impl Hint {
117    /// Stable label.
118    #[must_use]
119    pub fn name(&self) -> &'static str {
120        match self {
121            Self::InputDegraded => "input degraded",
122            Self::InputRecovered => "input recovered",
123            Self::SyncLoss => "sync loss",
124            Self::PcrDiscontinuity => "pcr discontinuity",
125            Self::SourceEnded => "source ended",
126            Self::SourceError => "source error",
127            Self::Reconnected => "reconnected",
128        }
129    }
130    /// Stable ABI code (`br_on_hint`).
131    #[must_use]
132    pub fn code(&self) -> u32 {
133        match self {
134            Self::InputDegraded => 1,
135            Self::InputRecovered => 2,
136            Self::SyncLoss => 3,
137            Self::PcrDiscontinuity => 4,
138            Self::SourceEnded => 5,
139            Self::SourceError => 6,
140            Self::Reconnected => 7,
141        }
142    }
143    /// Inverse of [`code`](Self::code); `None` for an unknown code.
144    #[must_use]
145    pub fn from_code(code: u32) -> Option<Self> {
146        Some(match code {
147            1 => Self::InputDegraded,
148            2 => Self::InputRecovered,
149            3 => Self::SyncLoss,
150            4 => Self::PcrDiscontinuity,
151            5 => Self::SourceEnded,
152            6 => Self::SourceError,
153            7 => Self::Reconnected,
154            _ => return None,
155        })
156    }
157}
158broadcast_common::impl_spec_display!(Hint);
159
160/// A decision for the caller. Media positions are in the **playback (PTS)
161/// domain** as 27 MHz ticks (`PTS90k x 300`), i.e. the domain of `on_media`
162/// and `on_tick`'s `playback`.
163#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164#[cfg_attr(feature = "serde", derive(serde::Serialize))]
165#[non_exhaustive]
166pub enum Event {
167    /// First fill complete. Set the renderer clock to `media_27mhz` (the
168    /// oldest buffered media) and rate 1.
169    StartPlaying {
170        /// Position to start from.
171        media_27mhz: Ticks27,
172        /// Lead at the decision.
173        lead_us: Micros,
174    },
175    /// Underrun or re-prime. Set the renderer rate to 0 and hold the clock at
176    /// `hold_at_27mhz`; keep queueing every chunk that arrives meanwhile.
177    Pause {
178        /// Position to freeze at (never ahead of the data).
179        hold_at_27mhz: Ticks27,
180        /// Why.
181        reason: Reason,
182        /// Buffered lead at the pause (0 if the clock overran the data).
183        depth_us: Micros,
184        /// Resume target known now; it can rise when the first post-stall
185        /// chunk reveals the stall depth.
186        resume_target_us: Micros,
187        /// For an underrun or re-prime with two or more tracks known: the
188        /// track whose media end bounded the lead (the starving track).
189        /// `None` otherwise (single track, discontinuity).
190        track: Option<u32>,
191    },
192    /// Refilled. Re-seed the renderer clock to exactly `media_27mhz` and set
193    /// rate 1 in one step.
194    ///
195    /// **Resume is also a "go".** After a `Hint::PcrDiscontinuity` (or
196    /// `SyncLoss`/`Reconnected`) while `Playing` the controller emits `Pause`
197    /// then, once refilled, `Resume`, never a second `StartPlaying`
198    /// (`StartPlaying` happens once per controller until `reset`). A caller
199    /// must therefore treat `StartPlaying` and `Resume` identically as "set the
200    /// clock to `media_27mhz` and rate 1". If that differs from the clock at pause (after a
201    /// discontinuity) it is a time jump on the caller's side: re-enqueue
202    /// from there if the audio renderer flushes.
203    Resume {
204        /// Position to restart from.
205        media_27mhz: Ticks27,
206        /// Lead at the decision.
207        lead_us: Micros,
208    },
209    /// The target moved by at least one histogram bucket (or hit a bound).
210    TargetChanged {
211        /// Previously reported target.
212        old_us: Micros,
213        /// New target (never above `max_us`).
214        new_us: Micros,
215    },
216    /// The estimated need exceeds `max_us`; the target is clamped (the cap is
217    /// a guarantee). Raised once per excursion.
218    OverMax {
219        /// Unclamped need.
220        need_us: Micros,
221        /// The cap.
222        max_us: Micros,
223    },
224    /// The baseline was reset (discontinuity, reconnect, sync loss).
225    Rebaselined,
226    /// Events were lost because the caller did not poll in time.
227    EventsDropped {
228        /// How many.
229        count: u32,
230    },
231}
232
233/// Event kind codes (stable).
234pub mod kind {
235    /// [`Event::StartPlaying`](super::Event::StartPlaying)
236    pub const START_PLAYING: u32 = 1;
237    /// [`Event::Pause`](super::Event::Pause)
238    pub const PAUSE: u32 = 2;
239    /// [`Event::Resume`](super::Event::Resume)
240    pub const RESUME: u32 = 3;
241    /// [`Event::TargetChanged`](super::Event::TargetChanged)
242    pub const TARGET_CHANGED: u32 = 4;
243    /// [`Event::OverMax`](super::Event::OverMax)
244    pub const OVER_MAX: u32 = 5;
245    /// [`Event::Rebaselined`](super::Event::Rebaselined)
246    pub const REBASELINED: u32 = 6;
247    /// [`Event::EventsDropped`](super::Event::EventsDropped)
248    pub const EVENTS_DROPPED: u32 = 7;
249}
250
251/// Plain-data, `#[repr(C)]` form of an [`Event`] for a C ABI.
252///
253/// | kind | `reason` | `media_27mhz` | `a_us` | `b_us` |
254/// |---|---|---|---|---|
255/// | 1 StartPlaying | 0 | start position | lead | 0 |
256/// | 2 Pause | [`Reason::code`] | hold position | depth | resume target |
257/// | 3 Resume | 0 | restart position | lead | 0 |
258/// | 4 TargetChanged | 0 | 0 | old target | new target |
259/// | 5 OverMax | 0 | 0 | need | max |
260/// | 6 Rebaselined | 0 | 0 | 0 | 0 |
261/// | 7 EventsDropped | 0 | 0 | count | 0 |
262///
263/// `track_valid` is 1 only for a `Pause` that names the starving track in
264/// `track` (two or more tracks known); otherwise both are 0. Layout (ABI
265/// version 2): 40 bytes, `kind@0 reason@4 media_27mhz@8 a_us@16 b_us@24
266/// track@32 track_valid@36`.
267///
268/// There is no separate "Starved" event: a starvation is a `Pause` whose
269/// `reason` is 2/3 and whose `a_us` is the lead at that instant.
270#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
271#[cfg_attr(feature = "serde", derive(serde::Serialize))]
272#[repr(C)]
273pub struct EventRecord {
274    /// Event kind code (see [`kind`]).
275    pub kind: u32,
276    /// Pause reason code, else 0.
277    pub reason: u32,
278    /// Media position (PTS domain, 27 MHz), else 0.
279    pub media_27mhz: u64,
280    /// First value (table above).
281    pub a_us: u64,
282    /// Second value (table above).
283    pub b_us: u64,
284    /// The starving track when `track_valid == 1`, else 0.
285    pub track: u32,
286    /// 1 when `track` is meaningful, else 0.
287    pub track_valid: u32,
288}
289
290impl Event {
291    /// Convert to the plain-data record.
292    #[must_use]
293    pub fn to_record(&self) -> EventRecord {
294        let mut r = EventRecord::default();
295        match *self {
296            Self::StartPlaying {
297                media_27mhz,
298                lead_us,
299            } => {
300                r.kind = kind::START_PLAYING;
301                r.media_27mhz = media_27mhz;
302                r.a_us = lead_us;
303            }
304            Self::Pause {
305                hold_at_27mhz,
306                reason,
307                depth_us,
308                resume_target_us,
309                track,
310            } => {
311                r.kind = kind::PAUSE;
312                if let Some(t) = track {
313                    r.track = t;
314                    r.track_valid = 1;
315                }
316                r.reason = reason.code();
317                r.media_27mhz = hold_at_27mhz;
318                r.a_us = depth_us;
319                r.b_us = resume_target_us;
320            }
321            Self::Resume {
322                media_27mhz,
323                lead_us,
324            } => {
325                r.kind = kind::RESUME;
326                r.media_27mhz = media_27mhz;
327                r.a_us = lead_us;
328            }
329            Self::TargetChanged { old_us, new_us } => {
330                r.kind = kind::TARGET_CHANGED;
331                r.a_us = old_us;
332                r.b_us = new_us;
333            }
334            Self::OverMax { need_us, max_us } => {
335                r.kind = kind::OVER_MAX;
336                r.a_us = need_us;
337                r.b_us = max_us;
338            }
339            Self::Rebaselined => r.kind = kind::REBASELINED,
340            Self::EventsDropped { count } => {
341                r.kind = kind::EVENTS_DROPPED;
342                r.a_us = u64::from(count);
343            }
344        }
345        r
346    }
347
348    /// Stable label of the variant.
349    #[must_use]
350    pub fn name(&self) -> &'static str {
351        match self {
352            Self::StartPlaying { .. } => "start playing",
353            Self::Pause { .. } => "pause",
354            Self::Resume { .. } => "resume",
355            Self::TargetChanged { .. } => "target changed",
356            Self::OverMax { .. } => "over max",
357            Self::Rebaselined => "rebaselined",
358            Self::EventsDropped { .. } => "events dropped",
359        }
360    }
361
362    /// Pause/Resume/StartPlaying must never be lost.
363    fn is_critical(&self) -> bool {
364        matches!(
365            self,
366            Self::StartPlaying { .. } | Self::Pause { .. } | Self::Resume { .. }
367        )
368    }
369}
370broadcast_common::impl_spec_display!(Event);
371
372/// Controller statistics.
373#[derive(Clone, Copy, Debug, PartialEq, Eq)]
374#[cfg_attr(feature = "serde", derive(serde::Serialize))]
375#[non_exhaustive]
376pub struct Stats {
377    /// Current state.
378    pub state: State,
379    /// Reason of the most recent non-playing period (`Startup` initially);
380    /// meaningful only while `state != Playing`.
381    pub reason: crate::events::Reason,
382    /// Signed lead at the last tick (negative: the clock ran ahead of the media).
383    pub lead_us: i64,
384    /// Current target.
385    pub target_us: Micros,
386    /// Underrun pauses (not the first fill, discontinuities or re-primes).
387    pub stalls: u32,
388    /// Voluntary re-primes.
389    pub reprimes: u32,
390    /// Stall-memory peak when the last stall ended.
391    pub last_stall_depth_us: Micros,
392    /// Longest pause (Pause to Resume).
393    pub longest_freeze_us: Micros,
394    /// Estimator outputs.
395    pub est: JitterEstimate,
396    /// Arrival/tick clock regressions seen (clamped or ignored).
397    pub clock_regressions: u32,
398    /// Baseline resets.
399    pub discontinuities: u32,
400    /// Hints received.
401    pub hints_seen: u32,
402    /// Events lost to queue overflow.
403    pub events_dropped: u32,
404    /// Between `InputDegraded` and `InputRecovered`.
405    pub input_degraded: bool,
406    /// Minimum-window entries dropped by the cap.
407    pub window_overflows: u32,
408    /// With two or more tracks known: the track currently bounding the media
409    /// end (the one that would starve first); `None` otherwise.
410    pub limiting_track: Option<u32>,
411}
412
413/// Bounded event queue: when full, the oldest non-critical event is dropped
414/// (the oldest of all if every queued event is critical) and counted; the
415/// loss is reported by one `EventsDropped` ahead of the survivors.
416#[derive(Clone, Debug, Default)]
417pub(crate) struct EventQueue {
418    q: VecDeque<Event>,
419    dropped_pending: u32,
420    dropped_total: u32,
421}
422
423impl EventQueue {
424    pub(crate) fn new() -> Self {
425        Self {
426            q: VecDeque::with_capacity(EVENT_QUEUE_CAP + 1),
427            dropped_pending: 0,
428            dropped_total: 0,
429        }
430    }
431
432    pub(crate) fn push(&mut self, e: Event) {
433        if self.q.len() >= EVENT_QUEUE_CAP {
434            let victim = self.q.iter().position(|x| !x.is_critical());
435            match victim {
436                Some(i) => {
437                    self.q.remove(i);
438                }
439                None => {
440                    self.q.pop_front();
441                }
442            }
443            self.dropped_pending = self.dropped_pending.saturating_add(1);
444            self.dropped_total = self.dropped_total.saturating_add(1);
445        }
446        self.q.push_back(e);
447    }
448
449    pub(crate) fn poll(&mut self) -> Option<Event> {
450        if self.dropped_pending > 0 {
451            let count = core::mem::take(&mut self.dropped_pending);
452            return Some(Event::EventsDropped { count });
453        }
454        self.q.pop_front()
455    }
456
457    pub(crate) fn dropped_total(&self) -> u32 {
458        self.dropped_total
459    }
460
461    pub(crate) fn clear(&mut self) {
462        self.q.clear();
463        self.dropped_pending = 0;
464    }
465}