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
//! Head-Related Transfer Function (HRTF) module. Provides all needed types and methods for HRTF rendering.
//!
//! # Overview
//!
//! HRTF stands for [Head-Related Transfer Function](https://en.wikipedia.org/wiki/Head-related_transfer_function)
//! and can work only with spatial sounds. For each of such sound source after it was processed by HRTF you can
//! definitely tell from which locationsound came from. In other words HRTF improves perception of sound to
//! the level of real life.
//!
//! # HRIR Spheres
//!
//! This library uses Head-Related Impulse Response (HRIR) spheres to create HRTF spheres. HRTF sphere is a set of
//! points in 3D space which are connected into a mesh forming triangulated sphere. Each point contains spectrum
//! for left and right ears which will be used to modify samples from each spatial sound source to create binaural
//! sound. HRIR spheres can be found [here](https://github.com/mrDIMAS/hrir_sphere_builder/tree/master/hrtf_base/IRCAM)
//!
//! # Usage
//!
//! To use HRTF you need to change default renderer to HRTF renderer like so:
//!
//! ```no_run
//! use fyrox_sound::context::{self, SoundContext};
//! use fyrox_sound::renderer::hrtf::{HrirSphereResource, HrirSphereResourceExt, HrtfRenderer};
//! use fyrox_sound::renderer::Renderer;
//! use std::path::{Path, PathBuf};
//! use hrtf::HrirSphere;
//!
//! fn use_hrtf(context: &mut SoundContext) {
//!     // IRC_1002_C.bin is HRIR sphere in binary format, can be any valid HRIR sphere
//!     // from base mentioned above.
//!     let hrir_path = PathBuf::from("examples/data/IRC_1002_C.bin");
//!     let hrir_sphere = HrirSphere::from_file(&hrir_path, context::SAMPLE_RATE).unwrap();
//!
//!     context.state().set_renderer(Renderer::HrtfRenderer(HrtfRenderer::new(HrirSphereResource::from_hrir_sphere(hrir_sphere, hrir_path))));
//! }
//! ```
//!
//! # Performance
//!
//! HRTF is `heavy`. Usually it 4-5 slower than default renderer, this is essential because HRTF requires some heavy
//! math (fast Fourier transform, convolution, etc.). On Ryzen 1700 it takes 400-450 μs (0.4 - 0.45 ms) per source.
//! In most cases this is ok, engine works in separate thread and it has around 100 ms to prepare new portion of
//! samples for output device.
//!
//! # Known problems
//!
//! This renderer still suffers from small audible clicks in very fast moving sounds, clicks sounds more like
//! "buzzing" - it is due the fact that hrtf is different from frame to frame which gives "bumps" in amplitude
//! of signal because of phase shift each impulse response have. This can be fixed by short cross fade between
//! small amount of samples from previous frame with same amount of frames of current as proposed in
//! [here](http://csoundjournal.com/issue9/newHRTFOpcodes.html)
//!
//! Clicks can be reproduced by using clean sine wave of 440 Hz on some source moving around listener.

use crate::{
    context::{self, DistanceModel, SoundContext},
    listener::Listener,
    renderer::render_source_2d_only,
    source::SoundSource,
};
use fyrox_core::{
    log::Log,
    reflect::prelude::*,
    uuid::{uuid, Uuid},
    visitor::{Visit, VisitResult, Visitor},
    TypeUuidProvider,
};
use fyrox_resource::{
    event::ResourceEventBroadcaster,
    loader::{BoxedLoaderFuture, ResourceLoader},
    untyped::UntypedResource,
    Resource, ResourceData, ResourceStateRef,
};
use hrtf::HrirSphere;
use std::{
    any::Any,
    borrow::Cow,
    fmt::Debug,
    fmt::Formatter,
    io::Cursor,
    path::{Path, PathBuf},
};

/// See module docs.
#[derive(Clone, Debug, Default, Reflect)]
pub struct HrtfRenderer {
    hrir_resource: Option<HrirSphereResource>,
    #[reflect(hidden)]
    processor: Option<hrtf::HrtfProcessor>,
}

impl Visit for HrtfRenderer {
    fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
        let mut region = visitor.enter_region(name)?;

        Log::verify(self.hrir_resource.visit("HrirResource", &mut region));

        Ok(())
    }
}

impl HrtfRenderer {
    /// Creates new HRTF renderer using specified HRTF sphere. See module docs for more info.
    pub fn new(hrir_sphere_resource: HrirSphereResource) -> Self {
        Self {
            processor: Some(hrtf::HrtfProcessor::new(
                {
                    let sphere = hrir_sphere_resource.data_ref().hrir_sphere.clone().unwrap();
                    sphere
                },
                SoundContext::HRTF_INTERPOLATION_STEPS,
                SoundContext::HRTF_BLOCK_LEN,
            )),
            hrir_resource: Some(hrir_sphere_resource),
        }
    }

    /// Sets a desired HRIR sphere resource. Current state of the renderer will be reset and then it will be recreated
    /// on the next render call only if the resource is fully loaded.
    pub fn set_hrir_sphere_resource(&mut self, resource: Option<HrirSphereResource>) {
        self.hrir_resource = resource;
        self.processor = None;
    }

    /// Returns current HRIR sphere resource (if any).
    pub fn hrir_sphere_resource(&self) -> Option<HrirSphereResource> {
        self.hrir_resource.clone()
    }

