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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Spatialization/Panning primitives
//!
//! Required for panning algorithm, distance and cone effects of panner nodes

use crate::context::{AudioContextRegistration, AudioParamId, BaseAudioContext};
use crate::node::{
    AudioNode, ChannelConfig, ChannelConfigOptions, ChannelCountMode, ChannelInterpretation,
};
use crate::param::{AudioParam, AudioParamDescriptor, AudioParamRaw, AutomationRate};
use crate::render::{AudioParamValues, AudioProcessor, AudioRenderQuantum};
use crate::SampleRate;

use std::f32::consts::PI;

/// AudioParam settings for the carthesian coordinates
pub(crate) const PARAM_OPTS: AudioParamDescriptor = AudioParamDescriptor {
    min_value: f32::MIN,
    max_value: f32::MAX,
    default_value: 0.,
    automation_rate: AutomationRate::A,
};

/// Represents the position and orientation of the person listening to the audio scene
///
/// All [`PannerNode`](crate::node::PannerNode) objects spatialize in relation to the [BaseAudioContext's](crate::context::BaseAudioContext) listener.
///
/// # Usage
///
/// For example usage, check the [`PannerNode`](crate::node::PannerNode) docs.
pub struct AudioListener {
    pub(crate) position_x: AudioParam,
    pub(crate) position_y: AudioParam,
    pub(crate) position_z: AudioParam,
    pub(crate) forward_x: AudioParam,
    pub(crate) forward_y: AudioParam,
    pub(crate) forward_z: AudioParam,
    pub(crate) up_x: AudioParam,
    pub(crate) up_y: AudioParam,
    pub(crate) up_z: AudioParam,
}

impl AudioListener {
    pub fn position_x(&self) -> &AudioParam {
        &self.position_x
    }
    pub fn position_y(&self) -> &AudioParam {
        &self.position_y
    }
    pub fn position_z(&self) -> &AudioParam {
        &self.position_z
    }
    pub fn forward_x(&self) -> &AudioParam {
        &self.forward_x
    }
    pub fn forward_y(&self) -> &AudioParam {
        &self.forward_y
    }
    pub fn forward_z(&self) -> &AudioParam {
        &self.forward_z
    }
    pub fn up_x(&self) -> &AudioParam {
        &self.up_x
    }
    pub fn up_y(&self) -> &AudioParam {
        &self.up_y
    }
    pub fn up_z(&self) -> &AudioParam {
        &self.up_z
    }
}

/// Wrapper for the [`AudioListener`] so it can be placed in the audio graph.
///
/// This node has no input, but takes the position/orientation AudioParams and copies them into the
/// 9 outputs. The outputs are connected to the PannerNodes (via an AudioParam).
///
/// The AudioListener is always connected to the AudioDestinationNode so at each
/// render quantum its positions are recalculated.
pub(crate) struct AudioListenerNode {
    registration: AudioContextRegistration,
    fields: AudioListener,
}

impl AudioNode for AudioListenerNode {
    fn registration(&self) -> &AudioContextRegistration {
        &self.registration
    }

    fn channel_config_raw(&self) -> &ChannelConfig {
        unreachable!()
    }

    fn channel_config_cloned(&self) -> ChannelConfig {
        ChannelConfigOptions {
            count: 1,
            mode: ChannelCountMode::Explicit,
            interpretation: ChannelInterpretation::Discrete,
        }
        .into()
    }

    fn number_of_inputs(&self) -> u32 {
        0
    }

    fn number_of_outputs(&self) -> u32 {
        9 // return all audio params as output
    }

    fn channel_count_mode(&self) -> ChannelCountMode {
        ChannelCountMode::Explicit
    }

    fn channel_interpretation(&self) -> ChannelInterpretation {
        ChannelInterpretation::Discrete
    }

    fn channel_count(&self) -> usize {
        1
    }
}

impl AudioListenerNode {
    pub fn new<C: BaseAudioContext>(context: &C) -> Self {
        context.base().register(move |registration| {
            let reg_id = registration.id();
            let base = context.base();

            let forward_z_opts = AudioParamDescriptor {
                default_value: -1.,
                ..PARAM_OPTS
            };
            let up_y_opts = AudioParamDescriptor {
                default_value: 1.,
                ..PARAM_OPTS
            };

            let (p1, v1) = base.create_audio_param(PARAM_OPTS, reg_id);
            let (p2, v2) = base.create_audio_param(PARAM_OPTS, reg_id);
            let (p3, v3) = base.create_audio_param(PARAM_OPTS, reg_id);
            let (p4, v4) = base.create_audio_param(PARAM_OPTS, reg_id);
            let (p5, v5) = base.create_audio_param(PARAM_OPTS, reg_id);
            let (p6, v6) = base.create_audio_param(forward_z_opts, reg_id);
            let (p7, v7) = base.create_audio_param(PARAM_OPTS, reg_id);
            let (p8, v8) = base.create_audio_param(up_y_opts, reg_id);
            let (p9, v9) = base.create_audio_param(PARAM_OPTS, reg_id);

            let node = Self {
                registration,
                fields: AudioListener {
                    position_x: p1,
                    position_y: p2,
                    position_z: p3,
                    forward_x: p4,
                    forward_y: p5,
                    forward_z: p6,
                    up_x: p7,
                    up_y: p8,
                    up_z: p9,
                },
            };
            let proc = ListenerRenderer {
                position_x: v1,
                position_y: v2,
                position_z: v3,
                forward_x: v4,
                forward_y: v5,
                forward_z: v6,
                up_x: v7,
                up_y: v8,
                up_z: v9,
            };

            (node, Box::new(proc))
        })
    }

