buffering-runtime 0.5.0

Sans-IO live-TS playout buffer controller: measures delivery jitter (RFC 5481 PDV), keeps a stall memory, and decides when a player should start, pause and resume and how deep its buffer must be. Integer-only, no_std + alloc.
Documentation
//! Replay a per-chunk delivery trace through the controller and print every
//! decision.
//!
//! With NO arguments it replays a built-in deterministic synthetic trace (a
//! clean 60 s link, one 1.4 s delivery stall at 20 s followed by a line-rate
//! burst of the backlog) with a 500 ms initial target so the stall is visible;
//! the private real traces cannot be a default (they live in the private
//! fixtures repo). With a path it replays a real trace.
//!
//! The trace is the zenith-tv CSV: `arrival_ns,bytes,pcr_27mhz` (the PCR cell
//! is empty for a chunk without one). It is read with `std::fs` at run time.
//! The renderer is the obedient model of the decision contract (it freezes at
//! `Pause`, restarts at `Resume`), ticked every `--tick-ms` (default 50).
//!
//! The playback (PTS) domain is derived from the PCR minus a constant
//! `--offset-ms` (default 500: PCR runs ahead of PTS); decisions do not
//! depend on it, only the printed positions do.
//!
//! ```text
//! cargo run -p buffering-runtime --example replay_trace                # built-in synthetic
//! cargo run -p buffering-runtime --example replay_trace -- <trace.csv> \
//!     [--initial-ms 1800] [--tick-ms 50] [--offset-ms 500] [--reconnect-gap-ms 2000]
//! ```
//!
//! A silence longer than `--reconnect-gap-ms` before a chunk is treated as a
//! reconnect: `SourceEnded` at the last chunk, `Reconnected` before the new one.

use core::time::Duration;

use broadcast_common::clock33::{PCR_WRAP_27MHZ, pcr_split};
use buffering_runtime::{
    BufferController, Clock27, ControllerConfig, Event, Hint, micros_as_duration,
};
use std::process::ExitCode;

/// `a` moved by the signed `delta` on the 27 MHz clock.
fn shift(a: u64, delta: i64) -> u64 {
    (i128::from(a) + i128::from(delta)).rem_euclid(i128::from(PCR_WRAP_27MHZ)) as u64
}

/// A reduced 27 MHz tick count as a validated clock position.
fn clock27(ticks: u64) -> Clock27 {
    let (base, ext) = pcr_split(ticks);
    Clock27::from_parts(base, ext).expect("a reduced 27 MHz value is on the clock")
}

const TICKS_PER_US: u64 = 27;

fn arg(args: &[String], name: &str, default: u64) -> u64 {
    args.iter()
        .position(|a| a == name)
        .and_then(|i| args.get(i + 1))
        .and_then(|v| v.parse().ok())
        .unwrap_or(default)
}

