forge-audio 0.1.0

Zero-allocation, lock-free audio architecture for real-time DSP, game engines, and WebAssembly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! WavDiff + DiffPool + RollbackBuffer — 18-byte diff protocol with
//! pre-allocated ring buffers for deterministic rollback.
//!
//! All world mutations flow through `WavDiff`. The `DiffPool` is a 1.1MB
//! pre-allocated ring buffer that never grows. The `RollbackBuffer` stores
//! exactly 120 frames (1.0 second at 120Hz) of `FrameSnapshot` metadata
//! for prediction/correction rollback.
//!
//! Zero heap allocation. Integer-only. Bitwise deterministic.

/// Pre-allocated DiffPool capacity.
/// 18 bytes × 64000 ≈ 1.125 MB — fits the 1.1MB budget with margin.
pub const POOL_CAPACITY: usize = 64000;

/// Rollback window: exactly 120 frames = 1.0 second at 120Hz.
/// Architecturally locked — do not change.
pub const ROLLBACK_FRAMES: usize = 120;

/// 18-byte diff record for a single state mutation.
///
/// Every state change produces
/// one `WavDiff`. The engine is the sole authority that evaluates diffs.
///
/// Layout: `#[repr(C, packed)]` guarantees exactly 18 bytes with zero padding.
/// Fields are laid out as 3×i32 + 3×u16 = 12 + 6 = 18 bytes.
#[repr(C, packed)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WavDiff {
    /// Channel index.
    pub channel: i32,             // 4 bytes
    /// Frame offset in buffer.
    pub frame_offset: i32,             // 4 bytes
    /// Parameter identifier.
    pub param_id: i32,             // 4 bytes
    /// Index within the channel's state array.
    pub index: u16,               // 2 bytes
    /// State value before the mutation.
    pub old_val: u16,             // 2 bytes
    /// State value after the mutation.
    pub new_val: u16,             // 2 bytes
}
// Compile-time size assertion: WavDiff must be exactly 18 bytes.
const _: () = assert!(core::mem::size_of::<WavDiff>() == 18);

impl WavDiff {
    /// Convenience accessor for coordinate tuple as a tuple.
    pub fn coords(&self) -> (i32, i32, i32) {
        (self.channel, self.frame_offset, self.param_id)
    }
}

impl Default for WavDiff {
    fn default() -> Self {
        Self {
            channel: 0,
            frame_offset: 0,
            param_id: 0,
            index: 0,
            old_val: 0,
            new_val: 0,
        }
    }
}

/// Pre-allocated 1.1MB ring buffer of `WavDiff` entries.
///
/// Never grows. When full, oldest entries are overwritten.
/// At 120Hz with ~100 diffs/frame, this holds ~640 frames (~5.3 seconds)
/// of history — well beyond the 120-frame rollback window.
pub struct DiffPool {
    buffer: Box<[WavDiff; POOL_CAPACITY]>, // @forge:allow_alloc — one-time boot allocation
    /// Write cursor — next slot to write into.
    head: usize,
    /// Total number of valid entries (capped at POOL_CAPACITY).
    count: usize,
}

impl DiffPool {
    /// Create a new pre-allocated DiffPool. All slots zeroed.
    /// Single heap allocation at boot — never grows.
    pub fn new() -> Self {
        // alloc-ok: one-time boot allocation, pre-allocated ring buffer
        let buffer = vec![WavDiff::default(); POOL_CAPACITY]
            .into_boxed_slice()
            .try_into()
            .unwrap_or_else(|_| unreachable!());
        Self {
            buffer,
            head: 0,
            count: 0,
        }
    }

    /// Append a diff to the ring buffer. Returns the absolute index.
    /// O(1), no allocation.
    pub fn push(&mut self, diff: WavDiff) -> u32 {
        let idx = self.head;
        self.buffer[idx] = diff;
        self.head = (self.head + 1) % POOL_CAPACITY;
        if self.count < POOL_CAPACITY {
            self.count += 1;
        }
        idx as u32
    }

