Skip to main content

qualia_audio/
sonify.rs

1//! U3-style hear path: events → parametric mono PCM (navigate by time).
2
3use crate::types::AuditoryEvent;
4
5/// Map class hash low bits to a hearable frequency (deterministic, not semantic truth).
6pub fn class_to_hz(class_hash: u64) -> f32 {
7    let bucket = (class_hash % 12) as f32;
8    220.0 * 2.0_f32.powf(bucket / 12.0)
9}
10
11/// Render events into mono f32 of `total_frames` at `sample_rate`.
12/// Overlapping events sum with soft clip.
13pub fn sonify_events_mono(
14    events: &[AuditoryEvent],
15    sample_rate: u32,
16    total_frames: usize,
17    out: &mut [f32],
18) -> usize {
19    let n = total_frames.min(out.len());
20    out[..n].fill(0.0);
21    if sample_rate == 0 || n == 0 {
22        return 0;
23    }
24    for e in events {
25        if e.class_hash == 0 && e.confidence_u16 == 0 {
26            continue;
27        }
28        let f0 = class_to_hz(e.class_hash);
29        let gain = e.confidence_f32() * 0.25;
30        let start = e.start_frame.min(n as u64) as usize;
31        let end = e.end_frame.min(n as u64) as usize;
32        if end <= start {
33            continue;
34        }
35        for i in start..end {
36            let t = (i - start) as f32 / sample_rate as f32;
37            // Simple envelope
38            let env = if i - start < 64 {
39                (i - start) as f32 / 64.0
40            } else if end - i < 64 {
41                (end - i) as f32 / 64.0
42            } else {
43                1.0
44            };
45            out[i] += (core::f32::consts::TAU * f0 * t).sin() * gain * env;
46        }
47    }
48    for s in out.iter_mut().take(n) {
49        *s = s.clamp(-1.0, 1.0);
50    }
51    n
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    use crate::types::AuditoryEvent;
58
59    #[test]
60    fn sonify_nonzero() {
61        let mut e = AuditoryEvent::empty();
62        e.class_hash = 0xABC;
63        e.confidence_u16 = 40_000;
64        e.start_frame = 0;
65        e.end_frame = 1000;
66        let mut out = [0.0f32; 2000];
67        let n = sonify_events_mono(&[e], 16000, 2000, &mut out);
68        assert_eq!(n, 2000);
69        assert!(out.iter().any(|&x| x.abs() > 0.01));
70    }
71}