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
use crate::analysis::{
    Analyser, AnalyserRingBuffer, DEFAULT_FFT_SIZE, DEFAULT_MAX_DECIBELS, DEFAULT_MIN_DECIBELS,
    DEFAULT_SMOOTHING_TIME_CONSTANT,
};
use crate::context::{AudioContextRegistration, BaseAudioContext};
use crate::render::{AudioParamValues, AudioProcessor, AudioRenderQuantum, RenderScope};

use super::{AudioNode, ChannelConfig, ChannelConfigOptions, ChannelInterpretation};

/// Options for constructing an [`AnalyserNode`]
// dictionary AnalyserOptions : AudioNodeOptions {
//   unsigned long fftSize = 2048;
//   double maxDecibels = -30;
//   double minDecibels = -100;
//   double smoothingTimeConstant = 0.8;
// };
#[derive(Clone, Debug)]
pub struct AnalyserOptions {
    pub fft_size: usize,
    pub max_decibels: f64,
    pub min_decibels: f64,
    pub smoothing_time_constant: f64,
    pub channel_config: ChannelConfigOptions,
}

impl Default for AnalyserOptions {
    fn default() -> Self {
        Self {
            fft_size: DEFAULT_FFT_SIZE,
            max_decibels: DEFAULT_MAX_DECIBELS,
            min_decibels: DEFAULT_MIN_DECIBELS,
            smoothing_time_constant: DEFAULT_SMOOTHING_TIME_CONSTANT,
            channel_config: ChannelConfigOptions::default(),
        }
    }
}

/// `AnalyserNode` represents a node able to provide real-time frequency and
/// time-domain analysis information.
///
/// It is an AudioNode that passes the audio stream unchanged from the input to
/// the output, but allows you to take the generated data, process it, and create
/// audio visualizations..
///
/// - MDN documentation: <https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode>
/// - specification: <https://webaudio.github.io/web-audio-api/#AnalyserNode>
/// - see also: [`BaseAudioContext::create_analyser`]
///
/// # Usage
///
/// ```no_run
/// use web_audio_api::context::{BaseAudioContext, AudioContext};
/// use web_audio_api::node::{AudioNode, AudioScheduledSourceNode};
///
/// let context = AudioContext::default();
///
/// let mut analyser = context.create_analyser();
/// analyser.connect(&context.destination());
///
/// let mut osc = context.create_oscillator();
/// osc.frequency().set_value(200.);
/// osc.connect(&analyser);
/// osc.start();
///
/// let mut bins = vec![0.; analyser.frequency_bin_count()];
///
///
/// loop {
///     analyser.get_float_frequency_data(&mut bins);
///     println!("{:?}", &bins[0..20]); // print 20 first bins
///     std::thread::sleep(std::time::Duration::from_millis(1000));
/// }
/// ```
///
/// # Examples
///
/// - `cargo run --release --example analyser`
/// - `cd showcase/mic_playback && cargo run --release`
///
pub struct AnalyserNode {
    registration: AudioContextRegistration,
    channel_config: ChannelConfig,
    analyser: Analyser,
}

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

    fn channel_config(&self) -> &ChannelConfig {
        &self.channel_config
    }

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

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

