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` / `b` meaning per
6//! kind is the table on [`EventRecord`].
7
8use core::time::Duration;
9
10use crate::jitter::JitterEstimate;
11use crate::time::{Clock27, instant_micros};
12use alloc::collections::VecDeque;
13
14/// Event queue capacity (oldest non-critical event dropped first).
15pub(crate) const EVENT_QUEUE_CAP: usize = 16;
16
17/// Controller state.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize))]
20#[non_exhaustive]
21pub enum State {
22 /// Filling: first fill, or refilling after a discontinuity.
23 Buffering,
24 /// Rendering; the caller's clock runs at rate 1.
25 Playing,
26 /// Paused for an underrun or a voluntary re-prime, refilling.
27 Starved,
28}
29
30impl State {
31 /// Stable label.
32 #[must_use]
33 pub fn name(&self) -> &'static str {
34 match self {
35 Self::Buffering => "buffering",
36 Self::Playing => "playing",
37 Self::Starved => "starved",
38 }
39 }
40 /// Stable ABI code.
41 #[must_use]
42 pub fn code(&self) -> u32 {
43 match self {
44 Self::Buffering => 1,
45 Self::Playing => 2,
46 Self::Starved => 3,
47 }
48 }
49}
50broadcast_common::impl_spec_display!(State);
51
52/// Why the controller is not playing.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize))]
55#[non_exhaustive]
56pub enum Reason {
57 /// First fill after construction/reset.
58 Startup,
59 /// Lead exhausted and no chunk for `nodata_after` (or the source ended).
60 NoData,
61 /// Lead exhausted while chunks were still arriving.
62 DataArriving,
63 /// Baseline reset (reconnect, sync loss, PCR discontinuity).
64 Discontinuity,
65 /// Voluntary re-prime (`reprime_floor`).
66 Reprime,
67}
68
69impl Reason {
70 /// Stable label.
71 #[must_use]
72 pub fn name(&self) -> &'static str {
73 match self {
74 Self::Startup => "startup",
75 Self::NoData => "no data",
76 Self::DataArriving => "data arriving",
77 Self::Discontinuity => "discontinuity",
78 Self::Reprime => "reprime",
79 }
80 }
81 /// Stable ABI code.
82 #[must_use]
83 pub fn code(&self) -> u32 {
84 match self {
85 Self::Startup => 1,
86 Self::NoData => 2,
87 Self::DataArriving => 3,
88 Self::Discontinuity => 4,
89 Self::Reprime => 5,
90 }
91 }
92}
93broadcast_common::impl_spec_display!(Reason);
94
95/// Out-of-band input the caller reports. Non-authoritative except where
96/// stated: starvation is only ever declared from lead and the clock.
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98#[cfg_attr(feature = "serde", derive(serde::Serialize))]
99#[non_exhaustive]
100pub enum Hint {
101 /// Continuity errors / TEI seen: recorded in `Stats::input_degraded` only.
102 InputDegraded,
103 /// The degradation ended.
104 InputRecovered,
105 /// Sync loss: re-baseline.
106 SyncLoss,
107 /// The caller saw a PCR discontinuity: re-baseline.
108 PcrDiscontinuity,
109 /// The connection ended: later pauses report `NoData`.
110 SourceEnded,
111 /// The connection failed: later pauses report `NoData`.
112 SourceError,
113 /// First chunk of a new connection follows (send BEFORE feeding it):
114 /// re-baseline, keep the stall memory, resume at the target.
115 Reconnected,
116}
117
118impl Hint {
119 /// Stable label.
120 #[must_use]
121 pub fn name(&self) -> &'static str {
122 match self {
123 Self::InputDegraded => "input degraded",
124 Self::InputRecovered => "input recovered",
125 Self::SyncLoss => "sync loss",
126 Self::PcrDiscontinuity => "pcr discontinuity",
127 Self::SourceEnded => "source ended",
128 Self::SourceError => "source error",
129 Self::Reconnected => "reconnected",
130 }
131 }
132 /// Stable ABI code (`br_on_hint`).
133 #[must_use]
134 pub fn code(&self) -> u32 {
135 match self {
136 Self::InputDegraded => 1,
137 Self::InputRecovered => 2,
138 Self::SyncLoss => 3,
139 Self::PcrDiscontinuity => 4,
140 Self::SourceEnded => 5,
141 Self::SourceError => 6,
142 Self::Reconnected => 7,
143 }
144 }
145 /// Inverse of [`code`](Self::code); `None` for an unknown code.
146 #[must_use]
147 pub fn from_code(code: u32) -> Option<Self> {
148 Some(match code {
149 1 => Self::InputDegraded,
150 2 => Self::InputRecovered,
151 3 => Self::SyncLoss,
152 4 => Self::PcrDiscontinuity,
153 5 => Self::SourceEnded,
154 6 => Self::SourceError,
155 7 => Self::Reconnected,
156 _ => return None,
157 })
158 }
159}
160broadcast_common::impl_spec_display!(Hint);
161
162/// A decision for the caller. Media positions are in the **playback (PTS)
163/// domain** as 27 MHz ticks (`PTS90k x 300`), i.e. the domain of `on_media`
164/// and `on_tick`'s `playback`.
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166#[cfg_attr(feature = "serde", derive(serde::Serialize))]
167#[non_exhaustive]
168pub enum Event {
169 /// First fill complete. Set the renderer clock to `media_27mhz` (the
170 /// oldest buffered media) and rate 1.
171 StartPlaying {
172 /// Position to start from.
173 media_27mhz: Clock27,
174 /// Lead at the decision.
175 lead: Duration,
176 },
177 /// Underrun or re-prime. Set the renderer rate to 0 and hold the clock at
178 /// `hold_at_27mhz`; keep queueing every chunk that arrives meanwhile.
179 Pause {
180 /// Position to freeze at (never ahead of the data).
181 hold_at_27mhz: Clock27,
182 /// Why.
183 reason: Reason,
184 /// Buffered lead at the pause (0 if the clock overran the data).
185 depth: Duration,
186 /// Resume target known now; it can rise when the first post-stall
187 /// chunk reveals the stall depth.
188 resume_target: Duration,
189 /// For an underrun or re-prime with two or more tracks known: the
190 /// track whose media end bounded the lead (the starving track).
191 /// `None` otherwise (single track, discontinuity).
192 track: Option<u32>,
193 },
194 /// Refilled. Re-seed the renderer clock to exactly `media_27mhz` and set
195 /// rate 1 in one step.
196 ///
197 /// **Resume is also a "go".** After a `Hint::PcrDiscontinuity` (or
198 /// `SyncLoss`/`Reconnected`) while `Playing` the controller emits `Pause`
199 /// then, once refilled, `Resume`, never a second `StartPlaying`
200 /// (`StartPlaying` happens once per controller until `reset`). A caller
201 /// must therefore treat `StartPlaying` and `Resume` identically as "set the
202 /// clock to `media_27mhz` and rate 1". If that differs from the clock at pause (after a
203 /// discontinuity) it is a time jump on the caller's side: re-enqueue
204 /// from there if the audio renderer flushes.
205 Resume {
206 /// Position to restart from.
207 media_27mhz: Clock27,
208 /// Lead at the decision.
209 lead: Duration,
210 },
211 /// The target moved by at least one histogram bucket (or hit a bound).
212 TargetChanged {
213 /// Previously reported target.
214 old: Duration,
215 /// New target (never above `max`).
216 new: Duration,
217 },
218 /// The estimated need exceeds the configured `max`; the target is clamped
219 /// (the cap is a guarantee). Raised once per excursion.
220 OverMax {
221 /// Unclamped need.
222 need: Duration,
223 /// The cap.
224 max: Duration,
225 },
226 /// The baseline was reset (discontinuity, reconnect, sync loss).
227 Rebaselined,
228 /// Events were lost because the caller did not poll in time.
229 EventsDropped {
230 /// How many.
231 count: u32,
232 },
233}
234
235/// Event kind codes (stable).
236pub mod kind {
237 /// [`Event::StartPlaying`](super::Event::StartPlaying)
238 pub const START_PLAYING: u32 = 1;
239 /// [`Event::Pause`](super::Event::Pause)
240 pub const PAUSE: u32 = 2;
241 /// [`Event::Resume`](super::Event::Resume)
242 pub const RESUME: u32 = 3;
243 /// [`Event::TargetChanged`](super::Event::TargetChanged)
244 pub const TARGET_CHANGED: u32 = 4;
245 /// [`Event::OverMax`](super::Event::OverMax)
246 pub const OVER_MAX: u32 = 5;
247 /// [`Event::Rebaselined`](super::Event::Rebaselined)
248 pub const REBASELINED: u32 = 6;
249 /// [`Event::EventsDropped`](super::Event::EventsDropped)
250 pub const EVENTS_DROPPED: u32 = 7;
251}
252
253/// Plain-data, `#[repr(C)]` form of an [`Event`] for a C ABI.
254///
255/// | kind | `reason` | `media_27mhz` | `a` | `b` |
256/// |---|---|---|---|---|
257/// | 1 StartPlaying | 0 | start position | lead, µs | 0 |
258/// | 2 Pause | [`Reason::code`] | hold position | depth, µs | resume target, µs |
259/// | 3 Resume | 0 | restart position | lead, µs | 0 |
260/// | 4 TargetChanged | 0 | 0 | old target, µs | new target, µs |
261/// | 5 OverMax | 0 | 0 | need, µs | max, µs |
262/// | 6 Rebaselined | 0 | 0 | 0 | 0 |
263/// | 7 EventsDropped | 0 | 0 | count | 0 |
264///
265/// `a`/`b` are whole microseconds: the `#[repr(C)]` record is an
266/// integer-only ABI, so a `Duration` crosses it by its microsecond value.
267///
268/// `track_valid` is 1 only for a `Pause` that names the starving track in
269/// `track` (two or more tracks known); otherwise both are 0. Layout (ABI
270/// version 2): 40 bytes, `kind@0 reason@4 media_27mhz@8 a@16 b@24
271/// track@32 track_valid@36`.
272///
273/// There is no separate "Starved" event: a starvation is a `Pause` whose
274/// `reason` is 2/3 and whose `a` is the lead at that instant.
275#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
276#[cfg_attr(feature = "serde", derive(serde::Serialize))]
277#[repr(C)]
278#[non_exhaustive]
279pub struct EventRecord {
280 /// Event kind code (see [`kind`]).
281 pub kind: u32,
282 /// Pause reason code, else 0.
283 pub reason: u32,
284 /// Media position (PTS domain, 27 MHz), else 0.
285 pub media_27mhz: u64,
286 /// First value in whole microseconds (table above).
287 pub a: u64,
288 /// Second value in whole microseconds (table above).
289 pub b: u64,
290 /// The starving track when `track_valid == 1`, else 0.
291 pub track: u32,
292 /// 1 when `track` is meaningful, else 0.
293 pub track_valid: u32,
294}
295
296impl Event {
297 /// Convert to the plain-data record.
298 #[must_use]
299 pub fn to_record(&self) -> EventRecord {
300 let mut r = EventRecord::default();
301 match *self {
302 Self::StartPlaying { media_27mhz, lead } => {
303 r.kind = kind::START_PLAYING;
304 r.media_27mhz = media_27mhz.ticks();
305 r.a = instant_micros(lead);
306 }
307 Self::Pause {
308 hold_at_27mhz,
309 reason,
310 depth,
311 resume_target,
312 track,
313 } => {
314 r.kind = kind::PAUSE;
315 if let Some(t) = track {
316 r.track = t;
317 r.track_valid = 1;
318 }
319 r.reason = reason.code();
320 r.media_27mhz = hold_at_27mhz.ticks();
321 r.a = instant_micros(depth);
322 r.b = instant_micros(resume_target);
323 }
324 Self::Resume { media_27mhz, lead } => {
325 r.kind = kind::RESUME;
326 r.media_27mhz = media_27mhz.ticks();
327 r.a = instant_micros(lead);
328 }
329 Self::TargetChanged { old, new } => {
330 r.kind = kind::TARGET_CHANGED;
331 r.a = instant_micros(old);
332 r.b = instant_micros(new);
333 }
334 Self::OverMax { need, max } => {
335 r.kind = kind::OVER_MAX;
336 r.a = instant_micros(need);
337 r.b = instant_micros(max);
338 }
339 Self::Rebaselined => r.kind = kind::REBASELINED,
340 Self::EventsDropped { count } => {
341 r.kind = kind::EVENTS_DROPPED;
342 r.a = 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: Duration,
384 /// Current target.
385 pub target: Duration,
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: Duration,
392 /// Longest pause (Pause to Resume).
393 pub longest_freeze: Duration,
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}
466
467#[cfg(test)]
468mod tests {
469 use super::{Event, EventQueue, Reason, State};
470 use crate::time::Clock27;
471 use core::time::Duration;
472
473 fn zero() -> Clock27 {
474 Clock27::from_27mhz(0).expect("zero is on the clock")
475 }
476
477 #[test]
478 fn every_state_has_its_stable_label() {
479 assert_eq!(State::Buffering.name(), "buffering");
480 assert_eq!(State::Playing.name(), "playing");
481 assert_eq!(State::Starved.name(), "starved");
482 }
483
484 #[test]
485 fn every_reason_has_its_stable_label() {
486 assert_eq!(Reason::Startup.name(), "startup");
487 assert_eq!(Reason::NoData.name(), "no data");
488 assert_eq!(Reason::DataArriving.name(), "data arriving");
489 assert_eq!(Reason::Discontinuity.name(), "discontinuity");
490 assert_eq!(Reason::Reprime.name(), "reprime");
491 }
492
493 #[test]
494 fn clearing_the_queue_discards_every_queued_event() {
495 let mut q = EventQueue::new();
496 q.push(Event::StartPlaying {
497 media_27mhz: zero(),
498 lead: Duration::ZERO,
499 });
500 q.push(Event::Rebaselined);
501 q.clear();
502 assert_eq!(q.poll(), None);
503 assert_eq!(q.poll(), None);
504 }
505}