1use 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#[non_exhaustive]
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize))]
52pub enum Input {
53 Chunk {
55 now_us: Micros,
57 bytes: u32,
59 pcr: Option<Ticks27>,
61 },
62 TrackMedia {
64 now_us: Micros,
66 track: u32,
68 end: Ticks27,
70 },
71 Tick {
73 now_us: Micros,
75 pts: Option<Ticks27>,
77 },
78 Register {
80 now_us: Micros,
82 track: u32,
84 },
85 Unregister {
87 now_us: Micros,
89 track: u32,
91 },
92 Hint {
94 now_us: Micros,
96 hint: Hint,
98 },
99}
100
101impl Input {
102 pub const CSV_HEADER: &'static str = "kind,now_us,a,b";
104
105 #[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 #[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 #[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 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 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 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#[non_exhaustive]
308#[derive(Clone, Copy, Debug, PartialEq, Eq)]
309pub enum Reason {
310 BadHeader,
312 UnknownKind,
314 MissingField {
316 field: &'static str,
318 },
319 BadNumber {
321 field: &'static str,
323 },
324 UnknownHint,
326 UnknownConfigKey,
328 InvalidConfig(Error),
330 NoConfig,
332}
333
334impl Reason {
335 #[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#[non_exhaustive]
354#[derive(Clone, Debug, PartialEq, Eq)]
355pub struct InputLogError {
356 pub line: String,
358 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 #[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 pub const ALL: &'static [ConfigKey] = &[$(ConfigKey::$variant),*];
393
394 #[must_use]
396 pub fn name(&self) -> &'static str {
397 match self {
398 $(Self::$variant => $token,)*
399 }
400 }
401
402 #[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#[non_exhaustive]
461#[derive(Clone, Debug, PartialEq, Eq)]
462pub struct InputLog {
463 pub config: ControllerConfig,
465 pub seed: Option<StallMemorySnapshot>,
467 pub inputs: Vec<Input>,
469}
470
471impl InputLog {
472 #[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 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 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 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 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 pub fn controller(&self) -> Result<BufferController, Error> {
601 BufferController::new(self.config, self.seed)
602 }
603
604 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}