    pub fn into_fields(self) -> AudioListener {
        self.fields
    }
}

struct ListenerRenderer {
    position_x: AudioParamId,
    position_y: AudioParamId,
    position_z: AudioParamId,
    forward_x: AudioParamId,
    forward_y: AudioParamId,
    forward_z: AudioParamId,
    up_x: AudioParamId,
    up_y: AudioParamId,
    up_z: AudioParamId,
}

impl AudioProcessor for ListenerRenderer {
    fn process(
        &mut self,
        _inputs: &[AudioRenderQuantum],
        outputs: &mut [AudioRenderQuantum],
        params: AudioParamValues,
        _timestamp: f64,
        _sample_rate: SampleRate,
    ) -> bool {
        // for now: persist param values in output, so PannerNodes have access
        outputs[0] = params.get_raw(&self.position_x).clone();
        outputs[1] = params.get_raw(&self.position_y).clone();
        outputs[2] = params.get_raw(&self.position_z).clone();
        outputs[3] = params.get_raw(&self.forward_x).clone();
        outputs[4] = params.get_raw(&self.forward_y).clone();
        outputs[5] = params.get_raw(&self.forward_z).clone();
        outputs[6] = params.get_raw(&self.up_x).clone();
        outputs[7] = params.get_raw(&self.up_y).clone();
        outputs[8] = params.get_raw(&self.up_z).clone();

        true // has intrinsic value
    }
}

/// Data holder for the BaseAudioContext so it can reconstruct the AudioListener on request
pub(crate) struct AudioListenerParams {
    pub position_x: AudioParamRaw,
    pub position_y: AudioParamRaw,
    pub position_z: AudioParamRaw,
    pub forward_x: AudioParamRaw,
    pub forward_y: AudioParamRaw,
    pub forward_z: AudioParamRaw,
    pub up_x: AudioParamRaw,
    pub up_y: AudioParamRaw,
    pub up_z: AudioParamRaw,
}

use vecmath::{
    vec3_cross, vec3_dot, vec3_len, vec3_normalized, vec3_scale, vec3_square_len, vec3_sub, Vector3,
};

/// Direction to source position measured from listener in 3D
pub fn azimuth_and_elevation(
    source_position: Vector3<f32>,
    listener_position: Vector3<f32>,
    listener_forward: Vector3<f32>,
    listener_up: Vector3<f32>,
) -> (f32, f32) {
    let relative_pos = vec3_sub(source_position, listener_position);

    // Handle degenerate case if source and listener are at the same point.
    if vec3_square_len(relative_pos) <= f32::MIN_POSITIVE {
        return (0., 0.);
    }

    // Calculate the source-listener vector.
    let source_listener = vec3_normalized(relative_pos);

    // Align axes.
    let listener_right = vec3_cross(listener_forward, listener_up);

    if vec3_square_len(listener_right) == 0. {
        // Handle the case where listener’s 'up' and 'forward' vectors are linearly dependent, in
        // which case 'right' cannot be determined
        return (0., 0.);
    }

    // Determine a unit vector orthogonal to listener’s right, forward
    let listener_right_norm = vec3_normalized(listener_right);
    let listener_forward_norm = vec3_normalized(listener_forward);
    let up = vec3_cross(listener_right_norm, listener_forward_norm);

    // Determine elevation first
    let mut elevation = 90. - 180. * vec3_dot(source_listener, up).acos() / PI;
    if elevation > 90. {
        elevation = 180. - elevation;
    } else if elevation < -90. {
        elevation = -180. - elevation;
    }

    let up_projection = vec3_dot(source_listener, up);
    let projected_source = vec3_sub(source_listener, vec3_scale(up, up_projection));

    // this case is not handled by the spec, so I stole the solution from
    // https://hg.mozilla.org/mozilla-central/rev/1100a5bc013b541c635bc42bd753531e95c952e4
    if vec3_square_len(projected_source) == 0. {
        return (0., elevation);
    }
    let projected_source = vec3_normalized(projected_source);

    let mut azimuth = 180. * vec3_dot(projected_source, listener_right_norm).acos() / PI;

    // Source in front or behind the listener.
    let front_back = vec3_dot(projected_source, listener_forward_norm);
    if front_back < 0. {
        azimuth = 360. - azimuth;
    }

    // Make azimuth relative to "forward" and not "right" listener vector.
    let max270 = std::ops::RangeInclusive::new(0., 270.);
    if max270.contains(&azimuth) {
        azimuth = 90. - azimuth;
    } else {
        azimuth = 450. - azimuth;
    }

    (azimuth, elevation)
}

