weirdnet-streaming 0.1.0

Streaming for Weirdnet: live and recorded audio streams over weirdnet-net with per-listener queues, clocks and remote routing, a follow-transport protocol (start, stop, locate, tempo, beacon), and loop-positioned streams with alignment for record-along.
Documentation
//! Stage stream metadata (record-along): what a stream is, and where on the sender's loop each frame belongs. The stream crate
//! carries both as opaque bytes.
//!
//! Positions are in ticks of the loop (the app's own unit), so senders and listeners with different sample rates agree; a
//! listener turns them into its own frames with [`Grid`].

use crate::listen::wall_us;
use crate::{Frame, MemorySource, Recording, StreamId, StreamInfo, StreamKind};
use serde::{Deserialize, Serialize};

/// Dry (the sender's own voices) or a mix (with other people's audio in it).
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum StageKind {
    /// Only the sender's own voices.
    Dry,
    /// The sender's voices mixed with other people's audio.
    Mix,
}

/// Once per stream, in [`StreamInfo::meta`].
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct StageStreamMeta {
    /// The app that made the stream.
    pub app: String,
    /// The project's name.
    pub project: String,
    /// Tempo, beats per minute.
    pub tempo_bpm: f64,
    /// Beats in a bar.
    pub beats_per_bar: u8,
    /// Bars in the loop.
    pub loop_bars: u16,
    /// Ticks in one loop.
    pub loop_ticks: u64,
    /// Dry or mix.
    pub kind: StageKind,
    /// Whose audio is in the stream (peer ids). Dry: just the sender.
    pub lineage: Vec<String>,
    /// For a recorded take: where on the loop its first sample belongs, in ticks.
    pub start_tick: Option<u64>,
}

/// Where a frame's first sample belongs on the sender's loop: the sender's frame within its loop and its loop length, so a
/// listener at any sample rate places it by ratio, exactly when the rates match.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LoopMarker {
    /// Which pass over the loop (0 for the first).
    pub loop_index: u32,
    /// The frame within that pass.
    pub frame: u64,
    /// Frames in one loop.
    pub loop_frames: u64,
}

/// Frame metadata: the send time (8 bytes, microseconds since the Unix epoch), then an optional loop marker (4 + 8 + 8 bytes,
/// little endian).
pub fn frame_meta(marker: Option<LoopMarker>) -> Vec<u8> {
    let mut v = wall_us().to_le_bytes().to_vec();
    if let Some(m) = marker {
        v.extend_from_slice(&m.loop_index.to_le_bytes());
        v.extend_from_slice(&m.frame.to_le_bytes());
        v.extend_from_slice(&m.loop_frames.to_le_bytes());
    }
    v
}

/// The loop marker in a frame's metadata.
pub fn marker_of(f: &Frame) -> Option<LoopMarker> {
    let m = f.meta.as_ref()?;
    let loop_index = u32::from_le_bytes(m.get(8..12)?.try_into().ok()?);
    let frame = u64::from_le_bytes(m.get(12..20)?.try_into().ok()?);
    let loop_frames = u64::from_le_bytes(m.get(20..28)?.try_into().ok()?);
    (loop_frames > 0).then_some(LoopMarker { loop_index, frame, loop_frames })
}

/// A loop in one side's frames.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Grid {
    /// Frames in one loop.
    pub loop_frames: u64,
    /// Ticks in one loop.
    pub loop_ticks: u64,
    /// Bars in the loop.
    pub loop_bars: u16,
}

impl Grid {
    /// Frames in one bar.
    pub fn bar_frames(&self) -> u64 {
        self.loop_frames / u64::from(self.loop_bars.max(1))
    }
    /// A tick on the loop as a frame, rounded to the nearest.
    pub fn tick_to_frame(&self, tick: u64) -> u64 {
        ((u128::from(tick) * u128::from(self.loop_frames) + u128::from(self.loop_ticks) / 2) / u128::from(self.loop_ticks.max(1))) as u64
    }
    /// A frame (any pass) as a tick within the loop.
    pub fn frame_to_tick(&self, frame: u64) -> u64 {
        ((u128::from(frame % self.loop_frames.max(1)) * u128::from(self.loop_ticks)) / u128::from(self.loop_frames.max(1))) as u64
    }
    /// A marker as an absolute position in this side's frames.
    pub fn abs(&self, m: LoopMarker) -> u64 {
        u64::from(m.loop_index) * self.loop_frames + self.within(m)
    }
    /// A marker's place within this side's loop.
    pub fn within(&self, m: LoopMarker) -> u64 {
        if m.loop_frames == self.loop_frames {
            return m.frame;
        }
        ((u128::from(m.frame) * u128::from(self.loop_frames) + u128::from(m.loop_frames) / 2) / u128::from(m.loop_frames)) as u64
    }
    /// The marker for an absolute position in this side's frames.
    pub fn marker(&self, abs: u64) -> LoopMarker {
        LoopMarker { loop_index: (abs / self.loop_frames.max(1)) as u32, frame: abs % self.loop_frames.max(1), loop_frames: self.loop_frames }
    }
}

/// A dry take as a recorded stream: interleaved f32 `samples` whose first sample belongs at `start_frame` on the loop, stamped
/// with `meta` (`meta.start_tick` is set, for people and other apps). 10 ms frames, each with its exact loop marker.
pub fn take_stream(id: &str, samples: &[f32], sample_rate: u32, channels: u16, grid: Grid, mut meta: StageStreamMeta, start: u64) -> MemorySource {
    meta.start_tick = Some(grid.frame_to_tick(start));
    let frames = samples.len() / channels.max(1) as usize;
    let mut info = StreamInfo::pcm_f32(id, "Dry take", sample_rate, channels).with_meta(serde_json::to_vec(&meta).unwrap_or_default());
    info.kind = StreamKind::Recorded { duration_ticks: frames as u64 };
    info.id = StreamId::new(id);
    let mut rec = Recording::new(info);
    let per = (sample_rate / 100) as usize;
    for (i, chunk) in samples.chunks(per * channels as usize).enumerate() {
        let pts = (i * per) as u64;
        let mut f = Frame::pcm_f32(i as u64, pts, channels, chunk);
        f.meta = Some(frame_meta(Some(grid.marker(start + pts))));
        rec.push(f);
    }
    rec.finish()
}