impl AnalyserNode {
    pub fn new<C: BaseAudioContext>(context: &C, options: AnalyserOptions) -> Self {
        context.register(move |registration| {
            let fft_size = options.fft_size;
            let smoothing_time_constant = options.smoothing_time_constant;
            let min_decibels = options.min_decibels;
            let max_decibels = options.max_decibels;

            let mut analyser = Analyser::new();
            analyser.set_fft_size(fft_size);
            analyser.set_smoothing_time_constant(smoothing_time_constant);
            analyser.set_min_decibels(min_decibels);
            analyser.set_max_decibels(max_decibels);

            let render = AnalyserRenderer {
                ring_buffer: analyser.get_ring_buffer_clone(),
            };

            let node = AnalyserNode {
                registration,
                channel_config: options.channel_config.into(),
                analyser,
            };

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

    /// The size of the FFT used for frequency-domain analysis (in sample-frames)
    ///
    /// # Panics
    ///
    /// This method may panic if the lock to the inner analyser is poisoned
    pub fn fft_size(&self) -> usize {
        self.analyser.fft_size()
    }

    /// Set FFT size
    ///
    /// # Panics
    ///
    /// This function panics if fft_size is not a power of two or not in the range [32, 32768]
    pub fn set_fft_size(&mut self, fft_size: usize) {
        self.analyser.set_fft_size(fft_size);
    }

    /// Time averaging parameter with the last analysis frame.
    /// A value from 0 -> 1 where 0 represents no time averaging with the last
    /// analysis frame. The default value is 0.8.
    ///
    /// # Panics
    ///
    /// This method may panic if the lock to the inner analyser is poisoned
    pub fn smoothing_time_constant(&self) -> f64 {
        self.analyser.smoothing_time_constant()
    }

    /// Set smoothing time constant
    ///
    /// # Panics
    ///
    /// This function panics if the value is set to a value less than 0 or more than 1.
    pub fn set_smoothing_time_constant(&mut self, value: f64) {
        self.analyser.set_smoothing_time_constant(value);
    }

    /// Minimum power value in the scaling range for the FFT analysis data for
    /// conversion to unsigned byte values. The default value is -100.
    ///
    /// # Panics
    ///
    /// This method may panic if the lock to the inner analyser is poisoned
    pub fn min_decibels(&self) -> f64 {
        self.analyser.min_decibels()
    }

    /// Set min decibels
    ///
    /// # Panics
    ///
    /// This function panics if the value is set to a value more than or equal
    /// to max decibels.
    pub fn set_min_decibels(&mut self, value: f64) {
        self.analyser.set_min_decibels(value);
    }

    /// Maximum power value in the scaling range for the FFT analysis data for
    /// conversion to unsigned byte values. The default value is -30.
    ///
    /// # Panics
    ///
    /// This method may panic if the lock to the inner analyser is poisoned
    pub fn max_decibels(&self) -> f64 {
        self.analyser.max_decibels()
    }

    /// Set max decibels
    ///
    /// # Panics
    ///
    /// This function panics if the value is set to a value less than or equal
    /// to min decibels.
    pub fn set_max_decibels(&mut self, value: f64) {
        self.analyser.set_max_decibels(value);
    }

    /// Number of bins in the FFT results, is half the FFT size
    ///
    /// # Panics
    ///
    /// This method may panic if the lock to the inner analyser is poisoned
    pub fn frequency_bin_count(&self) -> usize {
        self.analyser.frequency_bin_count()
    }

    /// Copy the current time domain data as f32 values into the provided buffer
    ///
    /// # Panics
    ///
    /// This method may panic if the lock to the inner analyser is poisoned
    pub fn get_float_time_domain_data(&mut self, buffer: &mut [f32]) {
        self.analyser.get_float_time_domain_data(buffer);
    }

    /// Copy the current time domain data as u8 values into the provided buffer
    ///
    /// # Panics
    ///
    /// This method may panic if the lock to the inner analyser is poisoned
    pub fn get_byte_time_domain_data(&mut self, buffer: &mut [u8]) {
        self.analyser.get_byte_time_domain_data(buffer);
    }

    /// Copy the current frequency data into the provided buffer
    ///
    /// # Panics
    ///
    /// This method may panic if the lock to the inner analyser is poisoned
    pub fn get_float_frequency_data(&mut self, buffer: &mut [f32]) {
        let current_time = self.registration.context().current_time();
        self.analyser.get_float_frequency_data(buffer, current_time);
    }

    /// Copy the current frequency data scaled between min_decibels and
    /// max_decibels into the provided buffer
    ///
    /// # Panics
    ///
    /// This method may panic if the lock to the inner analyser is poisoned
    pub fn get_byte_frequency_data(&mut self, buffer: &mut [u8]) {
        let current_time = self.registration.context().current_time();
        self.analyser.get_byte_frequency_data(buffer, current_time);
    }
}

struct AnalyserRenderer {
    ring_buffer: AnalyserRingBuffer,
}

impl AudioProcessor for AnalyserRenderer {
    fn process(
        &mut self,
        inputs: &[AudioRenderQuantum],
        outputs: &mut [AudioRenderQuantum],
        _params: AudioParamValues<'_>,
        _scope: &RenderScope,
    ) -> bool {
        // single input/output node
        let input = &inputs[0];
        let output = &mut outputs[0];

        // pass through input
        *output = input.clone();

        // down mix to mono
        let mut mono = input.clone();
        mono.mix(1, ChannelInterpretation::Speakers);

        // add current input to ring buffer
        let data = mono.channel_data(0).as_ref();
        self.ring_buffer.write(data);

        // no tail-time
        false
    }
}