~jojo/jojos-hue

ref: fd25d622b8969d915895c1eaf2ab89acf284d0f9 jojos-hue/server/src/audiovis.rs -rw-r--r-- 5.9 KiB
fd25d622JoJo color correct strips & preamp in audiovis based on base color value a month ago
                                                                                
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
use num::Complex;
use palette::{FromColor, Hsv, Mix, Saturate, Srgb};
use pulse_simple::Record;
use rustfft::FftPlanner;
use std::{
    sync::mpsc::{channel, Receiver},
    thread,
};

const SAMPLE_RATE: usize = 48000;
// Must be power of 2
const SAMPLES_PER_PERIOD: usize = 256;

const BASS_CUTOFF: f32 = 400.0;
const HIGH_CUTOFF: f32 = 3000.0;

const MAX_FREQ: f32 = 20_000.0;

pub struct AudioVis {
    rx: Receiver<Hsv>,
    color: Hsv,
}

impl AudioVis {
    pub fn new(base: Hsv) -> Self {
        let (tx, rx) = channel();
        thread::spawn(move || {
            let recorder = Record::new(
                "jojos-hue",
                "Capture audio to stream as color data to jojos-hue devices",
                None,
                SAMPLE_RATE as u32,
            );
            let mut stereo_data = [[0.0f32; 2]; SAMPLES_PER_PERIOD];
            let (bass_cutoff_bin, high_cutoff_bin) =
                (freq_to_bin(BASS_CUTOFF), freq_to_bin(HIGH_CUTOFF));
            let mut i = 0u16;
            loop {
                recorder.read(&mut stereo_data);
                let bin_amps = stereo_pcm_to_bins(&stereo_data);
                let mut bass_amps = [0.0; SAMPLES_PER_PERIOD >> 1];
                for (bin, &amp) in bin_amps.iter().enumerate() {
                    bass_amps[bin] = bass_pass(bin_to_freq(bin), amp);
                }
                let mut mid_amps = [0.0; SAMPLES_PER_PERIOD >> 1];
                for (bin, &amp) in bin_amps.iter().enumerate() {
                    mid_amps[bin] = mid_pass(bin_to_freq(bin), amp);
                }
                let mut high_amps = [0.0; SAMPLES_PER_PERIOD >> 1];
                for (bin, &amp) in bin_amps.iter().enumerate() {
                    high_amps[bin] = high_pass(bin_to_freq(bin), amp);
                }
                let amp_bass = max_amp(&bass_amps[..bass_cutoff_bin]);
                let amp_mid = max_amp(&mid_amps[bass_cutoff_bin..high_cutoff_bin]);
                let amp_high = max_amp(&high_amps[high_cutoff_bin..]);
                let preamp = base.value * 8.0;
                let (bass_lvl, mid_lvl, high_lvl) = (
                    norm_amp(preamp * amp_bass).powf(2.5),
                    norm_amp(preamp * amp_mid * 1.4).powf(2.55),
                    norm_amp(preamp * amp_high * 3.5).powf(2.3),
                );
                let color = Hsv::from_color(Srgb::new(bass_lvl, mid_lvl, high_lvl)).saturate(0.4);

                // i += 1;
                // if i > 40 {
                //     i = 0;
                //     println!(
                //         "amp: bass: {}, mid: {}, high: {}\nlvl: bass: {}, mid: {}, high: {}\nc2: {:?}\n",
                //         amp_bass,
                //         amp_mid,
                //         amp_high,
                //         bass_lvl,
                //         mid_lvl,
                //         high_lvl,
                //         color
                //     );
                // }

                tx.send(color).unwrap();
            }
        });
        Self {
            rx,
            color: Hsv::new(0.0, 0.0, 0.0),
        }
    }
    pub fn color(&mut self) -> Hsv {
        if let Some(c2) = self.rx.try_iter().last() {
            let c1 = self.color;
            self.color = c1.mix(&c2, 0.1).saturate(0.2);
        }
        self.color
    }
}
fn bin_to_freq(i: usize) -> f32 {
    (i * SAMPLE_RATE) as f32 / SAMPLES_PER_PERIOD as f32
}

