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 `silence_timeout_us`; 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_US`] 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 crate::config::{Micros, TICKS_PER_US, Ticks27};
67use crate::stall_memory::MaxHold;
68use alloc::vec::Vec;
69use broadcast_common::clock33::pcr_signed_distance;
70
71/// Most tracks tracked at once; deliveries for further tracks are ignored.
72pub const MAX_TRACKS: usize = 16;
73
74/// The track `BufferController::on_media` reports as.
75pub const DEFAULT_TRACK: u32 = 0;
76
77/// Fallback coalescing window (microseconds) for a caller that never calls
78/// `on_chunk`: calls this close are one delivery.
79pub const COALESCE_US: Micros = 1_000;
80
81/// Delivery steps a track must have shown before a start/resume is granted on
82/// its granularity (see `TrackSet::granularity_known`): the third delivery's
83/// window has closed, so two steps were measured.
84pub const LEARN_STEPS: u32 = 2;
85
86/// Wrap-safe: is `a` strictly before `b`?
87fn before(a: Ticks27, b: Ticks27) -> bool {
88    pcr_signed_distance(a, b) > 0
89}
90
91/// Delivery-instant bookkeeping for the granularity measurement.
92#[derive(Clone, Copy, Debug)]
93struct Step {
94    /// End as of the previous distinct delivery instant, and that instant.
95    prev_end: Ticks27,
96    prev_at: Micros,
97    /// End as of the current delivery instant, and that instant.
98    cur_end: Ticks27,
99    cur_at: Micros,
100    /// Chunk counter of the current delivery window.
101    cur_epoch: u64,
102    /// The window holds calls not yet folded into the memory.
103    pending: bool,
104}
105
106/// Rules deciding whether an end advance is a delivery step.
107#[derive(Clone, Copy, Debug)]
108pub(crate) struct StepRules {
109    /// Instants this far apart or more are not a cadence (the silence timeout).
110    pub(crate) max_interval_us: Micros,
111    /// Allowance of media advance over the arrival interval (`nodata_after_us`): more is a catch-up or a jump, not a cadence.
112    pub(crate) max_excess_us: Micros,
113    /// Arrival time of the chunk that ended the latest global data gap.
114    pub(crate) gap_end_at: Option<Micros>,
115    /// Number of `on_chunk` calls so far: the delivery-window counter. 0 means
116    /// the caller does not use chunk calls (time-based coalescing applies).
117    pub(crate) epoch: u64,
118}
119
120#[derive(Clone, Debug)]
121struct Track {
122    id: u32,
123    registered: bool,
124    end: Option<Ticks27>,
125    /// Arrival time of the last delivery, or of the registration while none.
126    seen_at: Micros,
127    step: Option<Step>,
128    /// Arrival time of the first delivery since the slot was (re)started.
129    first_at: Micros,
130    /// Delivery windows closed so far (deliveries seen, minus the open one).
131    windows: u32,
132    /// Largest delivery step (microseconds) with hold and decay.
133    gran: MaxHold,
134}
135
136/// The reduction result.
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub(crate) struct Effective {
139    pub(crate) end: Ticks27,
140    /// The track that bounds `end`.
141    pub(crate) limiting: u32,
142}
143
144impl Track {
145    /// Close the open delivery window (if any) and fold its step into the
146    /// granularity memory: `end after the last call - end before the first`.
147    fn commit_window(&mut self, rules: StepRules) {
148        let Some(s) = self.step.as_mut() else {
149            return;
150        };
151        if !s.pending {
152            return;
153        }
154        s.pending = false;
155        self.windows = self.windows.saturating_add(1);
156        let (prev_end, prev_at, cur_end, cur_at) = (s.prev_end, s.prev_at, s.cur_end, s.cur_at);
157        s.prev_end = cur_end;
158        s.prev_at = cur_at;
159        let advance = pcr_signed_distance(prev_end, cur_end);
160        let interval = cur_at.saturating_sub(prev_at);
161        if advance <= 0 || interval == 0 || interval >= rules.max_interval_us {
162            return;
163        }
164        if rules.gap_end_at.is_some_and(|g| g > prev_at) {
165            return;
166        }
167        let step_us = u64::try_from(advance).unwrap_or(0) / TICKS_PER_US;
168        if step_us > interval.saturating_add(rules.max_excess_us) {
169            return;
170        }
171        self.gran.observe(cur_at, step_us);
172    }
173
174    /// Fold one delivery into its delivery window; a call that does not belong
175    /// to the open window closes it first.
176    fn observe_step(&mut self, now: Micros, end: Ticks27, rules: StepRules) {
177        let same_window = self.step.as_ref().is_some_and(|s| {
178            s.cur_epoch == rules.epoch
179                && (rules.epoch > 0 || now.saturating_sub(s.cur_at) < COALESCE_US)
180        });
181        if !same_window {
182            self.commit_window(rules);
183        }
184        match self.step.as_mut() {
185            None => {
186                self.step = Some(Step {
187                    prev_end: end,
188                    prev_at: now,
189                    cur_end: end,
190                    cur_at: now,
191                    cur_epoch: rules.epoch,
192                    pending: true,
193                });
194            }
195            Some(s) => {
196                s.cur_epoch = rules.epoch;
197                s.cur_end = end;
198                s.cur_at = now;
199                s.pending = true;
200            }
201        }
202    }
203}
204
205/// Per-track ends.
206#[derive(Clone, Debug)]
207pub(crate) struct TrackSet {
208    v: Vec<Track>,
209    gran_hold_us: Micros,
210    gran_decay_us: Micros,
211    /// Arrival time of the most recent delivery on any track; the clock the
212    /// silence rule measures against. `None` until a delivery.
213    last_delivery: Option<Micros>,
214    /// Arrival time of the first delivery on any track since the set was
215    /// cleared or rebaselined: where a never-delivered track's silence clock
216    /// starts (a registration made before any media carries a clock that has
217    /// not started, so it cannot be the origin).
218    first_delivery: Option<Micros>,
219}
220
221impl TrackSet {
222    pub(crate) fn new(gran_hold_us: Micros, gran_decay_us: Micros) -> Self {
223        Self {
224            v: Vec::new(),
225            gran_hold_us,
226            gran_decay_us,
227            last_delivery: None,
228            first_delivery: None,
229        }
230    }
231
232    pub(crate) fn len(&self) -> usize {
233        self.v.len()
234    }
235
236    pub(crate) fn clear(&mut self) {
237        self.v.clear();
238        self.last_delivery = None;
239        self.first_delivery = None;
240    }
241
242    fn slot(&mut self, id: u32, now: Micros) -> Option<&mut Track> {
243        let i = match self.v.iter().position(|t| t.id == id) {
244            Some(i) => i,
245            None => {
246                if self.v.len() >= MAX_TRACKS {
247                    return None;
248                }
249                self.v.push(Track {
250                    id,
251                    registered: false,
252                    end: None,
253                    seen_at: now,
254                    step: None,
255                    first_at: now,
256                    windows: 0,
257                    gran: MaxHold::new(self.gran_hold_us, self.gran_decay_us),
258                });
259                self.v.len() - 1
260            }
261        };
262        self.v.get_mut(i)
263    }
264
265    pub(crate) fn register(&mut self, id: u32, now: Micros) {
266        if let Some(t) = self.slot(id, now) {
267            t.registered = true;
268        }
269    }
270
271    /// Forget `id` entirely (registration and end). Unknown id: no-op.
272    pub(crate) fn unregister(&mut self, id: u32) {
273        self.v.retain(|t| t.id != id);
274    }
275
276    /// Record a delivery. `None` when the track cap was hit; otherwise whether
277    /// this was the track's first delivery since the last (re)start.
278    pub(crate) fn deliver(
279        &mut self,
280        id: u32,
281        now: Micros,
282        end: Ticks27,
283        rules: StepRules,
284    ) -> Option<bool> {
285        let t = self.slot(id, now)?;
286        let first = t.end.is_none();
287        t.end = Some(end);
288        t.seen_at = t.seen_at.max(now);
289        if first {
290            t.seen_at = now;
291            t.step = None;
292            t.first_at = now;
293        }
294        t.observe_step(now, end, rules);
295        self.last_delivery = Some(self.last_delivery.map_or(now, |l| l.max(now)));
296        self.first_delivery.get_or_insert(now);
297        Some(first)
298    }
299
300    /// A chunk boundary: close every open delivery window and fold its step.
301    pub(crate) fn close_windows(&mut self, rules: StepRules) {
302        for t in &mut self.v {
303            t.commit_window(rules);
304        }
305    }
306
307    /// The clock the silence rule measures against at `now`: the latest
308    /// delivery, advanced towards `now` by at most the largest held delivery
309    /// step (the time the next delivery is *expected* after the last one). A
310    /// sparse-but-regular track (one picture every 2.3 s) is then not charged
311    /// the quantisation of its own cadence (a never-delivered track used to be
312    /// excluded only at the first delivery that landed `silence_us` after the
313    /// first one, up to a whole step late), while a global gap still moves the
314    /// clock by no more than one expected step, so it excludes nobody.
315    fn silence_clock(&self, now: Micros) -> Option<Micros> {
316        let last = self.last_delivery?;
317        let step = self.v.iter().map(|t| t.gran.value(now)).max().unwrap_or(0);
318        Some(last.max(now.min(last.saturating_add(step))))
319    }
320
321    /// Silent relative to the (expected) most recent delivery on any track.
322    fn is_silent(&self, t: &Track, silence_us: Micros, clock: Option<Micros>) -> bool {
323        // a track that never delivered has been waited for since the first
324        // delivery on any track at the earliest, whenever it was registered
325        let since = match (t.end, self.first_delivery) {
326            (None, Some(f)) => t.seen_at.max(f),
327            _ => t.seen_at,
328        };
329        clock.is_some_and(|l| l.saturating_sub(since) >= silence_us)
330    }
331
332    /// Is `id` known and not excluded by the relative-silence rule at `now`?
333    pub(crate) fn is_live(&self, id: u32, now: Micros, silence_us: Micros) -> bool {
334        let clock = self.silence_clock(now);
335        self.v
336            .iter()
337            .any(|t| t.id == id && !self.is_silent(t, silence_us, clock))
338    }
339
340    /// Largest held delivery step over the non-excluded tracks at `now`.
341    pub(crate) fn granularity_us(&self, now: Micros, silence_us: Micros) -> Micros {
342        let clock = self.silence_clock(now);
343        self.v
344            .iter()
345            .filter(|t| !self.is_silent(t, silence_us, clock))
346            .map(|t| t.gran.value(now))
347            .max()
348            .unwrap_or(0)
349    }
350
351    /// Has every non-excluded, delivering track shown enough deliveries for its
352    /// granularity to be known ([`LEARN_STEPS`] closed steps), or been
353    /// delivering for `max_wait_us` (so a slow or one-shot track never blocks
354    /// forever)? A start before this would be granted blind to the cadence.
355    pub(crate) fn granularity_known(
356        &self,
357        now: Micros,
358        silence_us: Micros,
359        max_wait_us: Micros,
360    ) -> bool {
361        let clock = self.silence_clock(now);
362        self.v
363            .iter()
364            .filter(|t| t.end.is_some() && !self.is_silent(t, silence_us, clock))
365            .all(|t| t.windows > LEARN_STEPS || now.saturating_sub(t.first_at) >= max_wait_us)
366    }
367
368    /// Forget every end (a discontinuity); registrations survive and wait
369    /// again from `now`.
370    pub(crate) fn rebaseline(&mut self, now: Micros) {
371        self.v.retain(|t| t.registered);
372        self.last_delivery = None;
373        self.first_delivery = None;
374        for t in &mut self.v {
375            t.end = None;
376            t.step = None;
377            t.seen_at = now;
378        }
379    }
380
381    /// Earliest end over the non-excluded tracks (see the module docs for the
382    /// relative-silence rule). With `pending_blocks`, `None` while a
383    /// non-excluded track has no end; without it such a track is skipped (the
384    /// registered-but-silent rule gates only a start or resume, never the
385    /// starvation check while playing).
386    pub(crate) fn effective(
387        &self,
388        now: Micros,
389        silence_us: Micros,
390        pending_blocks: bool,
391    ) -> Option<Effective> {
392        let clock = self.silence_clock(now);
393        let mut min: Option<Effective> = None;
394        for t in self
395            .v
396            .iter()
397            .filter(|t| !self.is_silent(t, silence_us, clock))
398        {
399            let Some(end) = t.end else {
400                if pending_blocks {
401                    return None;
402                }
403                continue;
404            };
405            if min.is_none_or(|m| before(end, m.end)) {
406                min = Some(Effective {
407                    end,
408                    limiting: t.id,
409                });
410            }
411        }
412        min
413    }
414}