kira 0.12.0

Expressive audio library for games
Documentation
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#[cfg(test)]
mod test;

use std::sync::Mutex;
use std::{sync::Arc, time::Duration};

use crate::sound::{EndPosition, IntoOptionalRegion, PlaybackPosition, Region, SoundData};
use crate::{Decibels, Panning, PlaybackRate, StartTime};
use crate::{Tween, Value};
use rtrb::RingBuffer;

use super::sound::Shared;
use super::{StreamingSoundHandle, StreamingSoundSettings, command_writers_and_readers};

use super::{
	decoder::Decoder,
	sound::{StreamingSound, decode_scheduler::DecodeScheduler},
};

const ERROR_BUFFER_CAPACITY: usize = 1;

/// A streaming sound that is not playing yet.
pub struct StreamingSoundData<Error: Send + 'static> {
	pub(crate) decoder: Box<dyn Decoder<Error = Error>>,
	/// Settings for the streaming sound.
	pub settings: StreamingSoundSettings,
	/**

	The portion of the sound this [`StreamingSoundData`] represents.

	Note that the [`StreamingSoundData`] holds the entire piece of audio
	it was originally given regardless of the value of `slice`, but
	[`StreamingSoundData::num_frames`] and [`StreamingSoundData::duration`]
	will behave as if this [`StreamingSoundData`] only contained the specified
	portion of audio.
	*/
	pub slice: Option<(usize, usize)>,
}

impl<Error: Send> StreamingSoundData<Error> {
	/// Creates a [`StreamingSoundData`] for a [`Decoder`].
	#[must_use]
	pub fn from_decoder(decoder: impl Decoder<Error = Error> + 'static) -> Self {
		Self {
			decoder: Box::new(decoder),
			settings: StreamingSoundSettings::default(),
			slice: None,
		}
	}

	/**

	Sets when the sound should start playing.

	# Examples

	Configuring a sound to start 4 ticks after a clock's current time:

	```no_run
	use kira::{
		AudioManager, AudioManagerSettings, DefaultBackend,
		sound::streaming::{StreamingSoundData, StreamingSoundSettings},
		clock::ClockSpeed,
	};

	let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
	let clock_handle = manager.add_clock(ClockSpeed::TicksPerMinute(120.0))?;
	let sound = StreamingSoundData::from_file("sound.ogg")?
		.start_time(clock_handle.time() + 4);
	# Result::<(), Box<dyn std::error::Error>>::Ok(())
	```
	*/
	#[must_use = "This method consumes self and returns a modified StreamingSoundData, so the return value should be used"]
	pub fn start_time(mut self, start_time: impl Into<StartTime>) -> Self {
		self.settings.start_time = start_time.into();
		self
	}

	/// Sets where in the sound playback should start.
	#[must_use = "This method consumes self and returns a modified StreamingSoundData, so the return value should be used"]
	pub fn start_position(mut self, start_position: impl Into<PlaybackPosition>) -> Self {
		self.settings.start_position = start_position.into();
		self
	}

	/**

	Sets the portion of the sound that should be looped.

	# Examples

	Configure a sound to loop the portion from 3 seconds in to the end:

	```no_run
	# use kira::sound::streaming::StreamingSoundData;
	let sound = StreamingSoundData::from_file("sound.ogg")?.loop_region(3.0..);
	# Result::<(), Box<dyn std::error::Error>>::Ok(())
	```

	Configure a sound to loop the portion from 2 to 4 seconds:

	```no_run
	# use kira::sound::streaming::StreamingSoundData;
	let sound = StreamingSoundData::from_file("sound.ogg")?.loop_region(2.0..4.0);
	# Result::<(), Box<dyn std::error::Error>>::Ok(())
	```
	*/
	#[must_use = "This method consumes self and returns a modified StreamingSoundData, so the return value should be used"]
	pub fn loop_region(mut self, loop_region: impl IntoOptionalRegion) -> Self {
		self.settings.loop_region = loop_region.into_optional_region();
		self
	}

	/**

	Sets the volume of the sound.

	# Examples

	Set the volume to a fixed value:

	```no_run
	# use kira::sound::streaming::StreamingSoundData;
	let sound = StreamingSoundData::from_file("sound.ogg")?.volume(-6.0);
	# Result::<(), Box<dyn std::error::Error>>::Ok(())
	```

	Link the volume to a modulator:

	```no_run
	use kira::{
		AudioManager, AudioManagerSettings, DefaultBackend,
		modulator::tweener::TweenerBuilder,
		sound::streaming::StreamingSoundData,
		Value, Mapping, Easing,
		Decibels,
	};

	let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
	let tweener = manager.add_modulator(TweenerBuilder {
		initial_value: 0.5,
	})?;
	let sound = StreamingSoundData::from_file("sound.ogg")?.volume(Value::FromModulator {
		id: tweener.id(),
		mapping: Mapping {
			input_range: (0.0, 1.0),
			output_range: (Decibels::SILENCE, Decibels::IDENTITY),
			easing: Easing::Linear,
		},
	});
	# Result::<(), Box<dyn std::error::Error>>::Ok(())
	```
	*/
	#[must_use = "This method consumes self and returns a modified StreamingSoundData, so the return value should be used"]
	pub fn volume(mut self, volume: impl Into<Value<Decibels>>) -> Self {
		self.settings.volume = volume.into();
		self
	}