/// 60 s of 35 ms PCR chunks with 0-15 ms deterministic jitter and one 1.4 s
/// stall at 20 s whose backlog arrives as a 10x burst. `(arrival_us, bytes, pcr)`.
fn synthetic() -> Vec<(u64, u32, Option<u64>)> {
    const STEP_US: u64 = 35_000;
    const GAP_AT_US: u64 = 20_000_000;
    const GAP_US: u64 = 1_400_000;
    let (mut seed, mut last, mut burst) = (12345u64, 0u64, None::<u64>);
    let mut v = Vec::new();
    for k in 0..(60_000_000 / STEP_US) {
        let media = k * STEP_US;
        seed = (seed.wrapping_mul(1_103_515_245).wrapping_add(12_345)) & 0x7FFF_FFFF;
        let ideal = media + (seed >> 8) % 15_000;
        let mut arrival = ideal;
        if burst.is_none() && (GAP_AT_US..GAP_AT_US + STEP_US).contains(&ideal) {
            burst = Some(GAP_AT_US + GAP_US);
        }
        if let Some(b) = burst {
            if b > ideal {
                arrival = b;
                burst = Some(b + STEP_US / 10);
            } else {
                burst = None;
            }
        }
        arrival = arrival.max(last);
        last = arrival;
        v.push((
            arrival,
            1316,
            Some((media * TICKS_PER_US + 27_000_000) % PCR_WRAP_27MHZ),
        ));
    }
    v
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let path = args.first().filter(|a| !a.starts_with("--"));
    let tick_us = arg(&args, "--tick-ms", 50) * 1000;
    let offset =
        i64::try_from(arg(&args, "--offset-ms", 500) * 1000 * TICKS_PER_US).unwrap_or(i64::MAX);
    let gap_us = arg(&args, "--reconnect-gap-ms", 2000) * 1000;
    let mut cfg = ControllerConfig::default();
    let default_initial_ms = if path.is_some() {
        cfg.policy.initial.as_millis() as u64
    } else {
        500
    };
    cfg.policy.initial = Duration::from_millis(arg(&args, "--initial-ms", default_initial_ms));
    let mut c = match BufferController::new(cfg, None) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("bad config: {e}");
            return ExitCode::from(1);
        }
    };

    let mut chunks: Vec<(u64, u32, Option<u64>)> = Vec::new();
    if let Some(path) = path {
        let text = match std::fs::read_to_string(path) {
            Ok(t) => t,
            Err(e) => {
                eprintln!("cannot read {path}: {e}");
                return ExitCode::from(1);
            }
        };
        for line in text.lines().skip(1) {
            let mut f = line.split(',');
            let (Some(a), Some(b), pcr) = (f.next(), f.next(), f.next()) else {
                continue;
            };
            let (Ok(a), Ok(b)) = (a.parse::<u64>(), b.parse::<u32>()) else {
                continue;
            };
            chunks.push((a / 1000, b, pcr.and_then(|p| p.parse::<u64>().ok())));
        }
    } else {
        chunks = synthetic();
    }
    let Some(t0) = chunks.first().map(|c| c.0) else {
        eprintln!("empty trace");
        return ExitCode::from(1);
    };

    // Renderer model: (running, clock position at last set, time of last set).
    let mut running = false;
    let zero = clock27(0);
    let (mut clock, mut t_set) = (zero, Duration::ZERO);
    let pos = |clock: Clock27, t_set: Duration, now: Duration| {
        let elapsed_us = now.saturating_sub(t_set).as_micros() as u64;
        clock27((clock.ticks() + elapsed_us * TICKS_PER_US) % PCR_WRAP_27MHZ)
    };
    let mut next_tick = Duration::ZERO;
    let mut last_arrival = Duration::ZERO;
    let out = |c: &mut BufferController,
               now: Duration,
               running: &mut bool,
               clock: &mut Clock27,
               t_set: &mut Duration| {
        while let Some(ev) = c.poll_event() {
            let t = now.as_secs_f64();
            match ev {
                Event::StartPlaying { media_27mhz, lead } | Event::Resume { media_27mhz, lead } => {
                    *running = true;
                    *clock = media_27mhz;
                    *t_set = now;
                    println!(
                        "{t:9.3}s {} media={media_27mhz} lead={}us",
                        ev.name(),
                        lead.as_micros()
                    );
                }
                Event::Pause { hold_at_27mhz, .. } => {
                    *clock = hold_at_27mhz;
                    *t_set = now;
                    *running = false;
                    println!("{t:9.3}s {ev:?}");
                }
                Event::TargetChanged { .. } => {}
                other => println!("{t:9.3}s {other:?}"),
            }
        }
    };

    for (i, (arrival, bytes, pcr)) in chunks.iter().enumerate() {
        let arrival = micros_as_duration(arrival - t0);
        if i > 0 && arrival.saturating_sub(last_arrival).as_micros() as u64 >= gap_us {
            c.on_hint(last_arrival, Hint::SourceEnded);
            c.on_hint(arrival, Hint::Reconnected);
            out(&mut c, arrival, &mut running, &mut clock, &mut t_set);
        }
        while (next_tick.as_micros() as u64) <= (arrival.as_micros() as u64) {
            let p = running.then(|| pos(clock, t_set, next_tick));
            c.on_tick(
                next_tick,
                (running || clock != zero).then_some(p.unwrap_or(clock)),
            );
            out(&mut c, next_tick, &mut running, &mut clock, &mut t_set);
            next_tick += Duration::from_micros(tick_us);
        }
        c.on_chunk(arrival, *bytes, pcr.map(clock27));
        if let Some(pcr) = pcr {
            let end = shift(*pcr, -offset);
            c.on_media(arrival, clock27(end));
        }
        last_arrival = arrival;
    }
    let s = c.stats();
    println!(
        "state={} target={}us stalls={} longest_freeze={}us pdv_baseline={}us stall_peak={}us rfc3550_j={}us discontinuities={} hints={}",
        s.state,
        s.target.as_micros(),
        s.stalls,
        s.longest_freeze.as_micros(),
        s.est.baseline.as_micros(),
        s.est.stall_peak.as_micros(),
        s.est.rfc3550_jitter.as_micros(),
        s.discontinuities,
        s.hints_seen
    );
    ExitCode::SUCCESS
}