summaryrefslogtreecommitdiffstats
path: root/chromium/third_party/blink/renderer/modules/webaudio/analyser_node.cc
blob: cb281f5b728f737ce0a07c289d09c06a17205dd0 (plain)
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
/*
 * Copyright (C) 2010, Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1.  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */

#include "third_party/blink/renderer/modules/webaudio/analyser_node.h"

#include "third_party/blink/renderer/bindings/modules/v8/v8_analyser_options.h"
#include "third_party/blink/renderer/modules/webaudio/audio_node_input.h"
#include "third_party/blink/renderer/modules/webaudio/audio_node_output.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"

namespace blink {

AnalyserHandler::AnalyserHandler(AudioNode& node, float sample_rate)
    : AudioBasicInspectorHandler(kNodeTypeAnalyser, node, sample_rate) {
  channel_count_ = 2;
  AddOutput(1);

  Initialize();
}

scoped_refptr<AnalyserHandler> AnalyserHandler::Create(AudioNode& node,
                                                       float sample_rate) {
  return base::AdoptRef(new AnalyserHandler(node, sample_rate));
}

AnalyserHandler::~AnalyserHandler() {
  Uninitialize();
}

void AnalyserHandler::Process(uint32_t frames_to_process) {
  AudioBus* output_bus = Output(0).Bus();

  if (!IsInitialized()) {
    output_bus->Zero();
    return;
  }

  scoped_refptr<AudioBus> input_bus = Input(0).Bus();

  // Give the analyser the audio which is passing through this
  // AudioNode.  This must always be done so that the state of the
  // Analyser reflects the current input.
  analyser_.WriteInput(input_bus.get(), frames_to_process);

  if (!Input(0).IsConnected()) {
    // No inputs, so clear the output, and propagate the silence hint.
    output_bus->Zero();
    return;
  }

  // For in-place processing, our override of pullInputs() will just pass the
  // audio data through unchanged if the channel count matches from input to
  // output (resulting in inputBus == outputBus). Otherwise, do an up-mix to
  // stereo.
  if (input_bus != output_bus)
    output_bus->CopyFrom(*input_bus);
}

void AnalyserHandler::SetFftSize(unsigned size,
                                 ExceptionState& exception_state) {
  if (!analyser_.SetFftSize(size)) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        (size < RealtimeAnalyser::kMinFFTSize ||
         size > RealtimeAnalyser::kMaxFFTSize)
            ? ExceptionMessages::IndexOutsideRange(
                  "FFT size", size, RealtimeAnalyser::kMinFFTSize,
                  ExceptionMessages::kInclusiveBound,
                  RealtimeAnalyser::kMaxFFTSize,
                  ExceptionMessages::kInclusiveBound)
            : ("The value provided (" + String::Number(size) +
               ") is not a power of two."));
  }
}

void AnalyserHandler::SetMinDecibels(double k,
                                     ExceptionState& exception_state) {
  if (k < MaxDecibels()) {
    analyser_.SetMinDecibels(k);
  } else {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        ExceptionMessages::IndexExceedsMaximumBound("minDecibels", k,
                                                    MaxDecibels()));
  }
}

void AnalyserHandler::SetMaxDecibels(double k,
                                     ExceptionState& exception_state) {
  if (k > MinDecibels()) {
    analyser_.SetMaxDecibels(k);
  } else {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        ExceptionMessages::IndexExceedsMinimumBound("maxDecibels", k,
                                                    MinDecibels()));
  }
}

void AnalyserHandler::SetMinMaxDecibels(double min_decibels,
                                        double max_decibels,
                                        ExceptionState& exception_state) {
  if (min_decibels >= max_decibels) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        "maxDecibels (" + String::Number(max_decibels) +
            ") must be greater than or equal to minDecibels " + "( " +
            String::Number(min_decibels) + ").");
    return;
  }
  analyser_.SetMinDecibels(min_decibels);
  analyser_.SetMaxDecibels(max_decibels);
}

void AnalyserHandler::SetSmoothingTimeConstant(
    double k,
    ExceptionState& exception_state) {
  if (k >= 0 && k <= 1) {
    analyser_.SetSmoothingTimeConstant(k);
  } else {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        ExceptionMessages::IndexOutsideRange(
            "smoothing value", k, 0.0, ExceptionMessages::kInclusiveBound, 1.0,
            ExceptionMessages::kInclusiveBound));
  }
}

