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
use block::{Block, Chunk, Tick, FRAMES_PER_BLOCK};
use euclid::default::Vector3D;
use node::{AudioNodeEngine, AudioNodeMessage, BlockInfo};
use node::{AudioNodeType, ChannelInfo};
use param::{Param, ParamDir, ParamType};
use std::f32::consts::PI;

// .normalize(), but it takes into account zero vectors
pub fn normalize_zero(v: Vector3D<f32>) -> Vector3D<f32> {
    let len = v.length();
    if len == 0. {
        v
    } else {
        v / len
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum PanningModel {
    EqualPower,
    HRTF,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DistanceModel {
    Linear,
    Inverse,
    Exponential,
}

#[derive(Copy, Clone, Debug)]
pub struct PannerNodeOptions {
    pub panning_model: PanningModel,
    pub distance_model: DistanceModel,
    pub position_x: f32,
    pub position_y: f32,
    pub position_z: f32,
    pub orientation_x: f32,
    pub orientation_y: f32,
    pub orientation_z: f32,
    pub ref_distance: f64,
    pub max_distance: f64,
    pub rolloff_factor: f64,
    pub cone_inner_angle: f64,
    pub cone_outer_angle: f64,
    pub cone_outer_gain: f64,
}

pub enum PannerNodeMessage {
    SetPanningModel(PanningModel),
    SetDistanceModel(DistanceModel),
    SetRefDistance(f64),
    SetMaxDistance(f64),
    SetRolloff(f64),
    SetConeInner(f64),
    SetConeOuter(f64),
    SetConeGain(f64),
}

impl Default for PannerNodeOptions {
    fn default() -> Self {
        PannerNodeOptions {
            panning_model: PanningModel::EqualPower,
            distance_model: DistanceModel::Inverse,
            position_x: 0.,
            position_y: 0.,
            position_z: 0.,
            orientation_x: 1.,
            orientation_y: 0.,
            orientation_z: 0.,
            ref_distance: 1.,
            max_distance: 10000.,
            rolloff_factor: 1.,
            cone_inner_angle: 360.,
            cone_outer_angle: 360.,
            cone_outer_gain: 0.,
        }
    }
}

#[derive(AudioNodeCommon)]
pub(crate) struct PannerNode {
    channel_info: ChannelInfo,
    panning_model: PanningModel,
    distance_model: DistanceModel,
    position_x: Param,
    position_y: Param,
    position_z: Param,
    orientation_x: Param,
    orientation_y: Param,
    orientation_z: Param,
    ref_distance: f64,
    max_distance: f64,
    rolloff_factor: f64,
    cone_inner_angle: f64,
    cone_outer_angle: f64,
    cone_outer_gain: f64,
    listener_data: Option<Block>,
}

impl PannerNode {
    pub fn new(options: PannerNodeOptions, channel_info: ChannelInfo) -> Self {
        if options.panning_model == PanningModel::HRTF {
            log::warn!("HRTF requested but not supported")
        }
        Self {
            channel_info,
            panning_model: options.panning_model,
            distance_model: options.distance_model,
            position_x: Param::new(options.position_x),
            position_y: Param::new(options.position_y),
            position_z: Param::new(options.position_z),
            orientation_x: Param::new(options.orientation_x),
            orientation_y: Param::new(options.orientation_y),
            orientation_z: Param::new(options.orientation_z),
            ref_distance: options.ref_distance,
            max_distance: options.max_distance,
            rolloff_factor: options.rolloff_factor,
            cone_inner_angle: options.cone_inner_angle,
            cone_outer_angle: options.cone_outer_angle,
            cone_outer_gain: options.cone_outer_gain,
            listener_data: None,
        }
    }

    pub fn update_parameters(&mut self, info: &BlockInfo, tick: Tick) -> bool {
        let mut changed = self.position_x.update(info, tick);
        changed |= self.position_y.update(info, tick);
        changed |= self.position_z.update(info, tick);
        changed |= self.orientation_x.update(info, tick);
        changed |= self.orientation_y.update(info, tick);
        changed |= self.orientation_z.update(info, tick);
        changed
    }

    /// Computes azimuth, elevation, and distance of source with respect to a
    /// given AudioListener's position, forward, and up vectors
    /// in degrees
    ///
    /// https://webaudio.github.io/web-audio-api/#azimuth-elevation
    /// https://webaudio.github.io/web-audio-api/#Spatialization-distance-effects
    fn azimuth_elevation_distance(
        &self,
        listener: (Vector3D<f32>, Vector3D<f32>, Vector3D<f32>),
    ) -> (f32, f32, f64) {
        let (listener_position, listener_forward, listener_up) = listener;
        let source_position = Vector3D::new(
            self.position_x.value(),
            self.position_y.value(),
            self.position_z.value(),
        );

        // degenerate case
        if source_position == listener_position {
            return (0., 0., 0.);
        }

        let diff = source_position - listener_position;
        let distance = diff.length();
        let source_listener = normalize_zero(diff);
        let listener_right = listener_forward.cross(listener_up);
        let listener_right_norm = normalize_zero(listener_right);
        let listener_forward_norm = normalize_zero(listener_forward);

        let up = listener_right_norm.cross(listener_forward_norm);

        let up_projection = source_listener.dot(up);
        let projected_source = normalize_zero(source_listener - up * up_projection);
        let mut azimuth = 180. * projected_source.dot(listener_right_norm).acos() / PI;

        let front_back = projected_source.dot(listener_forward_norm);
        if front_back < 0. {
            azimuth = 360. - azimuth;
        }
        if (azimuth >= 0.) && (azimuth <= 270.) {
            azimuth = 90. - azimuth;
        } else {
            azimuth = 450. - azimuth;
        }

        let mut elevation = 90. - 180. * source_listener.dot(up).acos() / PI;

        if elevation > 90. {
            elevation = 180. - elevation;
        } else if elevation < -90. {
            elevation = -180. - elevation;
        }

        (azimuth, elevation, distance as f64)
    }

    /// https://webaudio.github.io/web-audio-api/#Spatialization-sound-cones
    fn cone_gain(&self, listener: (Vector3D<f32>, Vector3D<f32>, Vector3D<f32>)) -> f64 {
        let (listener_position, _, _) = listener;
        let source_position = Vector3D::new(
            self.position_x.value(),
            self.position_y.value(),
            self.position_z.value(),
        );
        let source_orientation = Vector3D::new(
            self.orientation_x.value(),
            self.orientation_y.value(),
            self.orientation_z.value(),
        );

        if source_orientation == Vector3D::zero()
            || (self.cone_inner_angle == 360. && self.cone_outer_angle == 360.)
        {
            return 0.;
        }

        let normalized_source_orientation = normalize_zero(source_orientation);

        let source_to_listener = normalize_zero(source_position - listener_position);
        // Angle between the source orientation vector and the source-listener vector
        let angle = 180. * source_to_listener.dot(normalized_source_orientation).acos() / PI;
        let abs_angle = angle.abs() as f64;

        // Divide by 2 here since API is entire angle (not half-angle)
        let abs_inner_angle = self.cone_inner_angle.abs() / 2.;
        let abs_outer_angle = self.cone_outer_angle.abs() / 2.;

        if abs_angle < abs_inner_angle {
            // no attenuation
            1.
        } else if abs_angle >= abs_outer_angle {
            // max attenuation
            self.cone_outer_gain
        } else {
            // gain changes linearly from 1 to cone_outer_gain
            // as we go from inner to outer
            let x = (abs_angle - abs_inner_angle) / (abs_outer_angle - abs_inner_angle);
            (1. - x) + self.cone_outer_gain * x
        }
    }

    fn linear_distance(&self, mut distance: f64, rolloff_factor: f64) -> f64 {
        if distance > self.max_distance {
            distance = self.max_distance;
        }
        if distance < self.ref_distance {
            distance = self.ref_distance;
        }
        let denom = self.max_distance - self.ref_distance;
        1. - rolloff_factor * (distance - self.ref_distance) / denom
    }

    fn inverse_distance(&self, mut distance: f64, rolloff_factor: f64) -> f64 {
        if distance < self.ref_distance {
            distance = self.ref_distance;
        }
        let denom = self.ref_distance + rolloff_factor * (distance - self.ref_distance);
        self.ref_distance / denom
    }

    fn exponential_distance(&self, mut distance: f64, rolloff_factor: f64) -> f64 {
        if distance < self.ref_distance {
            distance = self.ref_distance;
        }

        (distance / self.ref_distance).powf(-rolloff_factor)
    }

    fn distance_gain_fn(&self) -> fn(&Self, f64, f64) -> f64 {
        match self.distance_model {
            DistanceModel::Linear => |x, d, r| x.linear_distance(d, r),
            DistanceModel::Inverse => |x, d, r| x.inverse_distance(d, r),
            DistanceModel::Exponential => |x, d, r| x.exponential_distance(d, r),
        }
    }
}

impl AudioNodeEngine for PannerNode {
    fn node_type(&self) -> AudioNodeType {
        AudioNodeType::PannerNode
    }

    fn process(&mut self, mut inputs: Chunk, info: &BlockInfo) -> Chunk {
        debug_assert!(inputs.len() == 1);

        let listener_data = if let Some(listener_data) = self.listener_data.take() {
            listener_data
        } else {
            return inputs;
        };

        // We clamp this early
        let rolloff_factor =
            if self.distance_model == DistanceModel::Linear && self.rolloff_factor > 1. {
                1.
            } else {
                self.rolloff_factor
            };

        {
            let block = &mut inputs.blocks[0];

            block.explicit_repeat();

            let mono = if block.chan_count() == 1 {
                block.resize_silence(2);
                true
            } else {
                debug_assert!(block.chan_count() == 2);
                false
            };

            let distance_gain_fn = self.distance_gain_fn();

            if self.panning_model == PanningModel::EqualPower {
                let (l, r) = block.data_mut().split_at_mut(FRAMES_PER_BLOCK.0 as usize);
                for frame in 0..FRAMES_PER_BLOCK.0 {
                    let frame = Tick(frame);
                    self.update_parameters(info, frame);
                    let data = listener_data.listener_data(frame);
                    let (mut azimuth, _elev, dist) = self.azimuth_elevation_distance(data);
                    let distance_gain = distance_gain_fn(self, dist, rolloff_factor);
                    let cone_gain = self.cone_gain(data);

                    // https://webaudio.github.io/web-audio-api/#Spatialization-equal-power-panning

                    // clamp to [-180, 180], then wrap to [-90, 90]
                    if azimuth < -180. {
                        azimuth = -180.
                    } else if azimuth > 180. {
                        azimuth = 180.
                    }
                    if azimuth < -90. {
                        azimuth = -180. - azimuth;
                    } else if azimuth > 90. {
                        azimuth = 180. - azimuth;
                    }

                    let x = if mono {
                        (azimuth + 90.) / 180.
                    } else if azimuth <= 0. {
                        (azimuth + 90.) / 90.
                    } else {
                        azimuth / 90.
                    };
                    let x = x * PI / 2.;

                    let mut gain_l = x.cos();
                    let mut gain_r = x.sin();
                    // 9. * PI / 2 is often slightly negative, clamp
                    if gain_l <= 0. {
                        gain_l = 0.
                    }
                    if gain_r <= 0. {
                        gain_r = 0.;
                    }

                    let index = frame.0 as usize;
                    if mono {
                        let input = l[index];
                        l[index] = input * gain_l;
                        r[index] = input * gain_r;
                    } else if azimuth <= 0. {
                        l[index] = l[index] + r[index] * gain_l;
                        r[index] = r[index] * gain_r;
                    } else {
                        r[index] = r[index] + l[index] * gain_r;
                        l[index] = l[index] * gain_l;
                    }
                    l[index] = l[index] * distance_gain as f32 * cone_gain as f32;
                    r[index] = r[index] * distance_gain as f32 * cone_gain as f32;
                }
            }
        }

        inputs
    }

    fn input_count(&self) -> u32 {
        1
    }

    fn get_param(&mut self, id: ParamType) -> &mut Param {
        match id {
            ParamType::Position(ParamDir::X) => &mut self.position_x,
            ParamType::Position(ParamDir::Y) => &mut self.position_y,
            ParamType::Position(ParamDir::Z) => &mut self.position_z,
            ParamType::Orientation(ParamDir::X) => &mut self.orientation_x,
            ParamType::Orientation(ParamDir::Y) => &mut self.orientation_y,
            ParamType::Orientation(ParamDir::Z) => &mut self.orientation_z,
            _ => panic!("Unknown param {:?} for PannerNode", id),
        }
    }

    fn set_listenerdata(&mut self, data: Block) {
        self.listener_data = Some(data);
    }

    fn message_specific(&mut self, message: AudioNodeMessage, _sample_rate: f32) {
        match message {
            AudioNodeMessage::PannerNode(p) => match p {
                PannerNodeMessage::SetPanningModel(p) => {
                    if p == PanningModel::HRTF {
                        log::warn!("HRTF requested but not supported");
                    }
                    self.panning_model = p;
                }
                PannerNodeMessage::SetDistanceModel(d) => self.distance_model = d,
                PannerNodeMessage::SetRefDistance(val) => self.ref_distance = val,
                PannerNodeMessage::SetMaxDistance(val) => self.max_distance = val,
                PannerNodeMessage::SetRolloff(val) => self.rolloff_factor = val,
                PannerNodeMessage::SetConeInner(val) => self.cone_inner_angle = val,
                PannerNodeMessage::SetConeOuter(val) => self.cone_outer_angle = val,
                PannerNodeMessage::SetConeGain(val) => self.cone_outer_gain = val,
            },
            _ => (),
        }
    }
}