1use 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#[non_exhaustive]
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize))]
60pub enum Input {
61 Chunk {
63 now_us: Duration,
65 bytes: u32,
67 pcr: Option<Clock27>,
69 },
70 TrackMedia {
72 now_us: Duration,
74 track: u32,
76 end: Clock27,
78 },
79 Tick {
81 now_us: Duration,
83 pts: Option<Clock27>,
85 },
86 Register {
88 now_us: Duration,
90 track: u32,
92 },
93 Unregister {
95 now_us: Duration,
97 track: u32,
99 },
100 Hint {
102 now_us: Duration,
104 hint: Hint,
106 },
107}
108
109impl Input {
110 pub const CSV_HEADER: &'static str = "kind,now_us,a,b";
112
113 #[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 #[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 #[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 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 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 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 fn micros(&self, field: &'static str, v: &str) -> Result<u64, InputLogError> {
321 self.number(field, v)
322 }
323
324 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 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#[non_exhaustive]
345#[derive(Clone, Copy, Debug, PartialEq, Eq)]
346pub enum Reason {
347 BadHeader,
349 UnknownKind,
351 MissingField {
353 field: &'static str,
355 },
356 BadNumber {
358 field: &'static str,
360 },
361 UnknownHint,
363 UnknownConfigKey,
365 InvalidConfig(Error),
367 NoConfig,
369}
370
371impl Reason {
372 #[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#[non_exhaustive]
391#[derive(Clone, Debug, PartialEq, Eq)]
392pub struct InputLogError {
393 pub line: String,
395 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
415fn 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
424fn 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 #[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 pub const ALL: &'static [ConfigKey] = &[$(ConfigKey::$variant),*];
457
458 #[must_use]
460 pub fn name(&self) -> &'static str {
461 match self {
462 $(Self::$variant => $token,)*
463 }
464 }
465
466 #[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 #[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#[non_exhaustive]
539#[derive(Clone, Debug, PartialEq, Eq)]
540pub struct InputLog {
541 pub config: ControllerConfig,
543 pub seed: Option<StallMemorySnapshot>,
545 pub inputs: Vec<Input>,
547}
548
549impl InputLog {
550 #[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 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 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 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 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 pub fn controller(&self) -> Result<BufferController, Error> {
680 BufferController::new(self.config, self.seed)
681 }
682
683 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}
700
701#[cfg(test)]
702mod tests {
703 use super::{Input, InputLogError, Reason};
704 use crate::error::{ConfigField, Error};
705 use crate::events::Hint;
706 use crate::time::Clock27;
707 use alloc::format;
708 use alloc::string::String;
709 use core::time::Duration;
710
711 fn zero() -> Clock27 {
712 Clock27::from_27mhz(0).expect("zero is on the clock")
713 }
714
715 #[test]
716 fn every_input_kind_has_its_row_label() {
717 assert_eq!(
718 Input::Chunk {
719 now_us: Duration::ZERO,
720 bytes: 1,
721 pcr: None
722 }
723 .name(),
724 "chunk"
725 );
726 assert_eq!(
727 Input::TrackMedia {
728 now_us: Duration::ZERO,
729 track: 1,
730 end: zero()
731 }
732 .name(),
733 "media"
734 );
735 assert_eq!(
736 Input::Tick {
737 now_us: Duration::ZERO,
738 pts: None
739 }
740 .name(),
741 "tick"
742 );
743 assert_eq!(
744 Input::Register {
745 now_us: Duration::ZERO,
746 track: 1
747 }
748 .name(),
749 "register"
750 );
751 assert_eq!(
752 Input::Unregister {
753 now_us: Duration::ZERO,
754 track: 1
755 }
756 .name(),
757 "unregister"
758 );
759 assert_eq!(
760 Input::Hint {
761 now_us: Duration::ZERO,
762 hint: Hint::SyncLoss
763 }
764 .name(),
765 "hint"
766 );
767 }
768
769 #[test]
770 fn every_log_reason_has_its_stable_label() {
771 assert_eq!(Reason::BadHeader.name(), "bad header");
772 assert_eq!(Reason::UnknownKind.name(), "unknown kind");
773 assert_eq!(
774 Reason::MissingField { field: "now_us" }.name(),
775 "missing field"
776 );
777 assert_eq!(Reason::BadNumber { field: "bytes" }.name(), "bad number");
778 assert_eq!(Reason::UnknownHint.name(), "unknown hint");
779 assert_eq!(Reason::UnknownConfigKey.name(), "unknown config key");
780 assert_eq!(
781 Reason::InvalidConfig(Error::InvalidConfig(ConfigField::Bucket)).name(),
782 "invalid config"
783 );
784 assert_eq!(Reason::NoConfig.name(), "no config");
785 }
786
787 fn text(reason: Reason, line: &str) -> String {
788 format!(
789 "{}",
790 InputLogError {
791 line: String::from(line),
792 reason
793 }
794 )
795 }
796
797 #[test]
798 fn a_rejected_row_names_its_field_in_the_error_text() {
799 assert_eq!(
800 text(Reason::MissingField { field: "now_us" }, "chunk"),
801 "missing field (now_us) in row \"chunk\""
802 );
803 assert_eq!(
804 text(Reason::BadNumber { field: "bytes" }, "chunk,x"),
805 "bad number (bytes) in row \"chunk,x\""
806 );
807 assert_eq!(
808 text(
809 Reason::InvalidConfig(Error::InvalidConfig(ConfigField::Bucket)),
810 "config,0,bucket,0"
811 ),
812 "invalid config (invalid configuration: bucket) in row \"config,0,bucket,0\""
813 );
814 }
815}