/// Distance between two points in 3D
pub fn distance(source_position: Vector3<f32>, listener_position: Vector3<f32>) -> f32 {
    vec3_len(vec3_sub(source_position, listener_position))
}

/// Angle between two vectors in 3D
pub fn angle(
    source_position: Vector3<f32>,
    source_orientation: Vector3<f32>,
    listener_position: Vector3<f32>,
) -> f32 {
    // handle edge case of missing source orientation
    if vec3_square_len(source_orientation) == 0. {
        return 0.;
    }
    let normalized_source_orientation = vec3_normalized(source_orientation);

    let relative_pos = vec3_sub(source_position, listener_position);
    // Handle degenerate case if source and listener are at the same point.
    if vec3_square_len(relative_pos) <= f32::MIN_POSITIVE {
        return 0.;
    }
    // Calculate the source-listener vector.
    let source_listener = vec3_normalized(relative_pos);

    let angle = 180. * vec3_dot(source_listener, normalized_source_orientation).acos() / PI;
    angle.abs()
}

#[cfg(test)]
mod tests {
    use float_eq::assert_float_eq;

    use super::*;

    // listener coordinates/directions
    const LP: [f32; 3] = [0., 0., 0.];
    const LF: [f32; 3] = [0., 0., -1.];
    const LU: [f32; 3] = [0., 1., 0.];

    #[test]
    fn azimuth_elevation_equal_pos() {
        let pos = [0., 0., 0.];
        let (azimuth, elevation) = azimuth_and_elevation(pos, LP, LF, LU);

        assert_float_eq!(azimuth, 0., abs <= 0.);
        assert_float_eq!(elevation, 0., abs <= 0.);
    }

    #[test]
    fn azimuth_elevation_horizontal_plane() {
        // horizontal plane is spanned by x-z axes

        let pos = [10., 0., 0.];
        let (azimuth, elevation) = azimuth_and_elevation(pos, LP, LF, LU);
        assert_float_eq!(azimuth, 90., abs <= 0.001);
        assert_float_eq!(elevation, 0., abs <= 0.);

        let pos = [-10., 0., 0.];
        let (azimuth, elevation) = azimuth_and_elevation(pos, LP, LF, LU);
        assert_float_eq!(azimuth, -90., abs <= 0.001);
        assert_float_eq!(elevation, 0., abs <= 0.);

        let pos = [10., 0., -10.];
        let (azimuth, elevation) = azimuth_and_elevation(pos, LP, LF, LU);
        assert_float_eq!(azimuth, 45., abs <= 0.001);
        assert_float_eq!(elevation, 0., abs <= 0.);

        let pos = [-10., 0., -10.];
        let (azimuth, elevation) = azimuth_and_elevation(pos, LP, LF, LU);
        assert_float_eq!(azimuth, -45., abs <= 0.001);
        assert_float_eq!(elevation, 0., abs <= 0.);
    }

    #[test]
    fn azimuth_elevation_vertical() {
        let pos = [0., -10., 0.];
        let (azimuth, elevation) = azimuth_and_elevation(pos, LP, LF, LU);
        assert_float_eq!(azimuth, 0., abs <= 0.001);
        assert_float_eq!(elevation, -90., abs <= 0.001);

        let pos = [0., 10., 0.];
        let (azimuth, elevation) = azimuth_and_elevation(pos, LP, LF, LU);
        assert_float_eq!(azimuth, 0., abs <= 0.001);
        assert_float_eq!(elevation, 90., abs <= 0.001);
    }

    #[test]
    fn angle_equal_pos() {
        let pos = [0., 0., 0.];
        let orientation = [1., 0., 0.];
        let angle = angle(pos, orientation, LP);

        assert_float_eq!(angle, 0., abs <= 0.);
    }

    #[test]
    fn angle_no_orientation() {
        let pos = [10., 0., 0.];
        let orientation = [0., 0., 0.];
        let angle = angle(pos, orientation, LP);

        assert_float_eq!(angle, 0., abs <= 0.);
    }

    #[test]
    fn test_angle() {
        let pos = [1., 0., 0.];
        let orientation = [0., 1., 0.];
        let angle = angle(pos, orientation, LP);

        assert_float_eq!(angle, 90., abs <= 0.);
    }

    #[test]
    fn test_angle_abs_value() {
        let pos = [1., 0., 0.];
        let orientation = [0., -1., 0.];
        let angle = angle(pos, orientation, LP);

        assert_float_eq!(angle, 90., abs <= 0.);
    }
}