fyrox_sound/
context.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Context module.
22//!
23//! # Overview
24//!
25//! Context is a sort of "sound scene" - an isolated storage for a set of sound sources, effects, filters, etc.
26//! fyrox-sound can manage multiple contexts at the same time. Main usage for multiple contexts is a typical
27//! situation in games where you have multiple scenes: a scene for main menu, a scene for game level, a scene
28//! for inventory and so on. With this approach of multiple contexts it is very easy to manage such scenes:
29//! for example your main menu have a complex scene with some sounds and you decide to load a game level -
30//! once the level is loaded you just set master gain of main menu context and it will no longer produce any
31//! sounds, only your level will do.
32
33use crate::bus::AudioBusGraph;
34use crate::{
35    listener::Listener,
36    pool::Ticket,
37    renderer::{render_source_default, Renderer},
38    source::{SoundSource, Status},
39};
40use fyrox_core::{
41    pool::{Handle, Pool},
42    reflect::prelude::*,
43    uuid_provider,
44    visitor::prelude::*,
45};
46use std::{
47    sync::{Arc, Mutex, MutexGuard},
48    time::Duration,
49};
50use strum_macros::{AsRefStr, EnumString, VariantNames};
51
52/// Sample rate for output device.
53/// TODO: Make this configurable, for now its set to most commonly used sample rate of 44100 Hz.
54pub const SAMPLE_RATE: u32 = 44100;
55
56/// Distance model defines how volume of sound will decay when distance to listener changes.
57#[derive(Copy, Clone, Debug, Eq, PartialEq, Reflect, Visit, AsRefStr, EnumString, VariantNames)]
58#[repr(u32)]
59pub enum DistanceModel {
60    /// No distance attenuation at all.
61    None = 0,
62
63    /// Distance will decay using following formula:
64    ///
65    /// `clamped_distance = min(max(distance, radius), max_distance)`
66    /// `attenuation = radius / (radius + rolloff_factor * (clamped_distance - radius))`
67    ///
68    /// where - `radius` - of source at which it has maximum volume,
69    ///         `max_distance` - distance at which decay will stop,
70    ///         `rolloff_factor` - coefficient that defines how fast volume will decay
71    ///
72    /// # Notes
73    ///
74    /// This is default distance model of context.
75    InverseDistance = 1,
76
77    /// Distance will decay using following formula:
78    ///
79    /// `clamped_distance = min(max(distance, radius), max_distance)`
80    /// `attenuation = 1.0 - radius * (clamped_distance - radius) / (max_distance - radius)`
81    ///
82    /// where - `radius` - of source at which it has maximum volume,
83    ///         `max_distance` - distance at which decay will stop
84    ///
85    /// # Notes
86    ///
87    /// As you can see `rolloff_factor` is ignored here because of linear law.
88    LinearDistance = 2,
89
90    /// Distance will decay using following formula:
91    ///
92    /// `clamped_distance = min(max(distance, radius), max_distance)`
93    /// `(clamped_distance / radius) ^ (-rolloff_factor)`
94    ///
95    /// where - `radius` - of source at which it has maximum volume,
96    ///         `max_distance` - distance at which decay will stop,
97    ///         `rolloff_factor` - coefficient that defines how fast volume will decay
98    ExponentDistance = 3,
99}
100
101uuid_provider!(DistanceModel = "957f3b00-3f89-438c-b1b7-e841e8d75ba9");
102
103impl Default for DistanceModel {
104    fn default() -> Self {
105        Self::InverseDistance
106    }
107}
108
109/// See module docs.
110#[derive(Clone, Default, Debug, Visit)]
111pub struct SoundContext {
112    pub(crate) state: Option<Arc<Mutex<State>>>,
113}
114
115impl PartialEq for SoundContext {
116    fn eq(&self, other: &Self) -> bool {
117        Arc::ptr_eq(self.state.as_ref().unwrap(), other.state.as_ref().unwrap())
118    }
119}
120
121/// A set of flags, that can be used to define what should be skipped during the
122/// serialization of a sound context.
123#[derive(Default, Debug, Clone)]
124pub struct SerializationOptions {
125    /// All sources won't be serialized, if set.
126    pub skip_sources: bool,
127    /// Bus graph won't be serialized, if set.
128    pub skip_bus_graph: bool,
129}
130
131/// Internal state of context.
132#[derive(Default, Debug, Clone, Reflect)]
133pub struct State {
134    sources: Pool<SoundSource>,
135    listener: Listener,
136    render_duration: Duration,
137    renderer: Renderer,
138    bus_graph: AudioBusGraph,
139    distance_model: DistanceModel,
140    paused: bool,
141    /// A set of flags, that can be used to define what should be skipped during the
142    /// serialization of a sound context.
143    #[reflect(hidden)]
144    pub serialization_options: SerializationOptions,
145}
146
147impl State {
148    /// Extracts a source from the context and reserves its handle. It is used to temporarily take
149    /// ownership over source, and then put node back using given ticket.
150    pub fn take_reserve(
151        &mut self,
152        handle: Handle<SoundSource>,
153    ) -> (Ticket<SoundSource>, SoundSource) {
154        self.sources.take_reserve(handle)
155    }
156
157    /// Puts source back by given ticket.
158    pub fn put_back(
159        &mut self,
160        ticket: Ticket<SoundSource>,
161        node: SoundSource,
162    ) -> Handle<SoundSource> {
163        self.sources.put_back(ticket, node)
164    }
165
166    /// Makes source handle vacant again.
167    pub fn forget_ticket(&mut self, ticket: Ticket<SoundSource>) {
168        self.sources.forget_ticket(ticket)
169    }
170
171    /// Pause/unpause the sound context. Paused context won't play any sounds.
172    pub fn pause(&mut self, pause: bool) {
173        self.paused = pause;
174    }
175
176    /// Returns true if the sound context is paused, false - otherwise.
177    pub fn is_paused(&self) -> bool {
178        self.paused
179    }
180
181    /// Sets new distance model.
182    pub fn set_distance_model(&mut self, distance_model: DistanceModel) {
183        self.distance_model = distance_model;
184    }
185
186    /// Returns current distance model.
187    pub fn distance_model(&self) -> DistanceModel {
188        self.distance_model
189    }
190
191    /// Normalizes given frequency using context's sampling rate. Normalized frequency then can be used
192    /// to create filters.
193    pub fn normalize_frequency(&self, f: f32) -> f32 {
194        f / SAMPLE_RATE as f32
195    }
196
197    /// Returns amount of time context spent on rendering all sound sources.
198    pub fn full_render_duration(&self) -> Duration {
199        self.render_duration
200    }
201
202    /// Sets new renderer.
203    pub fn set_renderer(&mut self, renderer: Renderer) -> Renderer {
204        std::mem::replace(&mut self.renderer, renderer)
205    }
206
207    /// Returns shared reference to current renderer.
208    pub fn renderer(&self) -> &Renderer {
209        &self.renderer
210    }
211
212    /// Returns mutable reference to current renderer.
213    pub fn renderer_mut(&mut self) -> &mut Renderer {
214        &mut self.renderer
215    }
216
217    /// Adds new sound source and returns handle of it by which it can be accessed later on.
218    pub fn add_source(&mut self, source: SoundSource) -> Handle<SoundSource> {
219        self.sources.spawn(source)
220    }
221
222    /// Removes sound source from the context.
223    pub fn remove_source(&mut self, source: Handle<SoundSource>) {
224        self.sources.free(source);
225    }
226
227    /// Returns shared reference to a pool with all sound sources.
228    pub fn sources(&self) -> &Pool<SoundSource> {
229        &self.sources
230    }
231
232    /// Returns mutable reference to a pool with all sound sources.
233    pub fn sources_mut(&mut self) -> &mut Pool<SoundSource> {
234        &mut self.sources
235    }
236
237    /// Returns shared reference to sound source at given handle. If handle is invalid, this method will panic.
238    pub fn source(&self, handle: Handle<SoundSource>) -> &SoundSource {
239        self.sources.borrow(handle)
240    }
241
242    /// Checks whether a handle to a sound source is valid or not.
243    pub fn is_valid_handle(&self, handle: Handle<SoundSource>) -> bool {
244        self.sources.is_valid_handle(handle)
245    }
246
247    /// Returns mutable reference to sound source at given handle. If handle is invalid, this method will panic.
248    pub fn source_mut(&mut self, handle: Handle<SoundSource>) -> &mut SoundSource {
249        self.sources.borrow_mut(handle)
250    }
251
252    /// Returns mutable reference to sound source at given handle. If handle is invalid, this method will panic.
253    pub fn try_get_source_mut(&mut self, handle: Handle<SoundSource>) -> Option<&mut SoundSource> {
254        self.sources.try_borrow_mut(handle)
255    }
256
257    /// Returns shared reference to listener. Engine has only one listener.
258    pub fn listener(&self) -> &Listener {
259        &self.listener
260    }
261
262    /// Returns mutable reference to listener. Engine has only one listener.
263    pub fn listener_mut(&mut self) -> &mut Listener {
264        &mut self.listener
265    }
266
267    /// Returns a reference to the audio bus graph.
268    pub fn bus_graph_ref(&self) -> &AudioBusGraph {
269        &self.bus_graph
270    }
271
272    /// Returns a reference to the audio bus graph.
273    pub fn bus_graph_mut(&mut self) -> &mut AudioBusGraph {
274        &mut self.bus_graph
275    }
276
277    pub(crate) fn render(&mut self, output_device_buffer: &mut [(f32, f32)]) {
278        let last_time = fyrox_core::instant::Instant::now();
279
280        if !self.paused {
281            self.sources.retain(|source| {
282                let done = source.is_play_once() && source.status() == Status::Stopped;
283                !done
284            });
285
286            self.bus_graph.begin_render(output_device_buffer.len());
287
288            // Render sounds to respective audio buses.
289            for source in self
290                .sources
291                .iter_mut()
292                .filter(|s| s.status() == Status::Playing)
293            {
294                if let Some(bus_input_buffer) = self.bus_graph.try_get_bus_input_buffer(&source.bus)
295                {
296                    source.render(output_device_buffer.len());
297
298                    match self.renderer {
299                        Renderer::Default => {
300                            // Simple rendering path. Much faster (4-5 times) than HRTF path.
301                            render_source_default(
302                                source,
303                                &self.listener,
304                                self.distance_model,
305                                bus_input_buffer,
306                            );
307                        }
308                        Renderer::HrtfRenderer(ref mut hrtf_renderer) => {
309                            hrtf_renderer.render_source(
310                                source,
311                                &self.listener,
312                                self.distance_model,
313                                bus_input_buffer,
314                            );
315                        }
316                    }
317                }
318            }
319
320            self.bus_graph.end_render(output_device_buffer);
321        }
322
323        self.render_duration = fyrox_core::instant::Instant::now() - last_time;
324    }
325}
326
327impl SoundContext {
328    /// TODO: This is magic constant that gives 1024 + 1 number when summed with
329    ///       HRTF length for faster FFT calculations. Find a better way of selecting this.
330    pub const HRTF_BLOCK_LEN: usize = 513;
331
332    pub(crate) const HRTF_INTERPOLATION_STEPS: usize = 4;
333
334    pub(crate) const SAMPLES_PER_CHANNEL: usize =
335        Self::HRTF_BLOCK_LEN * Self::HRTF_INTERPOLATION_STEPS;
336
337    /// Creates new instance of context. Internally context starts new thread which will call render all
338    /// sound source and send samples to default output device. This method returns `Arc<Mutex<Context>>`
339    /// because separate thread also uses context.
340    pub fn new() -> Self {
341        Self {
342            state: Some(Arc::new(Mutex::new(State {
343                sources: Pool::new(),
344                listener: Listener::new(),
345                render_duration: Default::default(),
346                renderer: Renderer::Default,
347                bus_graph: AudioBusGraph::new(),
348                distance_model: DistanceModel::InverseDistance,
349                paused: false,
350                serialization_options: Default::default(),
351            }))),
352        }
353    }
354
355    /// Returns internal state of the context.
356    ///
357    /// ## Deadlocks
358    ///
359    /// This method internally locks a mutex, so if you'll try to do something like this:
360    ///
361    /// ```no_run
362    /// # use fyrox_sound::context::SoundContext;
363    /// # let ctx = SoundContext::new();
364    /// let state = ctx.state();
365    /// // Do something
366    /// // ...
367    /// ctx.state(); // This will cause a deadlock.
368    /// ```
369    ///
370    /// You'll get a deadlock, so general rule here is to not store result of this method
371    /// anywhere.
372    pub fn state(&self) -> MutexGuard<'_, State> {
373        self.state.as_ref().unwrap().lock().unwrap()
374    }
375
376    /// Creates deep copy instead of shallow which is done by clone().
377    pub fn deep_clone(&self) -> SoundContext {
378        SoundContext {
379            state: Some(Arc::new(Mutex::new(self.state().clone()))),
380        }
381    }
382
383    /// Returns true if context is corrupted.
384    pub fn is_invalid(&self) -> bool {
385        self.state.is_none()
386    }
387}
388
389impl Visit for State {
390    fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
391        if visitor.is_reading() {
392            self.sources.clear();
393            self.renderer = Renderer::Default;
394        }
395
396        let mut region = visitor.enter_region(name)?;
397
398        self.listener.visit("Listener", &mut region)?;
399        if !self.serialization_options.skip_sources {
400            let _ = self.sources.visit("Sources", &mut region);
401        }
402        if !self.serialization_options.skip_bus_graph {
403            let _ = self.bus_graph.visit("BusGraph", &mut region);
404        }
405        self.renderer.visit("Renderer", &mut region)?;
406        self.paused.visit("Paused", &mut region)?;
407        self.distance_model.visit("DistanceModel", &mut region)?;
408
409        Ok(())
410    }
411}