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