Skip to main content

buffering_runtime/
input_log.rs

1//! Input log: record what a host fed a [`BufferController`] and replay it offline.
2//!
3//! A log is plain text, one row per call, header [`Input::CSV_HEADER`]
4//! (`kind,now_us,a,b`). The first rows after the header describe the controller
5//! (`config` rows, one per [`ControllerConfig`] field, and a `seed` row when a
6//! stall-memory seed was used); the remaining rows are the [`Input`]s in call
7//! order:
8//!
9//! | kind | `a` | `b` |
10//! |---|---|---|
11//! | `chunk` | bytes | last PCR, 27 MHz, or empty |
12//! | `media` | track key | media end, 27 MHz |
13//! | `tick` | `1` with a position, `0` without | playback position, 27 MHz, or empty |
14//! | `register`, `unregister` | track key | empty |
15//! | `hint` | [`Hint::name`] token | empty |
16//! | `config` (`now_us` 0) | [`ConfigKey::name`] token | value (`true`/`false` for flags) |
17//! | `seed` (`now_us` 0) | peak, microseconds | age, microseconds |
18//!
19//! [`InputLog::replay`] feeds the inputs through one fresh controller built from the recorded
20//! configuration, so the same log gives the same decisions on any host. Logs recorded before
21//! `config` rows existed parse with [`InputLog::parse_with_config`].
22
23use alloc::string::{String, ToString};
24use alloc::vec::Vec;
25use core::fmt::Write;
26
27use crate::config::{ControllerConfig, Micros, Ticks27};
28use crate::controller::BufferController;
29use crate::error::Error;
30use crate::events::{Event, Hint};
31use crate::stall_memory::StallMemorySnapshot;
32
33const KIND_CHUNK: &str = "chunk";
34const KIND_MEDIA: &str = "media";
35const KIND_TICK: &str = "tick";
36const KIND_HINT: &str = "hint";
37const KIND_REGISTER: &str = "register";
38const KIND_UNREGISTER: &str = "unregister";
39const KIND_CONFIG: &str = "config";
40const KIND_SEED: &str = "seed";
41const HAS_POSITION: &str = "1";
42const NO_POSITION: &str = "0";
43const HINT_CODE_FIRST: u32 = 1;
44const CONFIG_NOW_US: Micros = 0;
45
46/// One call a host made into a [`BufferController`].
47///
48/// Times are the host's monotonic microseconds; positions and media ends are 27 MHz ticks.
49#[non_exhaustive]
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize))]
52pub enum Input {
53    /// [`BufferController::on_chunk`]: bytes arrived.
54    Chunk {
55        /// Arrival time.
56        now_us: Micros,
57        /// Chunk length.
58        bytes: u32,
59        /// Last PCR of the chunk, 27 MHz.
60        pcr: Option<Ticks27>,
61    },
62    /// [`BufferController::on_track_media`]: a track's buffered media now ends at `end`.
63    TrackMedia {
64        /// Report time.
65        now_us: Micros,
66        /// Track key.
67        track: u32,
68        /// Media end, 27 MHz.
69        end: Ticks27,
70    },
71    /// [`BufferController::on_tick`]: the renderer's playback position.
72    Tick {
73        /// Tick time.
74        now_us: Micros,
75        /// Playback position, 27 MHz.
76        pts: Option<Ticks27>,
77    },
78    /// [`BufferController::register_track`].
79    Register {
80        /// Time of the call.
81        now_us: Micros,
82        /// Track key.
83        track: u32,
84    },
85    /// [`BufferController::unregister_track`].
86    Unregister {
87        /// Time of the call.
88        now_us: Micros,
89        /// Track key.
90        track: u32,
91    },
92    /// [`BufferController::on_hint`].
93    Hint {
94        /// Hint time.
95        now_us: Micros,
96        /// The hint.
97        hint: Hint,
98    },
99}
100
101impl Input {
102    /// Header row of a text log.
103    pub const CSV_HEADER: &'static str = "kind,now_us,a,b";
104
105    /// Stable label.
106    #[must_use]
107    pub fn name(&self) -> &'static str {
108        match self {
109            Self::Chunk { .. } => KIND_CHUNK,
110            Self::TrackMedia { .. } => KIND_MEDIA,
111            Self::Tick { .. } => KIND_TICK,
112            Self::Register { .. } => KIND_REGISTER,
113            Self::Unregister { .. } => KIND_UNREGISTER,
114            Self::Hint { .. } => KIND_HINT,
115        }
116    }
117
118    /// The time of the call.
119    #[must_use]
120    pub fn now_us(&self) -> Micros {
121        match self {
122            Self::Chunk { now_us, .. }
123            | Self::TrackMedia { now_us, .. }
124            | Self::Tick { now_us, .. }
125            | Self::Register { now_us, .. }
126            | Self::Unregister { now_us, .. }
127            | Self::Hint { now_us, .. } => *now_us,
128        }
129    }
130
131    /// The same input with its time moved `origin_us` earlier (saturating).
132    #[must_use]
133    pub fn rebased(self, origin_us: Micros) -> Self {
134        let mut out = self;
135        let (Self::Chunk { now_us, .. }
136        | Self::TrackMedia { now_us, .. }
137        | Self::Tick { now_us, .. }
138        | Self::Register { now_us, .. }
139        | Self::Unregister { now_us, .. }
140        | Self::Hint { now_us, .. }) = &mut out;
141        *now_us = now_us.saturating_sub(origin_us);
142        out
143    }
144
145    /// Makes the call this input records on `controller`. Replay is a loop over this.
146    pub fn apply(&self, controller: &mut BufferController) {
147        match *self {
148            Self::Chunk { now_us, bytes, pcr } => controller.on_chunk(now_us, bytes, pcr),
149            Self::TrackMedia { now_us, track, end } => {
150                controller.on_track_media(now_us, track, end);
151            }
152            Self::Tick { now_us, pts } => controller.on_tick(now_us, pts),
153            Self::Register { track, .. } => controller.register_track(track),
154            Self::Unregister { track, .. } => controller.unregister_track(track),
155            Self::Hint { now_us, hint } => controller.on_hint(now_us, hint),
156        }
157    }
158
159    /// Writes one row (columns of [`Input::CSV_HEADER`]) without a trailing newline.
160    ///
161    /// # Errors
162    /// Whatever `out` reports.
163    pub fn write_row(&self, out: &mut impl Write) -> core::fmt::Result {
164        match self {
165            Self::Chunk { now_us, bytes, pcr } => {
166                write!(out, "{KIND_CHUNK},{now_us},{bytes},")?;
167                write_opt(out, *pcr)
168            }
169            Self::TrackMedia { now_us, track, end } => {
170                write!(out, "{KIND_MEDIA},{now_us},{track},{end}")
171            }
172            Self::Tick { now_us, pts } => {
173                let has = if pts.is_some() {
174                    HAS_POSITION
175                } else {
176                    NO_POSITION
177                };
178                write!(out, "{KIND_TICK},{now_us},{has},")?;
179                write_opt(out, *pts)
180            }
181            Self::Register { now_us, track } => write!(out, "{KIND_REGISTER},{now_us},{track},"),
182            Self::Unregister { now_us, track } => {
183                write!(out, "{KIND_UNREGISTER},{now_us},{track},")
184            }
185            Self::Hint { now_us, hint } => write!(out, "{KIND_HINT},{now_us},{},", hint.name()),
186        }
187    }
188
189    /// Parses one input row; the inverse of [`Input::write_row`]. A missing trailing column is
190    /// read as empty.
191    ///
192    /// # Errors
193    /// [`InputLogError`] naming the row and the reason; `config`, `seed` and header rows are not
194    /// inputs.
195    pub fn parse_row(line: &str) -> Result<Self, InputLogError> {
196        let row = Row::split(line)?;
197        let now_us = row.number("now_us", row.now)?;
198        match row.kind {
199            KIND_CHUNK => Ok(Self::Chunk {
200                now_us,
201                bytes: row.number("bytes", row.a)?,
202                pcr: row.optional("pcr", row.b)?,
203            }),
204            KIND_MEDIA => Ok(Self::TrackMedia {
205                now_us,
206                track: row.number("track", row.a)?,
207                end: row.number("end", row.b)?,
208            }),
209            KIND_TICK => {
210                let pts = if row.a == HAS_POSITION {
211                    Some(row.number("pts", row.b)?)
212                } else if row.a == NO_POSITION {
213                    None
214                } else {
215                    return Err(row.fail(Reason::BadNumber {
216                        field: "has_position",
217                    }));
218                };
219                Ok(Self::Tick { now_us, pts })
220            }
221            KIND_REGISTER => Ok(Self::Register {
222                now_us,
223                track: row.number("track", row.a)?,
224            }),
225            KIND_UNREGISTER => Ok(Self::Unregister {
226                now_us,
227                track: row.number("track", row.a)?,
228            }),
229            KIND_HINT => {
230                let hint = (HINT_CODE_FIRST..)
231                    .map_while(Hint::from_code)
232                    .find(|h| h.name() == row.a)
233                    .ok_or_else(|| row.fail(Reason::UnknownHint))?;
234                Ok(Self::Hint { now_us, hint })
235            }
236            _ => Err(row.fail(Reason::UnknownKind)),
237        }
238    }
239}
240broadcast_common::impl_spec_display!(Input);
241
242fn write_opt(out: &mut impl Write, v: Option<u64>) -> core::fmt::Result {
243    match v {
244        Some(v) => write!(out, "{v}"),
245        None => Ok(()),
246    }
247}
248
249struct Row<'a> {
250    line: &'a str,
251    kind: &'a str,
252    now: &'a str,
253    a: &'a str,
254    b: &'a str,
255}
256
257impl<'a> Row<'a> {
258    fn split(line: &'a str) -> Result<Self, InputLogError> {
259        let mut f = line.trim_end_matches('\r').split(',');
260        let row = Self {
261            line,
262            kind: f.next().unwrap_or(""),
263            now: f.next().unwrap_or(""),
264            a: f.next().unwrap_or(""),
265            b: f.next().unwrap_or(""),
266        };
267        if row.now.is_empty() {
268            return Err(row.fail(Reason::MissingField { field: "now_us" }));
269        }
270        Ok(row)
271    }
272
273    fn fail(&self, reason: Reason) -> InputLogError {
274        InputLogError {
275            line: self.line.to_string(),
276            reason,
277        }
278    }
279
280    fn number<T: core::str::FromStr>(
281        &self,
282        field: &'static str,
283        v: &str,
284    ) -> Result<T, InputLogError> {
285        if v.is_empty() {
286            return Err(self.fail(Reason::MissingField { field }));
287        }
288        v.parse()
289            .map_err(|_| self.fail(Reason::BadNumber { field }))
290    }
291
292    fn optional<T: core::str::FromStr>(
293        &self,
294        field: &'static str,
295        v: &str,
296    ) -> Result<Option<T>, InputLogError> {
297        if v.is_empty() {
298            return Ok(None);
299        }
300        v.parse()
301            .map(Some)
302            .map_err(|_| self.fail(Reason::BadNumber { field }))
303    }
304}
305
306/// Why a log row or log failed to parse or replay.
307#[non_exhaustive]
308#[derive(Clone, Copy, Debug, PartialEq, Eq)]
309pub enum Reason {
310    /// The first line is not [`Input::CSV_HEADER`].
311    BadHeader,
312    /// The row kind is not one of the log's kinds.
313    UnknownKind,
314    /// A required column is empty or absent.
315    MissingField {
316        /// The column.
317        field: &'static str,
318    },
319    /// A column is not a number of the required type.
320    BadNumber {
321        /// The column.
322        field: &'static str,
323    },
324    /// The `hint` token names no [`Hint`].
325    UnknownHint,
326    /// The `config` token names no [`ConfigKey`].
327    UnknownConfigKey,
328    /// The recorded configuration fails [`ControllerConfig::validate`].
329    InvalidConfig(Error),
330    /// The log has no `config` rows; use [`InputLog::parse_with_config`].
331    NoConfig,
332}
333
334impl Reason {
335    /// Stable label.
336    #[must_use]
337    pub fn name(&self) -> &'static str {
338        match self {
339            Self::BadHeader => "bad header",
340            Self::UnknownKind => "unknown kind",
341            Self::MissingField { .. } => "missing field",
342            Self::BadNumber { .. } => "bad number",
343            Self::UnknownHint => "unknown hint",
344            Self::UnknownConfigKey => "unknown config key",
345            Self::InvalidConfig(_) => "invalid config",
346            Self::NoConfig => "no config",
347        }
348    }
349}
350broadcast_common::impl_spec_display!(Reason);
351
352/// A log row that could not be read.
353#[non_exhaustive]
354#[derive(Clone, Debug, PartialEq, Eq)]
355pub struct InputLogError {
356    /// The offending line.
357    pub line: String,
358    /// Why it was rejected.
359    pub reason: Reason,
360}
361
362impl core::fmt::Display for InputLogError {
363    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
364        write!(f, "{}", self.reason)?;
365        match self.reason {
366            Reason::MissingField { field } | Reason::BadNumber { field } => {
367                write!(f, " ({field})")?;
368            }
369            Reason::InvalidConfig(e) => write!(f, " ({e})")?,
370            _ => {}
371        }
372        write!(f, " in row {:?}", self.line)
373    }
374}
375
376impl core::error::Error for InputLogError {}
377
378macro_rules! config_keys {
379    ($($variant:ident => $token:literal, $($path:ident).+ : $ty:ty;)*) => {
380        /// A [`ControllerConfig`] field as it appears in a `config` row.
381        #[non_exhaustive]
382        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
383        pub enum ConfigKey {
384            $(
385                #[doc = concat!("`", stringify!($($path).+), "`.")]
386                $variant,
387            )*
388        }
389
390        impl ConfigKey {
391            /// Every key, in the order a log writes them.
392            pub const ALL: &'static [ConfigKey] = &[$(ConfigKey::$variant),*];
393
394            /// The token written in column `a` of a `config` row.
395            #[must_use]
396            pub fn name(&self) -> &'static str {
397                match self {
398                    $(Self::$variant => $token,)*
399                }
400            }
401
402            /// The key with this token.
403            #[must_use]
404            pub fn from_name(token: &str) -> Option<Self> {
405                match token {
406                    $($token => Some(Self::$variant),)*
407                    _ => None,
408                }
409            }
410
411            fn write_value(&self, cfg: &ControllerConfig, out: &mut impl Write) -> core::fmt::Result {
412                match self {
413                    $(Self::$variant => write!(out, "{}", cfg.$($path).+),)*
414                }
415            }
416
417            fn set(&self, cfg: &mut ControllerConfig, value: &str) -> Option<()> {
418                match self {
419                    $(Self::$variant => cfg.$($path).+ = value.parse::<$ty>().ok()?,)*
420                }
421                Some(())
422            }
423        }
424    };
425}
426
427config_keys! {
428    JitterMinWindow => "jitter.min_window_us", jitter.min_window_us: u64;
429    JitterInterval => "jitter.interval_us", jitter.interval_us: u64;
430    JitterOutlier => "jitter.outlier_us", jitter.outlier_us: u64;
431    JitterBucket => "jitter.bucket_us", jitter.bucket_us: u32;
432    JitterBuckets => "jitter.buckets", jitter.buckets: u16;
433    JitterForget => "jitter.forget_q15", jitter.forget_q15: u16;
434    JitterQuantile => "jitter.quantile_permille", jitter.quantile_permille: u16;
435    JitterHold => "jitter.hold_us", jitter.hold_us: u64;
436    JitterDecay => "jitter.decay_us", jitter.decay_us: u64;
437    JitterMaxSamples => "jitter.max_samples", jitter.max_samples: u16;
438    JitterDiscontinuity => "jitter.discontinuity_us", jitter.discontinuity_us: u64;
439    PolicyMin => "policy.min_us", policy.min_us: u64;
440    PolicyInitial => "policy.initial_us", policy.initial_us: u64;
441    PolicyMax => "policy.max_us", policy.max_us: u64;
442    PolicyK1 => "policy.k1_q8", policy.k1_q8: u16;
443    PolicyMargin => "policy.margin_us", policy.margin_us: u64;
444    PolicyK2 => "policy.k2_q8", policy.k2_q8: u16;
445    PolicyAfterRebuffer => "policy.after_rebuffer_q8", policy.after_rebuffer_q8: u16;
446    PolicyMaxStepDown => "policy.max_step_down_us_per_s", policy.max_step_down_us_per_s: u32;
447    PolicyReprimeFloor => "policy.reprime_floor_us", policy.reprime_floor_us: u64;
448    PolicyReprimeHold => "policy.reprime_hold_us", policy.reprime_hold_us: u64;
449    StarveThreshold => "starve_threshold_us", starve_threshold_us: u64;
450    NodataAfter => "nodata_after_us", nodata_after_us: u64;
451    TrackSilenceTimeout => "track_silence_timeout_us", track_silence_timeout_us: u64;
452    TrackGranularity => "track_granularity", track_granularity: bool;
453    GranularityHold => "granularity_hold_us", granularity_hold_us: u64;
454    GranularityDecay => "granularity_decay_us", granularity_decay_us: u64;
455}
456broadcast_common::impl_spec_display!(ConfigKey);
457
458/// A complete, self-describing input log: the controller configuration, the optional stall-memory
459/// seed, and the inputs in call order.
460#[non_exhaustive]
461#[derive(Clone, Debug, PartialEq, Eq)]
462pub struct InputLog {
463    /// Configuration the controller was built from.
464    pub config: ControllerConfig,
465    /// Stall-memory seed the controller was built with.
466    pub seed: Option<StallMemorySnapshot>,
467    /// The recorded calls, in order.
468    pub inputs: Vec<Input>,
469}
470
471impl InputLog {
472    /// A log of `inputs` for a controller built from `config` and `seed`.
473    #[must_use]
474    pub fn new(
475        config: ControllerConfig,
476        seed: Option<StallMemorySnapshot>,
477        inputs: Vec<Input>,
478    ) -> Self {
479        Self {
480            config,
481            seed,
482            inputs,
483        }
484    }
485
486    /// Writes the header, the `config` rows, the `seed` row if any, then one row per input, each
487    /// line ending in a newline.
488    ///
489    /// # Errors
490    /// Whatever `out` reports.
491    pub fn write(&self, out: &mut impl Write) -> core::fmt::Result {
492        writeln!(out, "{}", Input::CSV_HEADER)?;
493        for key in ConfigKey::ALL {
494            write!(out, "{KIND_CONFIG},{CONFIG_NOW_US},{},", key.name())?;
495            key.write_value(&self.config, out)?;
496            out.write_char('\n')?;
497        }
498        if let Some(s) = &self.seed {
499            writeln!(
500                out,
501                "{KIND_SEED},{CONFIG_NOW_US},{},{}",
502                s.peak_us, s.age_us
503            )?;
504        }
505        for input in &self.inputs {
506            input.write_row(out)?;
507            out.write_char('\n')?;
508        }
509        Ok(())
510    }
511
512    /// Parses a log written by [`InputLog::write`].
513    ///
514    /// # Errors
515    /// [`InputLogError`] for a bad row, or [`Reason::NoConfig`] when the log has no `config` rows.
516    pub fn parse(text: &str) -> Result<Self, InputLogError> {
517        let (log, had_config) = Self::parse_inner(text, ControllerConfig::DEFAULT)?;
518        if had_config {
519            Ok(log)
520        } else {
521            Err(InputLogError {
522                line: String::new(),
523                reason: Reason::NoConfig,
524            })
525        }
526    }
527
528    /// Parses a log; `fallback` is used when it has no `config` rows (logs recorded before
529    /// `config` rows existed). Recorded `config` rows win over `fallback`.
530    ///
531    /// # Errors
532    /// [`InputLogError`] for a bad row.
533    pub fn parse_with_config(
534        text: &str,
535        fallback: ControllerConfig,
536    ) -> Result<Self, InputLogError> {
537        Self::parse_inner(text, fallback).map(|(log, _)| log)
538    }
539
540    fn parse_inner(text: &str, fallback: ControllerConfig) -> Result<(Self, bool), InputLogError> {
541        let mut lines = text.lines().filter(|l| !l.trim().is_empty());
542        let header = lines.next().unwrap_or("");
543        if header.trim_end_matches('\r') != Input::CSV_HEADER {
544            return Err(InputLogError {
545                line: header.to_string(),
546                reason: Reason::BadHeader,
547            });
548        }
549        let mut config = fallback;
550        let mut had_config = false;
551        let mut seed = None;
552        let mut inputs = Vec::new();
553        for line in lines {
554            let row = Row::split(line)?;
555            match row.kind {
556                KIND_CONFIG => {
557                    let key = ConfigKey::from_name(row.a)
558                        .ok_or_else(|| row.fail(Reason::UnknownConfigKey))?;
559                    key.set(&mut config, row.b)
560                        .ok_or_else(|| row.fail(Reason::BadNumber { field: "value" }))?;
561                    had_config = true;
562                }
563                KIND_SEED => {
564                    seed = Some(StallMemorySnapshot::new(
565                        row.number("peak_us", row.a)?,
566                        row.number("age_us", row.b)?,
567                    ));
568                }
569                _ => inputs.push(Input::parse_row(line)?),
570            }
571        }
572        config.validate().map_err(|e| InputLogError {
573            line: String::new(),
574            reason: Reason::InvalidConfig(e),
575        })?;
576        Ok((
577            Self {
578                config,
579                seed,
580                inputs,
581            },
582            had_config,
583        ))
584    }
585
586    /// Moves every input's time so the first input is at 0.
587    pub fn rebase(&mut self) {
588        let Some(origin) = self.inputs.first().map(Input::now_us) else {
589            return;
590        };
591        for input in &mut self.inputs {
592            *input = input.rebased(origin);
593        }
594    }
595
596    /// A controller built from the recorded configuration and seed.
597    ///
598    /// # Errors
599    /// [`Error`] when the configuration is invalid.
600    pub fn controller(&self) -> Result<BufferController, Error> {
601        BufferController::new(self.config, self.seed)
602    }
603
604    /// Replays every input through a fresh [`InputLog::controller`] and returns each event with
605    /// the time of the input that produced it.
606    ///
607    /// # Errors
608    /// [`Error`] when the recorded configuration is invalid.
609    pub fn replay(&self) -> Result<Vec<(Micros, Event)>, Error> {
610        let mut controller = self.controller()?;
611        let mut events = Vec::new();
612        for input in &self.inputs {
613            input.apply(&mut controller);
614            while let Some(e) = controller.poll_event() {
615                events.push((input.now_us(), e));
616            }
617        }
618        Ok(events)
619    }
620}