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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
//! The main entrypoint for controlling audio from gameplay code.

pub mod backend;
pub(crate) mod command;
pub mod error;

use std::{collections::HashSet, sync::Arc};

use ringbuf::RingBuffer;

use crate::{
	clock::{Clock, ClockHandle, ClockId},
	error::CommandError,
	sound::SoundData,
	track::{SubTrackId, Track, TrackBuilder, TrackHandle, TrackId},
	tween::Tween,
	ClockSpeed,
};

use self::{
	backend::{
		context::Context,
		resources::{create_resources, create_unused_resource_channels, ResourceControllers},
		Backend, Renderer,
	},
	command::{producer::CommandProducer, ClockCommand, Command, MixerCommand, SoundCommand},
	error::{AddClockError, AddSubTrackError, PlaySoundError},
};

/// The playback state for all audio.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MainPlaybackState {
	/// Audio is playing normally.
	Playing,
	/// Audio is fading out and will be paused when the
	/// fade-out is finished.
	Pausing,
	/// Audio processing is paused and no sound is being
	/// produced.
	Paused,
}

impl MainPlaybackState {
	fn from_u8(state: u8) -> Self {
		match state {
			0 => Self::Playing,
			1 => Self::Pausing,
			2 => Self::Paused,
			_ => panic!("Not a valid MainPlaybackState"),
		}
	}
}

/// Settings for an [`AudioManager`].
#[non_exhaustive]
pub struct AudioManagerSettings {
	/// The number of commands that be sent to the renderer at a time.
	///
	/// Each action you take, like playing a sound or pausing a clock,
	/// queues up one command.
	pub command_capacity: usize,
	/// The maximum number of sounds that can be playing at a time.
	pub sound_capacity: usize,
	/// The maximum number of mixer sub-tracks that can exist at a time.
	pub sub_track_capacity: usize,
	/// The maximum number of clocks that can exist at a time.
	pub clock_capacity: usize,
	/// Configures the main mixer track.
	pub main_track_builder: TrackBuilder,
}

impl AudioManagerSettings {
	/// Creates a new [`AudioManagerSettings`] with the default settings.
	pub fn new() -> Self {
		Self::default()
	}

	/// Sets the number of commands that be sent to the renderer at a time.
	///
	/// Each action you take, like playing a sound or pausing a clock,
	/// queues up one command.
	pub fn command_capacity(self, command_capacity: usize) -> Self {
		Self {
			command_capacity,
			..self
		}
	}

	/// Sets the maximum number of sounds that can be playing at a time.
	pub fn sound_capacity(self, sound_capacity: usize) -> Self {
		Self {
			sound_capacity,
			..self
		}
	}

	/// Sets the maximum number of mixer sub-tracks that can exist at a time.
	pub fn sub_track_capacity(self, sub_track_capacity: usize) -> Self {
		Self {
			sub_track_capacity,
			..self
		}
	}

	/// Sets the maximum number of clocks that can exist at a time.
	pub fn clock_capacity(self, clock_capacity: usize) -> Self {
		Self {
			clock_capacity,
			..self
		}
	}

	/// Configures the main mixer track.
	pub fn main_track_builder(self, builder: TrackBuilder) -> Self {
		Self {
			main_track_builder: builder,
			..self
		}
	}
}

impl Default for AudioManagerSettings {
	fn default() -> Self {
		Self {
			command_capacity: 128,
			sound_capacity: 128,
			sub_track_capacity: 128,
			clock_capacity: 8,
			main_track_builder: TrackBuilder::default(),
		}
	}
}

/// Controls audio from gameplay code.
pub struct AudioManager<B: Backend> {
	backend: B,
	context: Arc<Context>,
	command_producer: CommandProducer,
	resource_controllers: ResourceControllers,
}

impl<B: Backend> AudioManager<B> {
	/// Creates a new [`AudioManager`].
	pub fn new(mut backend: B, settings: AudioManagerSettings) -> Result<Self, B::InitError> {
		let sample_rate = backend.sample_rate();
		let context = Arc::new(Context::new(sample_rate));
		let (command_producer, command_consumer) =
			RingBuffer::new(settings.command_capacity).split();
		let (unused_resource_producers, unused_resource_collector) =
			create_unused_resource_channels(&settings);
		let (resources, resource_controllers) =
			create_resources(settings, unused_resource_producers, &context);
		let renderer = Renderer::new(context.clone(), resources, command_consumer);
		backend.init(renderer, unused_resource_collector)?;
		Ok(Self {
			backend,
			context,
			command_producer: CommandProducer::new(command_producer),
			resource_controllers,
		})
	}

