Skip to main content

playout_runtime/
schedule.rs

1//! The channel schedule: an ordered list of entries (programme / ad / slate).
2//!
3//! The wire/data format here is deliberately **ours to define** — issue
4//! [#748](https://github.com/fishloa/rust-broadcast/issues/748)'s
5//! design-decision comment: SCTE 224 (ESNI) covers policy/blackout
6//! signalling, not channel assembly, and adopting it would be cargo-culting a
7//! standard that does not answer this question. There is no applicable open
8//! standard for "ordered list of sources with planned starts" to transcribe,
9//! so [`Schedule`] is a plain in-memory model, not a wire type: it has no
10//! `Parse`/`Serialize` pair, and it is deliberately minimal — enough to plan
11//! [transitions](crate::transition) and the SCTE-35 cues they imply, nothing
12//! about rights, geography, or blackout rules.
13
14use crate::error::{Error, Result};
15use alloc::string::String;
16use alloc::vec::Vec;
17
18use broadcast_common::timescale::Timescale;
19
20/// A media position: ticks on the schedule's own timescale.
21///
22/// A tick count alone does not name an instant; the timescale it is counted
23/// in travels with it, so a playhead cannot be read as one clock's ticks
24/// while it was produced on another's.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize))]
27#[non_exhaustive]
28pub struct Playhead {
29    /// Ticks since the schedule's start.
30    pub ticks: u64,
31    /// Ticks per second.
32    pub timescale: Timescale,
33}
34
35impl Playhead {
36    /// The position `ticks` into a schedule counted `timescale` ticks per second.
37    #[must_use]
38    pub fn new(ticks: u64, timescale: Timescale) -> Self {
39        Self { ticks, timescale }
40    }
41}
42
43/// What kind of content a [`ScheduleEntry`] carries.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
46#[non_exhaustive]
47pub enum EntryKind {
48    /// Regular programme content.
49    Programme,
50    /// An advertisement — a scheduled ad-break asset.
51    Ad,
52    /// Filler/slate content played when nothing else is scheduled (e.g. a
53    /// hold slide, or gap-filler between programme and ad).
54    Slate,
55}
56
57impl EntryKind {
58    /// Stable label.
59    pub fn name(&self) -> &'static str {
60        match self {
61            EntryKind::Programme => "programme",
62            EntryKind::Ad => "ad",
63            EntryKind::Slate => "slate",
64        }
65    }
66}
67broadcast_common::impl_spec_display!(EntryKind);
68
69/// Caller-supplied opaque identity for a source's codec configuration (its
70/// `avcC`/`hvcC`/`esds`, etc.), used only for equality comparison.
71///
72/// This crate never parses codec-configuration bitstreams — the "no
73/// transcoding or conforming" non-goal in issue #748's design decision — so
74/// it cannot compute this itself. The caller (whatever demuxed the source,
75/// e.g. `transmux`'s init-segment parsing) computes a stable fingerprint of
76/// its own config and passes it here; a change in fingerprint between
77/// consecutive entries is exactly what
78/// [`TransitionPlan::discontinuity`](crate::transition::TransitionPlan::discontinuity)
79/// treats as a discontinuity to signal downstream (e.g. via
80/// `broadcast_hls::mark_init_discontinuities`) — never something this crate
81/// re-encodes or conforms.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
83#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
84pub struct CodecConfigId(pub u64);
85
86/// One entry in the schedule: a source, its kind, and when it is planned to
87/// start on the shared channel timeline.
88#[derive(Debug, Clone, PartialEq, Eq)]
89#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
90pub struct ScheduleEntry {
91    /// Caller-chosen identity for the source this entry plays (e.g. an asset
92    /// id or URI) — opaque to this crate beyond equality/display.
93    pub id: String,
94    /// What kind of content this entry is.
95    pub kind: EntryKind,
96    /// The channel-timeline instant this entry is scheduled to start at, in
97    /// the caller's clock unit.
98    ///
99    /// [`Schedule`]/[`crate::transition::TransitionPlan`] themselves never
100    /// interpret this unit — the rebase arithmetic is unit-agnostic. But if
101    /// this value (via [`crate::transition::TransitionPlan::rebase`]) ends up
102    /// passed to [`crate::scte35::build_splice_insert`] to emit a SCTE-35 cue,
103    /// it **must** already be 90 kHz ticks: `splice_time()`/`break_duration()`
104    /// are fixed 90 kHz fields (ANSI/SCTE 35 2023r1 §9.8.1/§9.8.2), and
105    /// `build_splice_insert` takes a `broadcast_common::clock33::Clock33`,
106    /// which validates the 33-bit range but not the unit — a 27 MHz or
107    /// millisecond channel clock produces a technically well-formed but
108    /// silently wrong-by-a-fixed-factor cue (PLAY-W1, #1126). Convert with
109    /// `scte35_splice::time::duration_to_ticks`/`ticks_to_duration` first if
110    /// the channel clock isn't already 90 kHz.
111    pub planned_start: u64,
112    /// The PTS value the source's own first presented sample carries, in the
113    /// same clock unit as [`Self::planned_start`] (and subject to the same
114    /// 90 kHz requirement before it reaches [`crate::scte35`]). Needed to
115    /// compute the PTS-rebase offset at the transition into this entry — see
116    /// [`crate::transition`].
117    pub source_start_pts: u64,
118    /// Codec-config identity, for discontinuity detection at the transition
119    /// into this entry.
120    pub codec_config: CodecConfigId,
121}
122
123/// An ordered schedule: entries strictly increasing by `planned_start`.
124///
125/// This crate does not sort entries for you — [`Schedule::push`] rejects an
126/// out-of-order entry immediately, so a caller building a schedule sees
127/// ordering mistakes at construction time rather than as a silently
128/// misordered playout later.
129#[derive(Debug, Clone, Default, PartialEq, Eq)]
130#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
131pub struct Schedule {
132    entries: Vec<ScheduleEntry>,
133}
134
135impl Schedule {
136    /// An empty schedule.
137    #[must_use]
138    pub fn new() -> Self {
139        Schedule {
140            entries: Vec::new(),
141        }
142    }
143
144    /// Append `entry`. Errors with [`Error::OutOfOrder`] if `entry` does not
145    /// start strictly after the schedule's current last entry.
146    pub fn push(&mut self, entry: ScheduleEntry) -> Result<()> {
147        if let Some(last) = self.entries.last()
148            && entry.planned_start <= last.planned_start
149        {
150            return Err(Error::OutOfOrder {
151                prev: last.planned_start,
152                next: entry.planned_start,
153            });
154        }
155        self.entries.push(entry);
156        Ok(())
157    }
158
159    /// The entries, in schedule order.
160    #[must_use]
161    pub fn entries(&self) -> &[ScheduleEntry] {
162        &self.entries
163    }
164
165    /// Number of entries.
166    #[must_use]
167    pub fn len(&self) -> usize {
168        self.entries.len()
169    }
170
171    /// Whether the schedule has no entries.
172    #[must_use]
173    pub fn is_empty(&self) -> bool {
174        self.entries.is_empty()
175    }
176
177    /// The entry active at `pts` — the last entry whose `planned_start <=
178    /// pts` — or `None` if `pts` precedes every entry (or the schedule is
179    /// empty).
180    #[must_use]
181    pub fn active_at(&self, pts: u64) -> Option<&ScheduleEntry> {
182        self.active_index_at(pts).map(|i| &self.entries[i])
183    }
184
185    /// Index form of [`Self::active_at`], for [`crate::transition`] to also
186    /// reach the *next* entry without a second lookup.
187    pub(crate) fn active_index_at(&self, pts: u64) -> Option<usize> {
188        if self.entries.is_empty() {
189            return None;
190        }
191        let idx = self.entries.partition_point(|e| e.planned_start <= pts);
192        if idx == 0 { None } else { Some(idx - 1) }
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    fn entry(id: &str, kind: EntryKind, planned_start: u64) -> ScheduleEntry {
201        ScheduleEntry {
202            id: id.into(),
203            kind,
204            planned_start,
205            source_start_pts: 0,
206            codec_config: CodecConfigId(1),
207        }
208    }
209
210    #[test]
211    fn push_accepts_strictly_increasing_starts() {
212        let mut sched = Schedule::new();
213        sched
214            .push(entry("prog-1", EntryKind::Programme, 0))
215            .unwrap();
216        sched.push(entry("ad-1", EntryKind::Ad, 1_000)).unwrap();
217        assert_eq!(sched.len(), 2);
218        assert!(!sched.is_empty());
219    }
220
221    #[test]
222    fn push_rejects_non_increasing_start() {
223        let mut sched = Schedule::new();
224        sched
225            .push(entry("prog-1", EntryKind::Programme, 1_000))
226            .unwrap();
227        let err = sched.push(entry("ad-1", EntryKind::Ad, 1_000)).unwrap_err();
228        match err {
229            Error::OutOfOrder { prev, next } => {
230                assert_eq!(prev, 1_000);
231                assert_eq!(next, 1_000);
232            }
233            other => panic!("expected OutOfOrder, got {other:?}"),
234        }
235
236        let err = sched.push(entry("ad-2", EntryKind::Ad, 500)).unwrap_err();
237        assert!(matches!(
238            err,
239            Error::OutOfOrder {
240                prev: 1_000,
241                next: 500
242            }
243        ));
244    }
245
246    #[test]
247    fn active_at_finds_the_last_entry_starting_at_or_before_pts() {
248        let mut sched = Schedule::new();
249        sched
250            .push(entry("prog-1", EntryKind::Programme, 0))
251            .unwrap();
252        sched.push(entry("ad-1", EntryKind::Ad, 1_000)).unwrap();
253        sched
254            .push(entry("prog-2", EntryKind::Programme, 2_000))
255            .unwrap();
256
257        assert_eq!(sched.active_at(0).unwrap().id, "prog-1");
258        assert_eq!(sched.active_at(999).unwrap().id, "prog-1");
259        assert_eq!(sched.active_at(1_000).unwrap().id, "ad-1");
260        assert_eq!(sched.active_at(1_999).unwrap().id, "ad-1");
261        assert_eq!(sched.active_at(2_000).unwrap().id, "prog-2");
262        assert_eq!(sched.active_at(1_000_000).unwrap().id, "prog-2");
263    }
264
265    #[test]
266    fn active_at_before_the_first_entry_is_none() {
267        let mut sched = Schedule::new();
268        sched
269            .push(entry("prog-1", EntryKind::Programme, 1_000))
270            .unwrap();
271        assert!(sched.active_at(999).is_none());
272    }
273
274    #[test]
275    fn empty_schedule_has_no_active_entry() {
276        let sched = Schedule::new();
277        assert!(sched.is_empty());
278        assert!(sched.active_at(0).is_none());
279    }
280
281    #[test]
282    fn label_convention() {
283        assert_eq!(EntryKind::Programme.name(), "programme");
284        assert_eq!(alloc::format!("{}", EntryKind::Ad), "ad");
285        assert_eq!(EntryKind::Slate.name(), "slate");
286    }
287}