	/**

	Sets the playback rate of the sound.

	Changing the playback rate will change both the speed
	and the pitch of the sound.

	# Examples

	Set the playback rate as a factor:

	```no_run
	# use kira::sound::streaming::StreamingSoundData;
	let sound = StreamingSoundData::from_file("sound.ogg")?.playback_rate(0.5);
	# Result::<(), Box<dyn std::error::Error>>::Ok(())
	```

	Set the playback rate as a change in semitones:

	```no_run
	# use kira::sound::streaming::StreamingSoundData;
	use kira::Semitones;
	let sound = StreamingSoundData::from_file("sound.ogg")?.playback_rate(Semitones(-2.0));
	# Result::<(), Box<dyn std::error::Error>>::Ok(())
	```

	Link the playback rate to a modulator:

	```no_run
	use kira::{
		AudioManager, AudioManagerSettings, DefaultBackend,
		modulator::tweener::TweenerBuilder,
		sound::streaming::StreamingSoundData,
		Value, Easing, Mapping,
		PlaybackRate,
	};

	let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
	let tweener = manager.add_modulator(TweenerBuilder {
		initial_value: 0.5,
	})?;
	let sound = StreamingSoundData::from_file("sound.ogg")?.playback_rate(Value::FromModulator {
		id: tweener.id(),
		mapping: Mapping {
			input_range: (0.0, 1.0),
			output_range: (PlaybackRate(0.0), PlaybackRate(1.0)),
			easing: Easing::Linear,
		},
	});
	# Result::<(), Box<dyn std::error::Error>>::Ok(())
	```
	*/
	#[must_use = "This method consumes self and returns a modified StreamingSoundData, so the return value should be used"]
	pub fn playback_rate(mut self, playback_rate: impl Into<Value<PlaybackRate>>) -> Self {
		self.settings.playback_rate = playback_rate.into();
		self
	}

	/**

	Sets the panning of the sound, where 0 is hard left
	and 1 is hard right.

	# Examples

	Set the panning to a fixed value:

	``` no_run
	# use kira::sound::streaming::StreamingSoundData;
	let sound = StreamingSoundData::from_file("sound.ogg")?.panning(-0.5);
	# Result::<(), Box<dyn std::error::Error>>::Ok(())
	```

	Link the panning to a modulator:

	```no_run
	use kira::{
		AudioManager, AudioManagerSettings, DefaultBackend,
		modulator::tweener::TweenerBuilder,
		sound::streaming::StreamingSoundData,
		Value, Easing, Mapping,
		Panning,
	};

	let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
	let tweener = manager.add_modulator(TweenerBuilder {
		initial_value: -0.5,
	})?;
	let sound = StreamingSoundData::from_file("sound.ogg")?.panning(Value::FromModulator {
		id: tweener.id(),
		mapping: Mapping {
			input_range: (-1.0, 1.0),
			output_range: (Panning::LEFT, Panning::RIGHT),
			easing: Easing::Linear,
		},
	});
	# Result::<(), Box<dyn std::error::Error>>::Ok(())
	```
	*/
	#[must_use = "This method consumes self and returns a modified StreamingSoundData, so the return value should be used"]
	pub fn panning(mut self, panning: impl Into<Value<Panning>>) -> Self {
		self.settings.panning = panning.into();
		self
	}

	/// Sets the tween used to fade in the instance from silence.
	#[must_use = "This method consumes self and returns a modified StreamingSoundData, so the return value should be used"]
	pub fn fade_in_tween(mut self, fade_in_tween: impl Into<Option<Tween>>) -> Self {
		self.settings.fade_in_tween = fade_in_tween.into();
		self
	}

	/// Returns the `StreamingSoundData` with the specified settings.
	#[must_use = "This method consumes self and returns a modified StreamingSoundData, so the return value should be used"]
	pub fn with_settings(mut self, settings: StreamingSoundSettings) -> Self {
		self.settings = settings;
		self
	}

