summaryrefslogtreecommitdiff
path: root/audio/src/lib.rs
blob: b2d3e875e1eb56bf9dadf4df94808e1f4aebef7f (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
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
//! The `audio` crate stores all audio assets that need to be loaded during runtime

use raylib::audio::RaylibAudio;
use std::time::{Duration, Instant};

use channel::{Channel, NoiseChannel, PulseChannel, TriangleChannel};
use data::Data;

mod channel;
mod data;
mod parse;
mod program;

/// The `Error` type used within this crate
pub type Error = Box<dyn std::error::Error>;

/// The `Result` type used witin this crate
pub type Result<T> = std::result::Result<T, crate::Error>;

const AUDIO_FPS: u32 = 60;
const TIME_SLICE: Duration = Duration::from_millis(1000 / AUDIO_FPS as u64);

/// Holds each audio channel
pub struct Channels {
	pub pulse_a: PulseChannel,
	pub pulse_b: PulseChannel,
	pub triangle: TriangleChannel,
	pub noise: NoiseChannel,
}
impl Channels {
	pub(crate) fn load() -> crate::Result<Self> {
		// Phantom handle to the raylib audio subsystem
		// Raylib doesnt use a handle, but the rust bindings
		// have one to ensure memory safety.
		//
		// We must leak this handle after allocating it,
		// if we dont then all audio will be unloaded :(
		//
		// NOTE: would this cause issues if `Audio::load` was
		// called multiple times?
		let handle = Box::leak(Box::new(RaylibAudio::init_audio_device()?));

		let pulse_a = PulseChannel::load(handle)?;
		pulse_a.set_volume(0.0);
		pulse_a.play();
		let pulse_b = PulseChannel::load(handle)?;
		pulse_b.set_volume(0.0);
		pulse_b.play();
		let triangle = TriangleChannel::load(handle)?;
		triangle.set_volume(0.0);
		triangle.play();
		let noise = NoiseChannel::load(handle)?;
		noise.set_volume(0.0);
		noise.play();

		Ok(Self {
			pulse_a,
			pulse_b,
			triangle,
			noise,
		})
	}
}

/// The `Audio` container initalizes the audio subsystem
/// for raylib, leaks it (to gurentee audio is statically loaded),
/// then loads all needed audio samples
pub struct Audio {
	channels: Channels,
	last: Instant,
	pub data: Data,
}
impl Audio {
	pub fn load() -> crate::Result<Self> {
		let channels = Channels::load()?;
		let last = Instant::now();
		let data = Data::load()?;

		Ok(Self {
			channels,
			last,
			data,
		})
	}

	pub fn update(&mut self) {
		if self.last.elapsed() >= TIME_SLICE {
			self.data.megalovania.exec(&mut self.channels);
			self.last = Instant::now();
		}

		self.channels.pulse_a.update();
		self.channels.pulse_b.update();
		self.channels.triangle.update();
		self.channels.noise.update();
	}
}