fn freq_to_bin(f: f32) -> usize {
    (f * SAMPLES_PER_PERIOD as f32 / SAMPLE_RATE as f32 + 0.5) as usize
}

fn pass_to(freq: f32, amp: f32, cut: f32) -> f32 {
    assert!(freq >= 0.0);
    if freq > cut {
        0.0
    } else {
        let x = freq / cut;
        let sharpness = (cut / 400.0).powf(2.0);
        amp * f32::max(1.0 - (3.0 * sharpness).powf(7.0 * (x - 1.0)), 0.0)
    }
}

fn band_pass(freq: f32, amp: f32, low_cut: f32, high_cut: f32) -> f32 {
    pass_from(freq, pass_to(freq, amp, high_cut), low_cut)
}

fn pass_from(freq: f32, amp: f32, cut: f32) -> f32 {
    assert!(freq >= 0.0 && cut < MAX_FREQ);
    if freq < cut {
        0.0
    } else {
        let x = (freq - cut) / (MAX_FREQ - cut);
        let sharpness = ((MAX_FREQ - cut) / 2700.0).powf(10.0);
        amp * f32::max(1.0 - (3.0 * sharpness).powf(-7.0 * x), 0.0)
    }
}

fn bass_pass(freq: f32, amp: f32) -> f32 {
    pass_to(freq, amp, BASS_CUTOFF)
}

fn mid_pass(freq: f32, amp: f32) -> f32 {
    band_pass(freq, amp, BASS_CUTOFF - 170.0, HIGH_CUTOFF + 300.0)
}

fn high_pass(freq: f32, amp: f32) -> f32 {
    pass_from(freq, amp, HIGH_CUTOFF)
}

/// Normalize an amplitude to [0, 1]
fn norm_amp(x: f32) -> f32 {
    (x / (x.powi(2) + 8.0).sqrt()).powf(1.8)
    //    db / (db + 1.0)
    // let x = db / 52.0;
    // if x > 1.0 {
    //     1.0
    // } else {
    //     (1.0 - x) * x + x * (1.0 / (1.0 + (-10.0 * (x - 0.5)).exp()))
    // }
}

/// bin == index of fft where there is a corresponding frequence
fn stereo_pcm_to_bins(
    stereo_data: &[[f32; 2]; SAMPLES_PER_PERIOD],
) -> [f32; SAMPLES_PER_PERIOD >> 1] {
    let complex_zero = Complex {
        re: 0.0f32,
        im: 0.0f32,
    };
    let mut avg_data = [complex_zero; SAMPLES_PER_PERIOD];
    for (i, &[l, r]) in stereo_data.iter().enumerate() {
        avg_data[i] = Complex {
            re: (l + r) / 2.0,
            im: 0.0,
        };
    }
    let mut planner = FftPlanner::new();
    let fft = planner.plan_fft_forward(SAMPLES_PER_PERIOD);
    fft.process(&mut avg_data as &mut [_]);
    let bin_amps_complex = avg_data;
    let mut bin_amps = [0.0f32; SAMPLES_PER_PERIOD >> 1];
    for (i, &c) in bin_amps_complex
        .iter()
        .take(SAMPLES_PER_PERIOD >> 1)
        .enumerate()
    {
        let amp = (c.re.powi(2) + c.im.powi(2)).sqrt();
        //bin_amps[i] = 20.0 * amp.log(10.0);
        bin_amps[i] = amp;
    }
    bin_amps
}

fn max_amp(amps: &[f32]) -> f32 {
    let mut max_amp = 0.0;
    for i in 0..amps.len() {
        if amps[i] > max_amp {
            max_amp = amps[i];
        }
    }
    max_amp
}