aboutsummaryrefslogtreecommitdiffstats
path: root/src/music.rs
blob: fe489891da379b75e88269a53367e79330fca28f (plain) (blame)
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
#[cfg(all(feature = "music", not(feature = "32k")))]
use sdl2::audio::AudioCallback;

#[cfg(all(feature = "music", not(feature = "32k")))]
use crate::vendored::micromod::MmC2r;

#[cfg(all(feature = "music", not(feature = "32k")))]
pub struct Music {
  pub pcm: Vec<i16>,
  pub offset: usize,
}

#[cfg(all(feature = "music", not(feature = "32k")))]
impl AudioCallback for Music {
  type Channel = f32;

  fn callback(&mut self, out_f: &mut [f32]) {
    let len = out_f.len();
    let slice = &self.pcm[self.offset..(self.offset + len).min(self.pcm.len() - 1)];
    let len = slice.len();
    pcm_to_f32pcm(&slice, out_f, len);
    self.offset += len;
    if self.offset > self.pcm.len() {
      self.offset = 0;
    }
  }
}

#[cfg(all(feature = "music", not(feature = "32k")))]
pub fn mmc2r_to_pcm(state: &mut MmC2r) -> Vec<i16> {
  let mut destination = Vec::<i16>::new();
  loop {
    let mut out = [0; 4096];
    if !state.get_audio(&mut out, 2048) {
      break;
    }
    for sample in out {
      destination.push(sample);
    }
  }
  destination
}

#[cfg(all(feature = "music", not(feature = "32k")))]
pub fn pcm_to_f32pcm(input: &[i16], output: &mut [f32], len: usize) {
  for i in 0..len {
    output[i] = f32::from(input[i]) / f32::from(0x7FFF as i16);
  }
}