void AnalyserHandler::UpdatePullStatusIfNeeded() {
  Context()->AssertGraphOwner();

  if (Output(0).IsConnected()) {
    // When an AudioBasicInspectorNode is connected to a downstream node, it
    // will get pulled by the downstream node, thus remove it from the context's
    // automatic pull list.
    if (need_automatic_pull_) {
      Context()->GetDeferredTaskHandler().RemoveAutomaticPullNode(this);
      need_automatic_pull_ = false;
    }
  } else {
    unsigned number_of_input_connections =
        Input(0).NumberOfRenderingConnections();
    // When an AnalyserNode is not connected to any downstream node
    // while still connected from upstream node(s), add it to the context's
    // automatic pull list.
    //
    // But don't remove the AnalyserNode if there are no inputs
    // connected to the node.  The node needs to be pulled so that the
    // internal state is updated with the correct input signal (of
    // zeroes).
    if (number_of_input_connections && !need_automatic_pull_) {
      Context()->GetDeferredTaskHandler().AddAutomaticPullNode(this);
      need_automatic_pull_ = true;
    }
  }
}

bool AnalyserHandler::RequiresTailProcessing() const {
  // Tail time is always non-zero so tail processing is required.
  return true;
}

double AnalyserHandler::TailTime() const {
  return RealtimeAnalyser::kMaxFFTSize /
         static_cast<double>(Context()->sampleRate());
}
// ----------------------------------------------------------------

AnalyserNode::AnalyserNode(BaseAudioContext& context)
    : AudioBasicInspectorNode(context) {
  SetHandler(AnalyserHandler::Create(*this, context.sampleRate()));
}

AnalyserNode* AnalyserNode::Create(BaseAudioContext& context,
                                   ExceptionState& exception_state) {
  DCHECK(IsMainThread());

  return MakeGarbageCollected<AnalyserNode>(context);
}

AnalyserNode* AnalyserNode::Create(BaseAudioContext* context,
                                   const AnalyserOptions* options,
                                   ExceptionState& exception_state) {
  DCHECK(IsMainThread());

  AnalyserNode* node = Create(*context, exception_state);

  if (!node)
    return nullptr;

  node->HandleChannelOptions(options, exception_state);

  node->setFftSize(options->fftSize(), exception_state);
  node->setSmoothingTimeConstant(options->smoothingTimeConstant(),
                                 exception_state);

  // minDecibels and maxDecibels have default values.  Set both of the values
  // at once.
  node->SetMinMaxDecibels(options->minDecibels(), options->maxDecibels(),
                          exception_state);

  return node;
}

AnalyserHandler& AnalyserNode::GetAnalyserHandler() const {
  return static_cast<AnalyserHandler&>(Handler());
}

unsigned AnalyserNode::fftSize() const {
  return GetAnalyserHandler().FftSize();
}

void AnalyserNode::setFftSize(unsigned size, ExceptionState& exception_state) {
  return GetAnalyserHandler().SetFftSize(size, exception_state);
}

unsigned AnalyserNode::frequencyBinCount() const {
  return GetAnalyserHandler().FrequencyBinCount();
}

void AnalyserNode::setMinDecibels(double min, ExceptionState& exception_state) {
  GetAnalyserHandler().SetMinDecibels(min, exception_state);
}

double AnalyserNode::minDecibels() const {
  return GetAnalyserHandler().MinDecibels();
}

void AnalyserNode::setMaxDecibels(double max, ExceptionState& exception_state) {
  GetAnalyserHandler().SetMaxDecibels(max, exception_state);
}

void AnalyserNode::SetMinMaxDecibels(double min,
                                     double max,
                                     ExceptionState& exception_state) {
  GetAnalyserHandler().SetMinMaxDecibels(min, max, exception_state);
}

double AnalyserNode::maxDecibels() const {
  return GetAnalyserHandler().MaxDecibels();
}

void AnalyserNode::setSmoothingTimeConstant(double smoothing_time,
                                            ExceptionState& exception_state) {
  GetAnalyserHandler().SetSmoothingTimeConstant(smoothing_time,
                                                exception_state);
}

double AnalyserNode::smoothingTimeConstant() const {
  return GetAnalyserHandler().SmoothingTimeConstant();
}

void AnalyserNode::getFloatFrequencyData(NotShared<DOMFloat32Array> array) {
  GetAnalyserHandler().GetFloatFrequencyData(array.View(),
                                             context()->currentTime());
}

void AnalyserNode::getByteFrequencyData(NotShared<DOMUint8Array> array) {
  GetAnalyserHandler().GetByteFrequencyData(array.View(),
                                            context()->currentTime());
}

void AnalyserNode::getFloatTimeDomainData(NotShared<DOMFloat32Array> array) {
  GetAnalyserHandler().GetFloatTimeDomainData(array.View());
}

void AnalyserNode::getByteTimeDomainData(NotShared<DOMUint8Array> array) {
  GetAnalyserHandler().GetByteTimeDomainData(array.View());
}

void AnalyserNode::ReportDidCreate() {
  GraphTracer().DidCreateAudioNode(this);
}

void AnalyserNode::ReportWillBeDestroyed() {
  GraphTracer().WillDestroyAudioNode(this);
}

}  // namespace blink