Skip to main content

weirdnet_streaming/
stage.rs

1//! Stage stream metadata (record-along): what a stream is, and where on the sender's loop each frame belongs. The stream crate
2//! carries both as opaque bytes.
3//!
4//! Positions are in ticks of the loop (the app's own unit), so senders and listeners with different sample rates agree; a
5//! listener turns them into its own frames with [`Grid`].
6
7use crate::listen::wall_us;
8use crate::{Frame, MemorySource, Recording, StreamId, StreamInfo, StreamKind};
9use serde::{Deserialize, Serialize};
10
11/// Dry (the sender's own voices) or a mix (with other people's audio in it).
12#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
13pub enum StageKind {
14    /// Only the sender's own voices.
15    Dry,
16    /// The sender's voices mixed with other people's audio.
17    Mix,
18}
19
20/// Once per stream, in [`StreamInfo::meta`].
21#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
22pub struct StageStreamMeta {
23    /// The app that made the stream.
24    pub app: String,
25    /// The project's name.
26    pub project: String,
27    /// Tempo, beats per minute.
28    pub tempo_bpm: f64,
29    /// Beats in a bar.
30    pub beats_per_bar: u8,
31    /// Bars in the loop.
32    pub loop_bars: u16,
33    /// Ticks in one loop.
34    pub loop_ticks: u64,
35    /// Dry or mix.
36    pub kind: StageKind,
37    /// Whose audio is in the stream (peer ids). Dry: just the sender.
38    pub lineage: Vec<String>,
39    /// For a recorded take: where on the loop its first sample belongs, in ticks.
40    pub start_tick: Option<u64>,
41}
42
43/// 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
44/// listener at any sample rate places it by ratio, exactly when the rates match.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct LoopMarker {
47    /// Which pass over the loop (0 for the first).
48    pub loop_index: u32,
49    /// The frame within that pass.
50    pub frame: u64,
51    /// Frames in one loop.
52    pub loop_frames: u64,
53}
54
55/// Frame metadata: the send time (8 bytes, microseconds since the Unix epoch), then an optional loop marker (4 + 8 + 8 bytes,
56/// little endian).
57pub fn frame_meta(marker: Option<LoopMarker>) -> Vec<u8> {
58    let mut v = wall_us().to_le_bytes().to_vec();
59    if let Some(m) = marker {
60        v.extend_from_slice(&m.loop_index.to_le_bytes());
61        v.extend_from_slice(&m.frame.to_le_bytes());
62        v.extend_from_slice(&m.loop_frames.to_le_bytes());
63    }
64    v
65}
66
67/// The loop marker in a frame's metadata.
68pub fn marker_of(f: &Frame) -> Option<LoopMarker> {
69    let m = f.meta.as_ref()?;
70    let loop_index = u32::from_le_bytes(m.get(8..12)?.try_into().ok()?);
71    let frame = u64::from_le_bytes(m.get(12..20)?.try_into().ok()?);
72    let loop_frames = u64::from_le_bytes(m.get(20..28)?.try_into().ok()?);
73    (loop_frames > 0).then_some(LoopMarker { loop_index, frame, loop_frames })
74}
75
76/// A loop in one side's frames.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub struct Grid {
79    /// Frames in one loop.
80    pub loop_frames: u64,
81    /// Ticks in one loop.
82    pub loop_ticks: u64,
83    /// Bars in the loop.
84    pub loop_bars: u16,
85}
86
87impl Grid {
88    /// Frames in one bar.
89    pub fn bar_frames(&self) -> u64 {
90        self.loop_frames / u64::from(self.loop_bars.max(1))
91    }
92    /// A tick on the loop as a frame, rounded to the nearest.
93    pub fn tick_to_frame(&self, tick: u64) -> u64 {
94        ((u128::from(tick) * u128::from(self.loop_frames) + u128::from(self.loop_ticks) / 2) / u128::from(self.loop_ticks.max(1))) as u64
95    }
96    /// A frame (any pass) as a tick within the loop.
97    pub fn frame_to_tick(&self, frame: u64) -> u64 {
98        ((u128::from(frame % self.loop_frames.max(1)) * u128::from(self.loop_ticks)) / u128::from(self.loop_frames.max(1))) as u64
99    }
100    /// A marker as an absolute position in this side's frames.
101    pub fn abs(&self, m: LoopMarker) -> u64 {
102        u64::from(m.loop_index) * self.loop_frames + self.within(m)
103    }
104    /// A marker's place within this side's loop.
105    pub fn within(&self, m: LoopMarker) -> u64 {
106        if m.loop_frames == self.loop_frames {
107            return m.frame;
108        }
109        ((u128::from(m.frame) * u128::from(self.loop_frames) + u128::from(m.loop_frames) / 2) / u128::from(m.loop_frames)) as u64
110    }
111    /// The marker for an absolute position in this side's frames.
112    pub fn marker(&self, abs: u64) -> LoopMarker {
113        LoopMarker { loop_index: (abs / self.loop_frames.max(1)) as u32, frame: abs % self.loop_frames.max(1), loop_frames: self.loop_frames }
114    }
115}
116
117/// A dry take as a recorded stream: interleaved f32 `samples` whose first sample belongs at `start_frame` on the loop, stamped
118/// with `meta` (`meta.start_tick` is set, for people and other apps). 10 ms frames, each with its exact loop marker.
119pub fn take_stream(id: &str, samples: &[f32], sample_rate: u32, channels: u16, grid: Grid, mut meta: StageStreamMeta, start: u64) -> MemorySource {
120    meta.start_tick = Some(grid.frame_to_tick(start));
121    let frames = samples.len() / channels.max(1) as usize;
122    let mut info = StreamInfo::pcm_f32(id, "Dry take", sample_rate, channels).with_meta(serde_json::to_vec(&meta).unwrap_or_default());
123    info.kind = StreamKind::Recorded { duration_ticks: frames as u64 };
124    info.id = StreamId::new(id);
125    let mut rec = Recording::new(info);
126    let per = (sample_rate / 100) as usize;
127    for (i, chunk) in samples.chunks(per * channels as usize).enumerate() {
128        let pts = (i * per) as u64;
129        let mut f = Frame::pcm_f32(i as u64, pts, channels, chunk);
130        f.meta = Some(frame_meta(Some(grid.marker(start + pts))));
131        rec.push(f);
132    }
133    rec.finish()
134}