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