	/// Returns the number of frames in the [`StreamingSoundData`].
	///
	/// If [`StreamingSoundData::slice`] is `Some`, this will be the number
	/// of frames in the slice.
	#[must_use]
	pub fn num_frames(&self) -> usize {
		if let Some((start, end)) = self.slice {
			end - start
		} else {
			self.decoder.num_frames()
		}
	}

	/// Returns the duration of the audio.
	///
	/// If [`StreamingSoundData::slice`] is `Some`, this will be the duration
	/// of the slice.
	#[must_use]
	pub fn duration(&self) -> Duration {
		Duration::from_secs_f64(self.num_frames() as f64 / self.decoder.sample_rate() as f64)
	}

	/// Returns the total duration of the audio, regardless of its slice.
	#[must_use]
	pub fn unsliced_duration(&self) -> Duration {
		Duration::from_secs_f64(
			self.decoder.num_frames() as f64 / self.decoder.sample_rate() as f64,
		)
	}

	/**

	Sets the portion of the audio this [`StreamingSoundData`] represents.
	*/
	#[must_use = "This method consumes self and returns a modified StreamingSoundData, so the return value should be used"]
	pub fn slice(mut self, region: impl IntoOptionalRegion) -> Self {
		self.slice = region.into_optional_region().map(|Region { start, end }| {
			let start = start.into_samples(self.decoder.sample_rate());
			let end = match end {
				EndPosition::EndOfAudio => self.decoder.num_frames(),
				EndPosition::Custom(end) => end.into_samples(self.decoder.sample_rate()),
			};
			(start, end)
		});
		self
	}
}

impl<T: Send> StreamingSoundData<T> {}

#[cfg(feature = "symphonia")]
impl StreamingSoundData<crate::sound::FromFileError> {
	/// Creates a [`StreamingSoundData`] for an audio file.
	pub fn from_file(
		path: impl AsRef<std::path::Path>,
	) -> Result<StreamingSoundData<crate::sound::FromFileError>, crate::sound::FromFileError> {
		use std::fs::File;

		use super::symphonia::SymphoniaDecoder;

		Ok(Self::from_decoder(SymphoniaDecoder::new(Box::new(
			File::open(path)?,
		))?))
	}

	/// Creates a [`StreamingSoundData`] for a cursor wrapping audio file data.
	pub fn from_cursor<T: AsRef<[u8]> + Send + Sync + 'static>(
		cursor: std::io::Cursor<T>,
	) -> Result<StreamingSoundData<crate::sound::FromFileError>, crate::sound::FromFileError> {
		use super::symphonia::SymphoniaDecoder;

		Ok(Self::from_decoder(SymphoniaDecoder::new(Box::new(cursor))?))
	}

	/// Creates a [`StreamingSoundData`] for a type that implements Symphonia's
	/// [`MediaSource`](symphonia::core::io::MediaSource) trait.
	pub fn from_media_source(
		media_source: impl symphonia::core::io::MediaSource + 'static,
	) -> Result<StreamingSoundData<crate::sound::FromFileError>, crate::sound::FromFileError> {
		use super::symphonia::SymphoniaDecoder;

		Ok(Self::from_decoder(SymphoniaDecoder::new(Box::new(
			media_source,
		))?))
	}
}

impl<Error: Send + 'static> StreamingSoundData<Error> {
	pub(crate) fn split(
		self,
	) -> Result<
		(
			StreamingSound,
			StreamingSoundHandle<Error>,
			DecodeScheduler<Error>,
		),
		Error,
	> {
		let (command_writers, command_readers, decode_scheduler_command_readers) =
			command_writers_and_readers();
		let (error_producer, error_consumer) = RingBuffer::new(ERROR_BUFFER_CAPACITY);
		let sample_rate = self.decoder.sample_rate();
		let shared = Arc::new(Shared::new());
		let (scheduler, frame_consumer) = DecodeScheduler::new(
			self.decoder,
			self.slice,
			self.settings,
			shared.clone(),
			decode_scheduler_command_readers,
			error_producer,
		)?;
		let sound = StreamingSound::new(
			sample_rate,
			self.settings,
			shared.clone(),
			frame_consumer,
			command_readers,
			&scheduler,
		);
		let handle = StreamingSoundHandle {
			shared,
			command_writers,
			error_consumer: Mutex::new(error_consumer),
		};
		Ok((sound, handle, scheduler))
	}
}

impl<Error: Send + 'static> SoundData for StreamingSoundData<Error> {
	type Error = Error;

	type Handle = StreamingSoundHandle<Error>;

	#[allow(clippy::type_complexity)]
	fn into_sound(self) -> Result<(Box<dyn crate::sound::Sound>, Self::Handle), Self::Error> {
		let (sound, handle, scheduler) = self.split()?;
		scheduler.start();
		Ok((Box::new(sound), handle))
	}
}