~jojo/jojos-hue

ref: 1ca4225edef1863d947306fb4c52d8dda84c4740 jojos-hue/server/src/audiovis.rs -rw-r--r-- 6.9 KiB
1ca4225eJoJo Add command AudioVis to visualise playback audio spectrum 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use num::Complex;
use palette::{Blend, 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 = 2900.0;

const MAX_FREQ: f32 = 20_000.0;

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

impl AudioVis {
    pub fn new() -> 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 max_amp_bass = max_amp(&bass_amps[..bass_cutoff_bin]).1;
                let m_m = max_amp(&mid_amps[bass_cutoff_bin..high_cutoff_bin]);
                let m_h = max_amp(&high_amps[high_cutoff_bin..]);
                let max_amp_mid = (m_m.0 + bass_cutoff_bin, m_m.1).1;
                let max_amp_high = (m_h.0 + high_cutoff_bin, m_h.1).1;
                let (bass_lvl, mid_lvl, high_lvl) = (
                    norm_amp(max_amp_bass).powf(1.22),       // .powf(2.5),
                    norm_amp(max_amp_mid * 1.6).powf(1.25),  // .powf(2.6),
                    norm_amp(max_amp_high * 3.2).powf(1.12), // .powf(2.4),
                );
                //let brightness = (bass_lvl * 1.6 + mid_lvl * 0.7 + high_lvl * 0.7) / 3.0;
                let color = Hsv::from_color(Srgb::new(bass_lvl, mid_lvl, high_lvl)).saturate(0.3);
                //let c1 = color.clone();
                //color.value = brightness;

                i += 1;
                if i > 40 {
                    i = 0;
                    let (max_bin_all, max_amp_all) = max_amp(&bin_amps);
                    println!(
                        "f: {:6.0}, amp: {:4.1}, vol: {:1.3}\namp: bass: {}, mid: {}, high: {}\nlvl: bass: {}, mid: {}, high: {}\nc2: {:?}\n",
                        bin_to_freq(max_bin_all),
                        max_amp_all,
                        norm_amp(max_amp_all),
                        max_amp_bass,
                        max_amp_mid,
                        max_amp_high,
                        bass_lvl,
                        mid_lvl,
                        high_lvl,
                        //c1,
                        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;
            let mut c3 = c1.mix(&c2, 0.6);
            let r = 0.2 + 0.8 * c2.value; // become bright fast, and dark more slowly
            c3.value = (1.0 - r) * c1.value + r * c2.value;
            self.color = c3;
            // let c1 = Srgb::from_color(self.color).into_linear();
            // let c2 = Srgb::from_color(c2).into_linear();
            // let c3 = c1.dodge(c2).mix(&c2, 0.6);
            // self.color = Hsv::from_color(Srgb::from_linear(c3)).saturate(0.15);
        }
        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]) -> (usize, f32) {
    let (mut max_bin, mut max_amp) = (0, 0.0);
    for i in 0..amps.len() {
        if amps[i] > max_amp {
            max_amp = amps[i];
            max_bin = i;
        }
    }
    (max_bin, max_amp)
}