    pub(crate) fn render_source(
        &mut self,
        source: &mut SoundSource,
        listener: &Listener,
        distance_model: DistanceModel,
        out_buf: &mut [(f32, f32)],
    ) {
        // Re-create HRTF processor on the fly only when a respective HRIR sphere resource is fully loaded.
        // This is a poor-man's async support for crippled OSes such as WebAssembly.
        if self.processor.is_none() {
            if let Some(resource) = self.hrir_resource.as_ref() {
                let state = resource.state();
                if let ResourceStateRef::Ok(hrir) = state.get() {
                    self.processor = Some(hrtf::HrtfProcessor::new(
                        hrir.hrir_sphere.clone().unwrap(),
                        SoundContext::HRTF_INTERPOLATION_STEPS,
                        SoundContext::HRTF_BLOCK_LEN,
                    ));
                }
            }
        }

        // Render as 2D first with k = (1.0 - spatial_blend).
        render_source_2d_only(source, out_buf);

        // Then add HRTF part with k = spatial_blend
        let new_distance_gain = source.gain()
            * source.spatial_blend()
            * source.calculate_distance_gain(listener, distance_model);
        let new_sampling_vector = source.calculate_sampling_vector(listener);

        if let Some(processor) = self.processor.as_mut() {
            processor.process_samples(hrtf::HrtfContext {
                source: &source.frame_samples,
                output: out_buf,
                new_sample_vector: hrtf::Vec3::new(
                    new_sampling_vector.x,
                    new_sampling_vector.y,
                    new_sampling_vector.z,
                ),
                prev_sample_vector: hrtf::Vec3::new(
                    source.prev_sampling_vector.x,
                    source.prev_sampling_vector.y,
                    source.prev_sampling_vector.z,
                ),
                prev_left_samples: &mut source.prev_left_samples,
                prev_right_samples: &mut source.prev_right_samples,
                prev_distance_gain: source.prev_distance_gain.unwrap_or(new_distance_gain),
                new_distance_gain,
            });
        }

        source.prev_sampling_vector = new_sampling_vector;
        source.prev_distance_gain = Some(new_distance_gain);
    }
}

/// Wrapper for [`HrirSphere`] to be able to use it in the resource manager, that will handle async resource
/// loading automatically.
#[derive(Reflect, Default)]
pub struct HrirSphereResourceData {
    path: PathBuf,
    #[reflect(hidden)]
    hrir_sphere: Option<HrirSphere>,
}

impl Debug for HrirSphereResourceData {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HrirSphereResourceData")
            .field("Path", &self.path.to_string_lossy().to_string())
            .finish()
    }
}

impl Visit for HrirSphereResourceData {
    fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
        let mut guard = visitor.enter_region(name)?;

        self.path.visit("Path", &mut guard)?;

        Ok(())
    }
}

impl TypeUuidProvider for HrirSphereResourceData {
    fn type_uuid() -> Uuid {
        uuid!("c92a0fa3-0ed3-49a9-be44-8f06271c6be2")
    }
}

impl ResourceData for HrirSphereResourceData {
    fn path(&self) -> Cow<Path> {
        Cow::Borrowed(&self.path)
    }

    fn set_path(&mut self, path: PathBuf) {
        self.path = path;
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn type_uuid(&self) -> Uuid {
        <Self as TypeUuidProvider>::type_uuid()
    }

    fn is_procedural(&self) -> bool {
        false
    }
}

/// Resource loader for [`HrirSphereResource`].
pub struct HrirSphereLoader;

impl ResourceLoader for HrirSphereLoader {
    fn extensions(&self) -> &[&str] {
        &["hrir"]
    }

    fn data_type_uuid(&self) -> Uuid {
        <HrirSphereResourceData as TypeUuidProvider>::type_uuid()
    }

    fn load(
        &self,
        hrir_sphere: UntypedResource,
        event_broadcaster: ResourceEventBroadcaster,
        reload: bool,
    ) -> BoxedLoaderFuture {
        Box::pin(async move {
            let path = hrir_sphere.path().to_path_buf();

            match fyrox_core::io::load_file(&path).await {
                Ok(file) => match HrirSphere::new(Cursor::new(file), context::SAMPLE_RATE) {
                    Ok(sphere) => {
                        Log::info(format!("HRIR sphere {:?} is loaded!", path));

                        hrir_sphere.commit_ok(HrirSphereResourceData {
                            hrir_sphere: Some(sphere),
                            path,
                        });

                        event_broadcaster.broadcast_loaded_or_reloaded(hrir_sphere, reload);
                    }
                    Err(error) => {
                        Log::err(format!(
                            "Unable to load HRIR sphere from {:?}! Reason {:?}",
                            path, error
                        ));

                        hrir_sphere.commit_error(path, error);
                    }
                },
                Err(error) => {
                    Log::err(format!(
                        "Unable to load HRIR sphere from {:?}! Reason {:?}",
                        path, error
                    ));

                    hrir_sphere.commit_error(path, error);
                }
            }
        })
    }
}

/// An alias to `Resource<HrirSphereResourceData>`.
pub type HrirSphereResource = Resource<HrirSphereResourceData>;

/// A set of extension methods for [`HrirSphereResource`]
pub trait HrirSphereResourceExt {
    /// Creates a new HRIR sphere resource directly from pre-loaded HRIR sphere. It could be used if you
    /// do not use a resource manager, but want to load HRIR spheres manually.
    fn from_hrir_sphere(hrir_sphere: HrirSphere, path: PathBuf) -> Self;
}

impl HrirSphereResourceExt for HrirSphereResource {
    fn from_hrir_sphere(hrir_sphere: HrirSphere, path: PathBuf) -> Self {
        Resource::new_ok(HrirSphereResourceData {
            hrir_sphere: Some(hrir_sphere),
            path,
        })
    }
}