Skip to main content

buffering_runtime/
tracks.rs

1//! Per-track media ends and the effective (minimum) media end.
2//!
3//! A TS mux sends video well ahead of its play time and audio close to real
4//! time, so the amount of media that can actually be played is bounded by the
5//! *least advanced* rendered track, not by video alone. The set keeps the end
6//! of the last delivered sample per track and reduces them to one position:
7//!
8//! * a track becomes **active** on its first delivery;
9//! * a track announced with [`BufferController::register_track`](crate::BufferController::register_track) that has not delivered yet
10//!   **blocks** a start or resume (no effective end) until it delivers or has
11//!   been silent for `track_silence_timeout`; while playing it is skipped, so the
12//!   starvation check keeps running over the tracks that have delivered;
13//! * a track removed with
14//!   [`BufferController::unregister_track`](crate::BufferController::unregister_track)
15//!   (a replaced or dead track) leaves the reduction at once; if no track is
16//!   left there is no effective end until one delivers;
17//! * a track is **excluded** when it is silent *relative to the other tracks*:
18//!   its own last delivery (or, if it never delivered, its registration) lies
19//!   at least `silence_timeout_us` before the most recent delivery on ANY
20//!   track. A dead track therefore cannot starve playback while the others
21//!   keep delivering, but the clock is the arrival time of the latest delivery,
22//!   not wall time, advanced towards now by at most the largest held delivery
23//!   step (the time the next delivery is expected; a source delivering every
24//!   2.3 s is not charged the quantisation of its own cadence): when nothing at
25//!   all is delivered (a global stall such as a reconnect or server restart)
26//!   nobody becomes excluded, however long the gap, and the stall is not
27//!   mistaken for the tracks being dead. Before any
28//!   delivery (or after a rebaseline) nothing is excluded either;
29//! * the effective end is the earliest end over the non-excluded tracks, so a
30//!   global stall keeps the MIN of the tracks' last ends (there is no
31//!   "all silent" fallback: the most recently delivering track is never
32//!   excluded).
33//!
34//! **Delivery granularity.** Each track also remembers the largest *step* its
35//! end advanced between two distinct delivery instants, as a max-hold with a hold and a
36//! linear decay (the stall-memory max-hold, bounded memory: a few scalars per track,
37//! at most [`MAX_TRACKS`] tracks). A step counts only when it looks like a
38//! delivery cadence: it advanced forward, the instants are less than the
39//! silence timeout apart, it is no more than the arrival interval plus
40//! `nodata_after_us` (a catch-up burst or a forward jump is not a cadence;
41//! the PDV and the stall memory cover those), and the
42//! caller reports no global data gap (a chunk gap of `nodata_after_us` or more)
43//! inside the interval (a gap is PDV, which the stall memory already covers).
44//! The policy keeps the target at least the largest held step plus the margin.
45//!
46//! **Delivery instant.** A track's delivery instant is the *chunk boundary*:
47//! all [`on_track_media`](crate::BufferController::on_track_media) calls for a
48//! track between two [`on_chunk`](crate::BufferController::on_chunk) calls are
49//! ONE delivery, and the step is `end after the last call - end before the
50//! first call`. A caller that never calls `on_chunk` gets the fallback: calls
51//! less than [`COALESCE`] apart are one delivery. So a caller reporting one
52//! end per delivered chunk and a caller reporting one per demuxed sample (a
53//! 0.3 s MP2 PES as 12 frames of 24 ms) produce the same floor. The step is
54//! folded into the memory when the window closes (at the next `on_chunk`, or at
55//! the next call that does not belong to it), so the floor rises at the chunk
56//! boundary that ends the delivery, with identical events however the calls
57//! were split.
58//!
59//! **Start gate.** `TrackSet::granularity_known` tells the controller whether
60//! every delivering track has shown [`LEARN_STEPS`] closed steps (or has been
61//! delivering for a bounded wait), so a start/resume is never granted before the
62//! floor could have been learnt.
63//!
64//! All position comparisons are wrap-safe (`broadcast_common::clock33`).
65
66use core::time::Duration;
67
68use crate::config::TICKS_PER_US;
69use crate::stall_memory::MaxHold;
70use crate::time::{
71    Clock27, duration_add, duration_between, instant_micros, micros_as_duration, window_micros,
72};
73use alloc::vec::Vec;
74use broadcast_common::clock33::pcr_signed_distance;
75
76/// Most tracks tracked at once; deliveries for further tracks are ignored.
77pub const MAX_TRACKS: usize = 16;
78
79/// The track `BufferController::on_media` reports as.
80pub const DEFAULT_TRACK: u32 = 0;
81
82/// Fallback coalescing window (microseconds) for a caller that never calls
83/// `on_chunk`: calls this close are one delivery.
84pub const COALESCE: Duration = Duration::from_millis(1);
85
86/// Delivery steps a track must have shown before a start/resume is granted on
87/// its granularity (see `TrackSet::granularity_known`): the third delivery's
88/// window has closed, so two steps were measured.
89pub const LEARN_STEPS: u32 = 2;
90
91/// Wrap-safe: is `a` strictly before `b`?
92fn before(a: Clock27, b: Clock27) -> bool {
93    pcr_signed_distance(a.ticks(), b.ticks()) > 0
94}
95
96/// Delivery-instant bookkeeping for the granularity measurement.
97#[derive(Clone, Copy, Debug)]
98struct Step {
99    /// End as of the previous distinct delivery instant, and that instant.
100    prev_end: Clock27,
101    prev_at: Duration,
102    /// End as of the current delivery instant, and that instant.
103    cur_end: Clock27,
104    cur_at: Duration,
105    /// Chunk counter of the current delivery window.
106    cur_epoch: u64,
107    /// The window holds calls not yet folded into the memory.
108    pending: bool,
109}
110
111/// Rules deciding whether an end advance is a delivery step.
112#[derive(Clone, Copy, Debug)]
113pub(crate) struct StepRules {
114    /// Instants this far apart or more are not a cadence (the silence timeout).
115    pub(crate) max_interval: Duration,
116    /// Allowance of media advance over the arrival interval (`nodata_after`): more is a catch-up or a jump, not a cadence.
117    pub(crate) max_excess: Duration,
118    /// Arrival time of the chunk that ended the latest global data gap.
119    pub(crate) gap_end_at: Option<Duration>,
120    /// Number of `on_chunk` calls so far: the delivery-window counter. 0 means
121    /// the caller does not use chunk calls (time-based coalescing applies).
122    pub(crate) epoch: u64,
123}
124
125#[derive(Clone, Debug)]
126struct Track {
127    id: u32,
128    registered: bool,
129    end: Option<Clock27>,
130    /// Arrival time of the last delivery, or of the registration while none.
131    seen_at: Duration,
132    step: Option<Step>,
133    /// Arrival time of the first delivery since the slot was (re)started.
134    first_at: Duration,
135    /// Delivery windows closed so far (deliveries seen, minus the open one).
136    windows: u32,
137    /// Largest delivery step (microseconds) with hold and decay.
138    gran: MaxHold,
139}
140
141/// The reduction result.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub(crate) struct Effective {
144    pub(crate) end: Clock27,
145    /// The track that bounds `end`.
146    pub(crate) limiting: u32,
147}
148
149impl Track {
150    /// Close the open delivery window (if any) and fold its step into the
151    /// granularity memory: `end after the last call - end before the first`.
152    fn commit_window(&mut self, rules: StepRules) {
153        let Some(s) = self.step.as_mut() else {
154            return;
155        };
156        if !s.pending {
157            return;
158        }
159        s.pending = false;
160        self.windows = self.windows.saturating_add(1);
161        let (prev_end, prev_at, cur_end, cur_at) = (s.prev_end, s.prev_at, s.cur_end, s.cur_at);
162        s.prev_end = cur_end;
163        s.prev_at = cur_at;
164        let advance = pcr_signed_distance(prev_end.ticks(), cur_end.ticks());
165        let interval = duration_between(prev_at, cur_at);
166        if advance <= 0 || interval.is_zero() || interval >= rules.max_interval {
167            return;
168        }
169        if rules.gap_end_at.is_some_and(|g| g > prev_at) {
170            return;
171        }
172        let step = u64::try_from(advance).unwrap_or(0) / TICKS_PER_US;
173        if step > instant_micros(interval).saturating_add(instant_micros(rules.max_excess)) {
174            return;
175        }
176        self.gran.observe(instant_micros(cur_at), step);
177    }
178
179    /// Fold one delivery into its delivery window; a call that does not belong
180    /// to the open window closes it first.
181    fn observe_step(&mut self, now: Duration, end: Clock27, rules: StepRules) {
182        let same_window = self.step.as_ref().is_some_and(|s| {
183            s.cur_epoch == rules.epoch
184                && (rules.epoch > 0 || duration_between(s.cur_at, now) < COALESCE)
185        });
186        if !same_window {
187            self.commit_window(rules);
188        }
189        match self.step.as_mut() {
190            None => {
191                self.step = Some(Step {
192                    prev_end: end,
193                    prev_at: now,
194                    cur_end: end,
195                    cur_at: now,
196                    cur_epoch: rules.epoch,
197                    pending: true,
198                });
199            }
200            Some(s) => {
201                s.cur_epoch = rules.epoch;
202                s.cur_end = end;
203                s.cur_at = now;
204                s.pending = true;
205            }
206        }
207    }
208}
209
210/// Per-track ends.
211#[derive(Clone, Debug)]
212pub(crate) struct TrackSet {
213    v: Vec<Track>,
214    gran_hold: Duration,
215    gran_decay: Duration,
216    /// Arrival time of the most recent delivery on any track; the clock the
217    /// silence rule measures against. `None` until a delivery.
218    last_delivery: Option<Duration>,
219    /// Arrival time of the first delivery on any track since the set was
220    /// cleared or rebaselined: where a never-delivered track's silence clock
221    /// starts (a registration made before any media carries a clock that has
222    /// not started, so it cannot be the origin).
223    first_delivery: Option<Duration>,
224}
225
226impl TrackSet {
227    pub(crate) fn new(gran_hold: Duration, gran_decay: Duration) -> Self {
228        Self {
229            v: Vec::new(),
230            gran_hold,
231            gran_decay,
232            last_delivery: None,
233            first_delivery: None,
234        }
235    }
236
237    pub(crate) fn len(&self) -> usize {
238        self.v.len()
239    }
240
241    pub(crate) fn clear(&mut self) {
242        self.v.clear();
243        self.last_delivery = None;
244        self.first_delivery = None;
245    }
246
247    fn slot(&mut self, id: u32, now: Duration) -> Option<&mut Track> {
248        let i = match self.v.iter().position(|t| t.id == id) {
249            Some(i) => i,
250            None => {
251                if self.v.len() >= MAX_TRACKS {
252                    return None;
253                }
254                self.v.push(Track {
255                    id,
256                    registered: false,
257                    end: None,
258                    seen_at: now,
259                    step: None,
260                    first_at: now,
261                    windows: 0,
262                    gran: MaxHold::new(
263                        window_micros(self.gran_hold),
264                        window_micros(self.gran_decay),
265                    ),
266                });
267                self.v.len() - 1
268            }
269        };
270        self.v.get_mut(i)
271    }
272
273    pub(crate) fn register(&mut self, id: u32, now: Duration) {
274        if let Some(t) = self.slot(id, now) {
275            t.registered = true;
276        }
277    }
278
279    /// Forget `id` entirely (registration and end). Unknown id: no-op.
280    pub(crate) fn unregister(&mut self, id: u32) {
281        self.v.retain(|t| t.id != id);
282    }
283
284    /// Record a delivery. `None` when the track cap was hit; otherwise whether
285    /// this was the track's first delivery since the last (re)start.
286    pub(crate) fn deliver(
287        &mut self,
288        id: u32,
289        now: Duration,
290        end: Clock27,
291        rules: StepRules,
292    ) -> Option<bool> {
293        let t = self.slot(id, now)?;
294        let first = t.end.is_none();
295        t.end = Some(end);
296        t.seen_at = t.seen_at.max(now);
297        if first {
298            t.seen_at = now;
299            t.step = None;
300            t.first_at = now;
301        }
302        t.observe_step(now, end, rules);
303        self.last_delivery = Some(self.last_delivery.map_or(now, |l| l.max(now)));
304        self.first_delivery.get_or_insert(now);
305        Some(first)
306    }
307
308    /// A chunk boundary: close every open delivery window and fold its step.
309    pub(crate) fn close_windows(&mut self, rules: StepRules) {
310        for t in &mut self.v {
311            t.commit_window(rules);
312        }
313    }
314
315    /// The clock the silence rule measures against at `now`: the latest
316    /// delivery, advanced towards `now` by at most the largest held delivery
317    /// step (the time the next delivery is *expected* after the last one). A
318    /// sparse-but-regular track (one picture every 2.3 s) is then not charged
319    /// the quantisation of its own cadence (a never-delivered track used to be
320    /// excluded only at the first delivery that landed `silence_us` after the
321    /// first one, up to a whole step late), while a global gap still moves the
322    /// clock by no more than one expected step, so it excludes nobody.
323    fn silence_clock(&self, now: Duration) -> Option<Duration> {
324        let last = self.last_delivery?;
325        let step = self
326            .v
327            .iter()
328            .map(|t| t.gran.value(instant_micros(now)))
329            .max()
330            .unwrap_or(0);
331        Some(last.max(now.min(duration_add(last, micros_as_duration(step)))))
332    }
333
334    /// Silent relative to the (expected) most recent delivery on any track.
335    fn is_silent(&self, t: &Track, silence: &Duration, clock: Option<Duration>) -> bool {
336        // a track that never delivered has been waited for since the first
337        // delivery on any track at the earliest, whenever it was registered
338        let since = match (t.end, self.first_delivery) {
339            (None, Some(f)) => t.seen_at.max(f),
340            _ => t.seen_at,
341        };
342        clock.is_some_and(|l| duration_between(since, l) >= *silence)
343    }
344
345    /// Is `id` known and not excluded by the relative-silence rule at `now`?
346    pub(crate) fn is_live(&self, id: u32, now: Duration, silence: Duration) -> bool {
347        let clock = self.silence_clock(now);
348        self.v
349            .iter()
350            .any(|t| t.id == id && !self.is_silent(t, &silence, clock))
351    }
352
353    /// Largest held delivery step over the non-excluded tracks at `now`.
354    pub(crate) fn granularity(&self, now: Duration, silence: Duration) -> Duration {
355        let clock = self.silence_clock(now);
356        self.v
357            .iter()
358            .filter(|t| !self.is_silent(t, &silence, clock))
359            .map(|t| micros_as_duration(t.gran.value(instant_micros(now))))
360            .max()
361            .unwrap_or(Duration::ZERO)
362    }
363
364    /// Has every non-excluded, delivering track shown enough deliveries for its
365    /// granularity to be known ([`LEARN_STEPS`] closed steps), or been
366    /// delivering for `max_wait_us` (so a slow or one-shot track never blocks
367    /// forever)? A start before this would be granted blind to the cadence.
368    pub(crate) fn granularity_known(
369        &self,
370        now: Duration,
371        silence: Duration,
372        max_wait: Duration,
373    ) -> bool {
374        let clock = self.silence_clock(now);
375        self.v
376            .iter()
377            .filter(|t| t.end.is_some() && !self.is_silent(t, &silence, clock))
378            .all(|t| t.windows > LEARN_STEPS || duration_between(t.first_at, now) >= max_wait)
379    }
380
381    /// Forget every end (a discontinuity); registrations survive and wait
382    /// again from `now`.
383    pub(crate) fn rebaseline(&mut self, now: Duration) {
384        self.v.retain(|t| t.registered);
385        self.last_delivery = None;
386        self.first_delivery = None;
387        for t in &mut self.v {
388            t.end = None;
389            t.step = None;
390            t.seen_at = now;
391        }
392    }
393
394    /// Earliest end over the non-excluded tracks (see the module docs for the
395    /// relative-silence rule). With `pending_blocks`, `None` while a
396    /// non-excluded track has no end; without it such a track is skipped (the
397    /// registered-but-silent rule gates only a start or resume, never the
398    /// starvation check while playing).
399    pub(crate) fn effective(
400        &self,
401        now: Duration,
402        silence: Duration,
403        pending_blocks: bool,
404    ) -> Option<Effective> {
405        let clock = self.silence_clock(now);
406        let mut min: Option<Effective> = None;
407        for t in self
408            .v
409            .iter()
410            .filter(|t| !self.is_silent(t, &silence, clock))
411        {
412            let Some(end) = t.end else {
413                if pending_blocks {
414                    return None;
415                }
416                continue;
417            };
418            if min.is_none_or(|m| before(end, m.end)) {
419                min = Some(Effective {
420                    end,
421                    limiting: t.id,
422                });
423            }
424        }
425        min
426    }
427}