    /// Get a diff by absolute index. Returns `None` if index is out of range.
    pub fn get(&self, index: u32) -> Option<&WavDiff> {
        let idx = index as usize;
        if idx < POOL_CAPACITY {
            Some(&self.buffer[idx])
        } else {
            None
        }
    }

    /// Current write head position.
    pub fn head(&self) -> usize {
        self.head
    }

    /// Number of valid entries in the pool.
    pub fn count(&self) -> usize {
        self.count
    }

    /// Iterate diffs for a frame given `start` index and `count`.
    /// Handles ring buffer wrap-around.
    pub fn frame_diffs(&self, start: u32, count: u16) -> FrameDiffIter<'_> {
        FrameDiffIter {
            pool: self,
            current: start as usize,
            remaining: count as usize,
        }
    }

    /// Iterate diffs for a frame in reverse order (for rewind).
    /// Traverses from `start + count - 1` back to `start`.
    pub fn frame_diffs_reverse(&self, start: u32, count: u16) -> FrameDiffReverseIter<'_> {
        let c = count as usize;
        let last = if c == 0 {
            start as usize
        } else {
            (start as usize + c - 1) % POOL_CAPACITY
        };
        FrameDiffReverseIter {
            pool: self,
            current: last,
            remaining: c,
        }
    }
}

/// Forward iterator over a frame's diffs in the DiffPool.
pub struct FrameDiffIter<'a> {
    pool: &'a DiffPool,
    current: usize,
    remaining: usize,
}

impl<'a> Iterator for FrameDiffIter<'a> {
    type Item = &'a WavDiff;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        let diff = &self.pool.buffer[self.current];
        self.current = (self.current + 1) % POOL_CAPACITY;
        self.remaining -= 1;
        Some(diff)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

/// Reverse iterator over a frame's diffs in the DiffPool.
pub struct FrameDiffReverseIter<'a> {
    pool: &'a DiffPool,
    current: usize,
    remaining: usize,
}

impl<'a> Iterator for FrameDiffReverseIter<'a> {
    type Item = &'a WavDiff;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        let diff = &self.pool.buffer[self.current];
        if self.current == 0 {
            self.current = POOL_CAPACITY - 1;
        } else {
            self.current -= 1;
        }
        self.remaining -= 1;
        Some(diff)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

/// Metadata snapshot for a single simulation frame.
///
/// Stored in the `RollbackBuffer`. Points into the `DiffPool` via
/// `diff_start` and `diff_count` — no data duplication.
#[derive(Clone, Copy, Debug)]
pub struct FrameSnapshot {
    /// Monotonic tick counter.
    pub tick: u64,
    /// 10-bit packed InputBits (u16 for alignment).
    pub inputs: u16,
    /// Index into DiffPool where this frame's diffs begin.
    pub diff_start: u32,
    /// Number of 18-byte diffs produced this frame.
    pub diff_count: u16,
    /// Blake3 checksum of physical state after this frame.
    pub checksum: [u8; 32],
}

impl Default for FrameSnapshot {
    fn default() -> Self {
        Self {
            tick: 0,
            inputs: 0,
            diff_start: 0,
            diff_count: 0,
            checksum: [0u8; 32],
        }
    }
}

/// 120-frame ring buffer for prediction/correction rollback.
///
/// Exactly 1.0 second at 120Hz. Architecturally locked — never grows.
/// Each frame stores a `FrameSnapshot` that references diffs in the `DiffPool`.
pub struct RollbackBuffer {
    frames: [FrameSnapshot; ROLLBACK_FRAMES],
    /// Write cursor — next slot to write into.
    head: usize,
    /// Number of valid frames stored (capped at ROLLBACK_FRAMES).
    count: usize,
}

impl RollbackBuffer {
    /// Create a new RollbackBuffer. All 120 slots zeroed.
    pub fn new() -> Self {
        Self {
            frames: [FrameSnapshot::default(); ROLLBACK_FRAMES],
            head: 0,
            count: 0,
        }
    }

