summaryrefslogtreecommitdiffstats
path: root/dom/media/webaudio/BiquadFilterNode.cpp
blob: 0c8c05586b3d24f6c32fb8dc45c64b2e1d280523 (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
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "BiquadFilterNode.h"
#include "AlignmentUtils.h"
#include "AudioNodeEngine.h"
#include "AudioNodeStream.h"
#include "AudioDestinationNode.h"
#include "PlayingRefChangeHandler.h"
#include "WebAudioUtils.h"
#include "blink/Biquad.h"
#include "mozilla/UniquePtr.h"
#include "AudioParamTimeline.h"

namespace mozilla {
namespace dom {

NS_IMPL_CYCLE_COLLECTION_INHERITED(BiquadFilterNode, AudioNode,
                                   mFrequency, mDetune, mQ, mGain)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(BiquadFilterNode)
NS_INTERFACE_MAP_END_INHERITING(AudioNode)

NS_IMPL_ADDREF_INHERITED(BiquadFilterNode, AudioNode)
NS_IMPL_RELEASE_INHERITED(BiquadFilterNode, AudioNode)

static void
SetParamsOnBiquad(WebCore::Biquad& aBiquad,
                  float aSampleRate,
                  BiquadFilterType aType,
                  double aFrequency,
                  double aQ,
                  double aGain,
                  double aDetune)
{
  const double nyquist = aSampleRate * 0.5;
  double normalizedFrequency = aFrequency / nyquist;

  if (aDetune) {
    normalizedFrequency *= std::pow(2.0, aDetune / 1200);
  }

  switch (aType) {
  case BiquadFilterType::Lowpass:
    aBiquad.setLowpassParams(normalizedFrequency, aQ);
    break;
  case BiquadFilterType::Highpass:
    aBiquad.setHighpassParams(normalizedFrequency, aQ);
    break;
  case BiquadFilterType::Bandpass:
    aBiquad.setBandpassParams(normalizedFrequency, aQ);
    break;
  case BiquadFilterType::Lowshelf:
    aBiquad.setLowShelfParams(normalizedFrequency, aGain);
    break;
  case BiquadFilterType::Highshelf:
    aBiquad.setHighShelfParams(normalizedFrequency, aGain);
    break;
  case BiquadFilterType::Peaking:
    aBiquad.setPeakingParams(normalizedFrequency, aQ, aGain);
    break;
  case BiquadFilterType::Notch:
    aBiquad.setNotchParams(normalizedFrequency, aQ);
    break;
  case BiquadFilterType::Allpass:
    aBiquad.setAllpassParams(normalizedFrequency, aQ);
    break;
  default:
    NS_NOTREACHED("We should never see the alternate names here");
    break;
  }
}

class BiquadFilterNodeEngine final : public AudioNodeEngine
{
public:
  BiquadFilterNodeEngine(AudioNode* aNode,
                         AudioDestinationNode* aDestination,
                         uint64_t aWindowID)
    : AudioNodeEngine(aNode)
    , mDestination(aDestination->Stream())
    // Keep the default values in sync with the default values in
    // BiquadFilterNode::BiquadFilterNode
    , mType(BiquadFilterType::Lowpass)
    , mFrequency(350.f)
    , mDetune(0.f)
    , mQ(1.f)
    , mGain(0.f)
    , mWindowID(aWindowID)
  {
  }

  enum Parameteres {
    TYPE,
    FREQUENCY,
    DETUNE,
    Q,
    GAIN
  };
  void SetInt32Parameter(uint32_t aIndex, int32_t aValue) override
  {
    switch (aIndex) {
    case TYPE: mType = static_cast<BiquadFilterType>(aValue); break;
    default:
      NS_ERROR("Bad BiquadFilterNode Int32Parameter");
    }
  }
  void RecvTimelineEvent(uint32_t aIndex,
                         AudioTimelineEvent& aEvent) override
  {
    MOZ_ASSERT(mDestination);

    WebAudioUtils::ConvertAudioTimelineEventToTicks(aEvent,
                                                    mDestination);

    switch (aIndex) {
    case FREQUENCY:
      mFrequency.InsertEvent<int64_t>(aEvent);
      break;
    case DETUNE:
      mDetune.InsertEvent<int64_t>(aEvent);
      break;
    case Q:
      mQ.InsertEvent<int64_t>(aEvent);
      break;
    case GAIN:
      mGain.InsertEvent<int64_t>(aEvent);
      break;
    default:
      NS_ERROR("Bad BiquadFilterNodeEngine TimelineParameter");
    }
  }

  void ProcessBlock(AudioNodeStream* aStream,
                    GraphTime aFrom,
                    const AudioBlock& aInput,
                    AudioBlock* aOutput,
                    bool* aFinished) override
  {
    float inputBuffer[WEBAUDIO_BLOCK_SIZE + 4];
    float* alignedInputBuffer = ALIGNED16(inputBuffer);
    ASSERT_ALIGNED16(alignedInputBuffer);

    if (aInput.IsNull()) {
      bool hasTail = false;
      for (uint32_t i = 0; i < mBiquads.Length(); ++i) {
        if (mBiquads[i].hasTail()) {
          hasTail = true;
          break;
        }
      }
      if (!hasTail) {
        if (!mBiquads.IsEmpty()) {
          mBiquads.Clear();
          aStream->ScheduleCheckForInactive();

          RefPtr<PlayingRefChangeHandler> refchanged =
            new PlayingRefChangeHandler(aStream, PlayingRefChangeHandler::RELEASE);
          aStream->Graph()->
            DispatchToMainThreadAfterStreamStateUpdate(refchanged.forget());
        }

        aOutput->SetNull(WEBAUDIO_BLOCK_SIZE);
        return;
      }

      PodArrayZero(inputBuffer);

    } else if(mBiquads.Length() != aInput.ChannelCount()){
      if (mBiquads.IsEmpty()) {
        RefPtr<PlayingRefChangeHandler> refchanged =
          new PlayingRefChangeHandler(aStream, PlayingRefChangeHandler::ADDREF);
        aStream->Graph()->
          DispatchToMainThreadAfterStreamStateUpdate(refchanged.forget());
      } else { // Help people diagnose bug 924718
        WebAudioUtils::LogToDeveloperConsole(mWindowID,
                                             "BiquadFilterChannelCountChangeWarning");
      }

      // Adjust the number of biquads based on the number of channels
      mBiquads.SetLength(aInput.ChannelCount());
    }

    uint32_t numberOfChannels = mBiquads.Length();
    aOutput->AllocateChannels(numberOfChannels);

    StreamTime pos = mDestination->GraphTimeToStreamTime(aFrom);

    double freq = mFrequency.GetValueAtTime(pos);
    double q = mQ.GetValueAtTime(pos);
    double gain = mGain.GetValueAtTime(pos);
    double detune = mDetune.GetValueAtTime(pos);

    for (uint32_t i = 0; i < numberOfChannels; ++i) {
      const float* input;
      if (aInput.IsNull()) {
        input = alignedInputBuffer;
      } else {
        input = static_cast<const float*>(aInput.mChannelData[i]);
        if (aInput.mVolume != 1.0) {
          AudioBlockCopyChannelWithScale(input, aInput.mVolume, alignedInputBuffer);
          input = alignedInputBuffer;
        }
      }
      SetParamsOnBiquad(mBiquads[i], aStream->SampleRate(), mType, freq, q, gain, detune);

      mBiquads[i].process(input,
                          aOutput->ChannelFloatsForWrite(i),
                          aInput.GetDuration());
    }
  }

  bool IsActive() const override
  {
    return !mBiquads.IsEmpty();
  }

  size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const override
  {
    // Not owned:
    // - mDestination - probably not owned
    // - AudioParamTimelines - counted in the AudioNode
    size_t amount = AudioNodeEngine::SizeOfExcludingThis(aMallocSizeOf);
    amount += mBiquads.ShallowSizeOfExcludingThis(aMallocSizeOf);
    return amount;
  }

  size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const override
  {
    return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
  }

private:
  AudioNodeStream* mDestination;
  BiquadFilterType mType;
  AudioParamTimeline mFrequency;
  AudioParamTimeline mDetune;
  AudioParamTimeline mQ;
  AudioParamTimeline mGain;
  nsTArray<WebCore::Biquad> mBiquads;
  uint64_t mWindowID;
};

BiquadFilterNode::BiquadFilterNode(AudioContext* aContext)
  : AudioNode(aContext,
              2,
              ChannelCountMode::Max,
              ChannelInterpretation::Speakers)
  , mType(BiquadFilterType::Lowpass)
  , mFrequency(new AudioParam(this, BiquadFilterNodeEngine::FREQUENCY,
                              350.f, "frequency"))
  , mDetune(new AudioParam(this, BiquadFilterNodeEngine::DETUNE, 0.f, "detune"))
  , mQ(new AudioParam(this, BiquadFilterNodeEngine::Q, 1.f, "Q"))
  , mGain(new AudioParam(this, BiquadFilterNodeEngine::GAIN, 0.f, "gain"))
{
  uint64_t windowID = aContext->GetParentObject()->WindowID();
  BiquadFilterNodeEngine* engine = new BiquadFilterNodeEngine(this, aContext->Destination(), windowID);
  mStream = AudioNodeStream::Create(aContext, engine,
                                    AudioNodeStream::NO_STREAM_FLAGS,
                                    aContext->Graph());
}

BiquadFilterNode::~BiquadFilterNode()
{
}

size_t
BiquadFilterNode::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
{
  size_t amount = AudioNode::SizeOfExcludingThis(aMallocSizeOf);

  if (mFrequency) {
    amount += mFrequency->SizeOfIncludingThis(aMallocSizeOf);
  }

  if (mDetune) {
    amount += mDetune->SizeOfIncludingThis(aMallocSizeOf);
  }

  if (mQ) {
    amount += mQ->SizeOfIncludingThis(aMallocSizeOf);
  }

  if (mGain) {
    amount += mGain->SizeOfIncludingThis(aMallocSizeOf);
  }

  return amount;
}

size_t
BiquadFilterNode::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const
{
  return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
}

JSObject*
BiquadFilterNode::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
  return BiquadFilterNodeBinding::Wrap(aCx, this, aGivenProto);
}

void
BiquadFilterNode::SetType(BiquadFilterType aType)
{
  mType = aType;
  SendInt32ParameterToStream(BiquadFilterNodeEngine::TYPE,
                             static_cast<int32_t>(aType));
}

void
BiquadFilterNode::GetFrequencyResponse(const Float32Array& aFrequencyHz,
                                       const Float32Array& aMagResponse,
                                       const Float32Array& aPhaseResponse)
{
  aFrequencyHz.ComputeLengthAndData();
  aMagResponse.ComputeLengthAndData();
  aPhaseResponse.ComputeLengthAndData();

  uint32_t length = std::min(std::min(aFrequencyHz.Length(), aMagResponse.Length()),
                             aPhaseResponse.Length());
  if (!length) {
    return;
  }

  auto frequencies = MakeUnique<float[]>(length);
  float* frequencyHz = aFrequencyHz.Data();
  const double nyquist = Context()->SampleRate() * 0.5;

  // Normalize the frequencies
  for (uint32_t i = 0; i < length; ++i) {
    if (frequencyHz[i] >= 0 && frequencyHz[i] <= nyquist) {
        frequencies[i] = static_cast<float>(frequencyHz[i] / nyquist);
    } else {
        frequencies[i] = std::numeric_limits<float>::quiet_NaN();
    }
  }

  const double currentTime = Context()->CurrentTime();

  double freq = mFrequency->GetValueAtTime(currentTime);
  double q = mQ->GetValueAtTime(currentTime);
  double gain = mGain->GetValueAtTime(currentTime);
  double detune = mDetune->GetValueAtTime(currentTime);

  WebCore::Biquad biquad;
  SetParamsOnBiquad(biquad, Context()->SampleRate(), mType, freq, q, gain, detune);
  biquad.getFrequencyResponse(int(length), frequencies.get(), aMagResponse.Data(), aPhaseResponse.Data());
}

} // namespace dom
} // namespace mozilla