summaryrefslogtreecommitdiffstats
path: root/mictoled/pdmgen/src/main.rs
blob: 873f3ead051badfad54b7b3add7fa6645f8020e9 (plain)
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
use std::{io::Write, slice};

fn main() {
    let freq_ampl_pairs : Vec<String> = std::env::args()
        .skip(1)
        .collect();

    let freq_ampl : Vec<(f32, f32)> = freq_ampl_pairs
        .chunks_exact(2)
        .map(|c| {
            (c[0].parse().expect("argument should convert to 32"),
             c[1].parse().expect("argument should convert to 32"))
        })
        .collect();

    println!("PDM gen with:");
    for (f, a) in &freq_ampl {
        println!("Freq: {} Ampl: {}", f, a);
    }

    const AUDIO_RATE : usize = 31250;
    const INTERP : usize = 64;
    //const PDM_RATE : usize = AUDIO_RATE * INTERP;

    const AUDIO_LEN : usize = 2 * AUDIO_RATE;

    let mut audio_signal = Vec::new();
    audio_signal.resize(AUDIO_LEN, 0f32);
    use std::f32::consts::PI;
    for (f, a) in &freq_ampl {
        for n in 0..AUDIO_LEN {
            audio_signal[n] += a * f32::sin(2.0 * PI * f / (AUDIO_RATE as f32) * (n as f32));
        }
    }

    let mut pdm_signal = Vec::with_capacity(audio_signal.len() * INTERP);
    for samp in audio_signal {
        let mut quant = 0i8;
        let mut sigma = 0.0;
        for _i in 0..INTERP {
            let delta = samp - quant as f32;
            sigma += delta;
            quant = if sigma >= 0.0 { 1 } else { -1 };
            pdm_signal.push(quant);
        }
    }

    let fd = std::fs::File::create("pdm.npy").expect("pdm.npy should be created");
    let mut fd = std::io::BufWriter::new(fd);
    let slice_u8: &[u8] = unsafe {
        slice::from_raw_parts(
            pdm_signal.as_ptr() as *const u8,
            pdm_signal.len(),
        )
    };
    fd.write(slice_u8).expect("write to pdm.npy");

    let fd = std::fs::File::create("pdm.hex").expect("pdm.hex should be created");
    let mut fd = std::io::BufWriter::new(fd);
    for samp in pdm_signal {
        writeln!(&mut fd, "{}", if samp > 0 { 1 } else { 0 }).expect("write to pdm.hex");
    }
}