    /// Record a frame snapshot. Overwrites oldest if buffer is full.
    pub fn push(&mut self, snapshot: FrameSnapshot) {
        self.frames[self.head] = snapshot;
        self.head = (self.head + 1) % ROLLBACK_FRAMES;
        if self.count < ROLLBACK_FRAMES {
            self.count += 1;
        }
    }

    /// Find a frame by tick number. Returns `None` if not in the buffer.
    pub fn find_by_tick(&self, tick: u64) -> Option<&FrameSnapshot> {
        for i in 0..self.count {
            let idx = if self.head == 0 {
                ROLLBACK_FRAMES - 1 - i
            } else {
                (self.head + ROLLBACK_FRAMES - 1 - i) % ROLLBACK_FRAMES
            };
            if self.frames[idx].tick == tick {
                return Some(&self.frames[idx]);
            }
        }
        None
    }

    /// Get the most recent frame snapshot.
    pub fn latest(&self) -> Option<&FrameSnapshot> {
        if self.count == 0 {
            return None;
        }
        let idx = if self.head == 0 {
            ROLLBACK_FRAMES - 1
        } else {
            self.head - 1
        };
        Some(&self.frames[idx])
    }

    /// Number of valid frames stored.
    pub fn count(&self) -> usize {
        self.count
    }

    /// Iterate frames from `start_tick` to `end_tick` (inclusive) in forward order.
    /// Used for replay (old→new) after rewind.
    pub fn frames_forward(&self, start_tick: u64, end_tick: u64) -> FrameRangeIter<'_> {
        let oldest_idx = if self.count < ROLLBACK_FRAMES {
            0
        } else {
            self.head
        };
        FrameRangeIter {
            buffer: self,
            pos: 0,
            oldest_idx,
            start_tick,
            end_tick,
        }
    }

    /// Iterate frames from `end_tick` back to `start_tick` (inclusive) in reverse order.
    /// Used for rewind (new→old).
    pub fn frames_reverse(&self, start_tick: u64, end_tick: u64) -> FrameRangeReverseIter<'_> {
        FrameRangeReverseIter {
            buffer: self,
            pos: 0,
            start_tick,
            end_tick,
        }
    }
}

/// Forward iterator over frames in a tick range.
pub struct FrameRangeIter<'a> {
    buffer: &'a RollbackBuffer,
    pos: usize,
    oldest_idx: usize,
    start_tick: u64,
    end_tick: u64,
}

impl<'a> Iterator for FrameRangeIter<'a> {
    type Item = &'a FrameSnapshot;

    fn next(&mut self) -> Option<Self::Item> {
        while self.pos < self.buffer.count {
            let idx = (self.oldest_idx + self.pos) % ROLLBACK_FRAMES;
            self.pos += 1;
            let frame = &self.buffer.frames[idx];
            if frame.tick >= self.start_tick && frame.tick <= self.end_tick {
                return Some(frame);
            }
        }
        None
    }
}

/// Reverse iterator over frames in a tick range.
pub struct FrameRangeReverseIter<'a> {
    buffer: &'a RollbackBuffer,
    pos: usize,
    start_tick: u64,
    end_tick: u64,
}

impl<'a> Iterator for FrameRangeReverseIter<'a> {
    type Item = &'a FrameSnapshot;

    fn next(&mut self) -> Option<Self::Item> {
        while self.pos < self.buffer.count {
            let idx = if self.buffer.head == 0 {
                ROLLBACK_FRAMES - 1 - self.pos
            } else {
                (self.buffer.head + ROLLBACK_FRAMES - 1 - self.pos) % ROLLBACK_FRAMES
            };
            self.pos += 1;
            let frame = &self.buffer.frames[idx];
            if frame.tick >= self.start_tick && frame.tick <= self.end_tick {
                return Some(frame);
            }
        }
        None
    }
}