	/// Plays a sound.
	pub fn play<D: SoundData>(
		&mut self,
		sound_data: D,
	) -> Result<D::Handle, PlaySoundError<D::Error>> {
		let key = self
			.resource_controllers
			.sound_controller
			.try_reserve()
			.map_err(|_| PlaySoundError::SoundLimitReached)?;
		let (sound, handle) = sound_data
			.into_sound()
			.map_err(PlaySoundError::IntoSoundError)?;
		self.command_producer
			.push(Command::Sound(SoundCommand::Add(key, sound)))?;
		Ok(handle)
	}

	/// Creates a mixer sub-track.
	pub fn add_sub_track(
		&mut self,
		builder: TrackBuilder,
	) -> Result<TrackHandle, AddSubTrackError> {
		let id = SubTrackId(
			self.resource_controllers
				.sub_track_controller
				.try_reserve()
				.map_err(|_| AddSubTrackError::SubTrackLimitReached)?,
		);
		let existing_routes = builder.routes.0.keys().copied().collect();
		let sub_track = Track::new(builder, &self.context);
		let handle = TrackHandle {
			id: TrackId::Sub(id),
			shared: Some(sub_track.shared()),
			command_producer: self.command_producer.clone(),
			existing_routes,
		};
		self.command_producer
			.push(Command::Mixer(MixerCommand::AddSubTrack(id, sub_track)))?;
		Ok(handle)
	}

	/// Creates a clock.
	pub fn add_clock(&mut self, speed: ClockSpeed) -> Result<ClockHandle, AddClockError> {
		let id = ClockId(
			self.resource_controllers
				.clock_controller
				.try_reserve()
				.map_err(|_| AddClockError::ClockLimitReached)?,
		);
		let clock = Clock::new(speed);
		let handle = ClockHandle {
			id,
			shared: clock.shared(),
			command_producer: self.command_producer.clone(),
		};
		self.command_producer
			.push(Command::Clock(ClockCommand::Add(id, clock)))?;
		Ok(handle)
	}

	/// Fades out and pauses all audio.
	pub fn pause(&mut self, fade_out_tween: Tween) -> Result<(), CommandError> {
		self.command_producer.push(Command::Pause(fade_out_tween))
	}

	/// Resumes and fades in all audio.
	pub fn resume(&mut self, fade_out_tween: Tween) -> Result<(), CommandError> {
		self.command_producer.push(Command::Resume(fade_out_tween))
	}

	/// Returns a handle to the main mixer track.
	pub fn main_track(&self) -> TrackHandle {
		TrackHandle {
			id: TrackId::Main,
			shared: None,
			command_producer: self.command_producer.clone(),
			existing_routes: HashSet::new(),
		}
	}

	/// Returns the current playback state of the audio.
	pub fn state(&self) -> MainPlaybackState {
		self.context.state()
	}

	/// Returns the number of sounds that can be loaded at a time.
	pub fn sound_capacity(&self) -> usize {
		self.resource_controllers.sound_controller.capacity()
	}

	/// Returns the number of mixer sub-tracks that can exist at a time.
	pub fn sub_track_capacity(&self) -> usize {
		self.resource_controllers.sub_track_controller.capacity()
	}

	/// Returns the number of clocks that can exist at a time.
	pub fn clock_capacity(&self) -> usize {
		self.resource_controllers.clock_controller.capacity()
	}

	/// Returns the number of sounds that are currently loaded.
	pub fn num_sounds(&self) -> usize {
		self.resource_controllers.sound_controller.len()
	}

	/// Returns the number of mixer sub-tracks that currently exist.
	pub fn num_sub_tracks(&self) -> usize {
		self.resource_controllers.sub_track_controller.len()
	}

	/// Returns the number of clocks that currently exist.
	pub fn num_clocks(&self) -> usize {
		self.resource_controllers.clock_controller.len()
	}

	/// Returns a mutable reference to this manager's backend.
	pub fn backend_mut(&mut self) -> &mut B {
		&mut self.backend
	}
}