summaryrefslogtreecommitdiffstats
path: root/dom/media/webaudio/IIRFilterNode.cpp
blob: 3a69a94c8c708aa594d26fe3d2c6420f01ad4b79 (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
/* -*- 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 "IIRFilterNode.h"
#include "AudioNodeEngine.h"

#include "blink/IIRFilter.h"

#include "nsGkAtoms.h"

namespace mozilla {
namespace dom {

NS_IMPL_ISUPPORTS_INHERITED0(IIRFilterNode, AudioNode)

class IIRFilterNodeEngine final : public AudioNodeEngine
{
public:
  IIRFilterNodeEngine(AudioNode* aNode, AudioDestinationNode* aDestination,
                      const AudioDoubleArray &aFeedforward,
                      const AudioDoubleArray &aFeedback,
                      uint64_t aWindowID)
    : AudioNodeEngine(aNode)
    , mDestination(aDestination->Stream())
    , mFeedforward(aFeedforward)
    , mFeedback(aFeedback)
    , mWindowID(aWindowID)
  {
  }

  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()) {
      if (!mIIRFilters.IsEmpty()) {
        bool allZero = true;
        for (uint32_t i = 0; i < mIIRFilters.Length(); ++i) {
          allZero &= mIIRFilters[i]->buffersAreZero();
        }

        // all filter buffer values are zero, so the output will be zero
        // as well.
        if (allZero) {
          mIIRFilters.Clear();
          aStream->ScheduleCheckForInactive();

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

          aOutput->SetNull(WEBAUDIO_BLOCK_SIZE);
          return;
        }

        PodZero(alignedInputBuffer, WEBAUDIO_BLOCK_SIZE);
      }
    } else if(mIIRFilters.Length() != aInput.ChannelCount()){
      if (mIIRFilters.IsEmpty()) {
        RefPtr<PlayingRefChangeHandler> refchanged =
          new PlayingRefChangeHandler(aStream, PlayingRefChangeHandler::ADDREF);
        aStream->Graph()->
          DispatchToMainThreadAfterStreamStateUpdate(refchanged.forget());
      } else {
        WebAudioUtils::LogToDeveloperConsole(mWindowID,
                                             "IIRFilterChannelCountChangeWarning");
      }

      // Adjust the number of filters based on the number of channels
      mIIRFilters.SetLength(aInput.ChannelCount());
      for (size_t i = 0; i < aInput.ChannelCount(); ++i) {
        mIIRFilters[i] = new blink::IIRFilter(&mFeedforward, &mFeedback);
      }
    }

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

    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;
        }
      }

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

  bool IsActive() const override
  {
    return !mIIRFilters.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 += mIIRFilters.ShallowSizeOfExcludingThis(aMallocSizeOf);
    return amount;
  }

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

private:
  AudioNodeStream* mDestination;
  nsTArray<nsAutoPtr<blink::IIRFilter>> mIIRFilters;
  AudioDoubleArray mFeedforward;
  AudioDoubleArray mFeedback;
  uint64_t mWindowID;
};

IIRFilterNode::IIRFilterNode(AudioContext* aContext,
                             const mozilla::dom::binding_detail::AutoSequence<double>& aFeedforward,
                             const mozilla::dom::binding_detail::AutoSequence<double>& aFeedback)
  : AudioNode(aContext,
              2,
              ChannelCountMode::Max,
              ChannelInterpretation::Speakers)
{
  mFeedforward.SetLength(aFeedforward.Length());
  PodCopy(mFeedforward.Elements(), aFeedforward.Elements(), aFeedforward.Length());
  mFeedback.SetLength(aFeedback.Length());
  PodCopy(mFeedback.Elements(), aFeedback.Elements(), aFeedback.Length());

  // Scale coefficients -- we guarantee that mFeedback != 0 when creating
  // the IIRFilterNode.
  double scale = mFeedback[0];
  double* elements = mFeedforward.Elements();
  for (size_t i = 0; i < mFeedforward.Length(); ++i) {
    elements[i] /= scale;
  }

  elements = mFeedback.Elements();
  for (size_t i = 0; i < mFeedback.Length(); ++i) {
    elements[i] /= scale;
  }

  // We check that this is exactly equal to one later in blink/IIRFilter.cpp
  elements[0] = 1.0;

  uint64_t windowID = aContext->GetParentObject()->WindowID();
  IIRFilterNodeEngine* engine = new IIRFilterNodeEngine(this, aContext->Destination(), mFeedforward, mFeedback, windowID);
  mStream = AudioNodeStream::Create(aContext, engine,
                                    AudioNodeStream::NO_STREAM_FLAGS,
                                    aContext->Graph());
}

IIRFilterNode::~IIRFilterNode()
{
}

size_t
IIRFilterNode::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
{
  size_t amount = AudioNode::SizeOfExcludingThis(aMallocSizeOf);
  return amount;
}

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

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

void
IIRFilterNode::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();
    }
  }

  blink::IIRFilter filter(&mFeedforward, &mFeedback);
  filter.getFrequencyResponse(int(length), frequencies.get(), aMagResponse.Data(), aPhaseResponse.Data());
}

} // namespace dom
} // namespace mozilla