/// Rewind state by applying diffs in reverse (new→old).
///
/// For each diff in the frame range (newest to oldest), swaps `new_val` back
/// to `old_val` in the provided state.
///
/// `apply_fn` receives `(coords, index, value_to_set)` for each rewind step.
pub fn rewind(
    pool: &DiffPool,
    rollback: &RollbackBuffer,
    start_tick: u64,
    end_tick: u64,
    mut apply_fn: impl FnMut((i32, i32, i32), u16, u16),
) {
    for frame in rollback.frames_reverse(start_tick, end_tick) {
        // Traverse diffs in reverse: undo new→old
        for diff in pool.frame_diffs_reverse(frame.diff_start, frame.diff_count) {
            apply_fn(diff.coords(), diff.index, diff.old_val);
        }
    }
}

/// Replay diffs forward (old→new) to restore state after rewind.
///
/// For each diff in the frame range (oldest to newest), applies `new_val`.
///
/// `apply_fn` receives `(coords, index, value_to_set)` for each replay step.
pub fn replay(
    pool: &DiffPool,
    rollback: &RollbackBuffer,
    start_tick: u64,
    end_tick: u64,
    mut apply_fn: impl FnMut((i32, i32, i32), u16, u16),
) {
    for frame in rollback.frames_forward(start_tick, end_tick) {
        // Traverse diffs forward: apply old→new
        for diff in pool.frame_diffs(frame.diff_start, frame.diff_count) {
            apply_fn(diff.coords(), diff.index, diff.new_val);
        }
    }
}

/// Compute a Blake3 checksum of a frame's diffs in the DiffPool.
///
/// Hashes each 18-byte WavDiff in the frame's range sequentially.
/// The resulting 32-byte hash is stored in `FrameSnapshot.checksum` for
/// bitwise reproducibility verification across edge devices.
///
/// Zero allocation — reads directly from the pre-allocated ring buffer.
pub fn compute_tick_checksum(pool: &DiffPool, diff_start: u32, diff_count: u16) -> [u8; 32] {
    let mut hasher = blake3::Hasher::new();
    for diff in pool.frame_diffs(diff_start, diff_count) {
        // Hash the raw 18 bytes of each WavDiff
        let bytes: &[u8] = unsafe {
            core::slice::from_raw_parts(
                diff as *const WavDiff as *const u8,
                core::mem::size_of::<WavDiff>(),
            )
        };
        hasher.update(bytes);
    }
    *hasher.finalize().as_bytes()
}


// ── Property-based tests ─────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;
    use std::collections::HashMap;

    /// Strategy to generate a valid WavDiff with constrained ranges.
    fn arb_wav_diff() -> impl Strategy<Value = WavDiff> {
        (
            // Coords: small range to increase collision likelihood
            -8i32..=8i32,
            -8i32..=8i32,
            -8i32..=8i32,
            // Index within block (0..32768 but u16 max is fine)
            0u16..=255u16,
            // State IDs: small range to increase old/new overlap
            0u16..=31u16,
            0u16..=31u16,
        )
            .prop_map(|(cx, cy, cz, idx, old, new)| WavDiff {
                channel: cx,
                frame_offset: cy,
                param_id: cz,
                index: idx,
                old_val: old,
                new_val: new,
            })
    }

    /// Strategy to generate a sequence of diffs (1..=120 per frame, up to 120 frames).
    fn arb_diff_sequence() -> impl Strategy<Value = Vec<Vec<WavDiff>>> {
        // 1..=20 frames, each with 1..=10 diffs
        proptest::collection::vec(
            proptest::collection::vec(arb_wav_diff(), 1..=10),
            1..=20,
        )
    }

    // ── CP-6: Rollback Equivalence ───────────────────────────────────────
    //
    // For any sequence of WavDiff entries, rewinding (new→old) then
    // replaying (old→new) produces the original state.
    //
    // **Validates: Requirements CP-6**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(64))]
        #[test]
        fn prop_cp6_rollback_equivalence(frames_diffs in arb_diff_sequence()) {
            let mut pool = DiffPool::new();
            let mut rollback = RollbackBuffer::new();

            // Build a simple state map
            // Start with all zeros (air)
            let mut grid: HashMap<((i32, i32, i32), u16), u16> = HashMap::new();

            let start_tick = 1u64;

            // 1. Apply all diffs forward, recording into pool + rollback
            for (frame_idx, frame_diffs) in frames_diffs.iter().enumerate() {
                let tick = start_tick + frame_idx as u64;
                let diff_start = pool.head() as u32;
                let mut diff_count = 0u16;

                for diff in frame_diffs {
                    let key = (diff.coords(), diff.index);
                    // Record current state as old_val for this diff
                    let current = grid.get(&key).copied().unwrap_or(0);
                    let actual_diff = WavDiff {
                        channel: diff.channel,
                        frame_offset: diff.frame_offset,
                        param_id: diff.param_id,
                        index: diff.index,
                        old_val: current,
                        new_val: diff.new_val,
                    };
                    pool.push(actual_diff);
                    grid.insert(key, diff.new_val);
                    diff_count += 1;
                }

                rollback.push(FrameSnapshot {
                    tick,
                    inputs: 0,
                    diff_start,
                    diff_count,
                    checksum: [0u8; 32],
                });
            }

            // Capture the final state
            let final_state = grid.clone();
            let end_tick = start_tick + frames_diffs.len() as u64 - 1;

            // 2. Rewind: apply diffs in reverse (new→old)
            rewind(&pool, &rollback, start_tick, end_tick, |coords, index, val| {
                grid.insert((coords, index), val);
            });

            // Capture the rewound state (should be all zeros / initial)
            let rewound_state = grid.clone();

            // Verify rewound state: all touched keys should be back to 0 (initial)
            for key in final_state.keys() {
                let val = rewound_state.get(key).copied().unwrap_or(0);
                prop_assert_eq!(val, 0,
                    "After rewind, key {:?} should be 0 (initial), got {}", key, val);
            }

            // 3. Replay: apply diffs forward (old→new)
            replay(&pool, &rollback, start_tick, end_tick, |coords, index, val| {
                grid.insert((coords, index), val);
            });

            // 4. Verify: replayed state matches the original final state
            for (key, expected_mat) in &final_state {
                let actual = grid.get(key).copied().unwrap_or(0);
                prop_assert_eq!(actual, *expected_mat,
                    "After replay, key {:?} should be {}, got {}", key, expected_mat, actual);
            }
        }
    }

    // ── Unit test: WavDiff size ────────────────────────────────────────
    #[test]
    fn test_wav_diff_is_18_bytes() {
        assert_eq!(core::mem::size_of::<WavDiff>(), 18);
    }

    // ── Unit test: DiffPool ring buffer wrap-around ──────────────────────
    #[test]
    fn test_diffpool_wraparound() {
        let mut pool = DiffPool::new();
        // Fill to capacity
        for i in 0..POOL_CAPACITY {
            pool.push(WavDiff {
                channel: 0,
                frame_offset: 0,
                param_id: 0,
                index: (i % 65536) as u16,
                old_val: 0,
                new_val: 1,
            });
        }
        assert_eq!(pool.count(), POOL_CAPACITY);
        assert_eq!(pool.head(), 0); // wrapped around

        // One more push overwrites slot 0
        pool.push(WavDiff {
            channel: 99,
            frame_offset: 0,
            param_id: 0,
            index: 42,
            old_val: 5,
            new_val: 10,
        });
        assert_eq!(pool.count(), POOL_CAPACITY); // still capped
        let d = pool.get(0).unwrap();
        let cx = { d.channel };
        let idx = { d.index };
        assert_eq!(cx, 99);
        assert_eq!(idx, 42);
    }

    // ── Unit test: RollbackBuffer 120-frame cap ──────────────────────────
    #[test]
    fn test_rollback_buffer_cap() {
        let mut rb = RollbackBuffer::new();
        for i in 0..150u64 {
            rb.push(FrameSnapshot {
                tick: i,
                inputs: 0,
                diff_start: 0,
                diff_count: 0,
                checksum: [0u8; 32],
            });
        }
        assert_eq!(rb.count(), ROLLBACK_FRAMES);
        // Oldest tick should be 30 (150 - 120)
        assert!(rb.find_by_tick(29).is_none());
        assert!(rb.find_by_tick(30).is_some());
        assert!(rb.find_by_tick(149).is_some());
    }
}