Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/dom/media/webrtc/SineWaveGenerator.h
Line
Count
Source (jump to first uncovered line)
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5
#ifndef SINEWAVEGENERATOR_H_
6
#define SINEWAVEGENERATOR_H_
7
8
#include "MediaSegment.h"
9
10
namespace mozilla {
11
12
// generate 1k sine wave per second
13
class SineWaveGenerator
14
{
15
public:
16
  static const int bytesPerSample = 2;
17
  static const int millisecondsPerSecond = PR_MSEC_PER_SEC;
18
19
  explicit SineWaveGenerator(uint32_t aSampleRate, uint32_t aFrequency) :
20
    mTotalLength(aSampleRate / aFrequency),
21
0
    mReadLength(0) {
22
0
    // If we allow arbitrary frequencies, there's no guarantee we won't get rounded here
23
0
    // We could include an error term and adjust for it in generation; not worth the trouble
24
0
    //MOZ_ASSERT(mTotalLength * aFrequency == aSampleRate);
25
0
    mAudioBuffer = MakeUnique<int16_t[]>(mTotalLength);
26
0
    for (int i = 0; i < mTotalLength; i++) {
27
0
      // Set volume to -20db. It's from 32768.0 * 10^(-20/20) = 3276.8
28
0
      mAudioBuffer[i] = (3276.8f * sin(2 * M_PI * i / mTotalLength));
29
0
    }
30
0
  }
31
32
  // NOTE: only safely called from a single thread (MSG callback)
33
0
  void generate(int16_t* aBuffer, TrackTicks aLengthInSamples) {
34
0
    TrackTicks remaining = aLengthInSamples;
35
0
36
0
    while (remaining) {
37
0
      TrackTicks processSamples = 0;
38
0
39
0
      if (mTotalLength - mReadLength >= remaining) {
40
0
        processSamples = remaining;
41
0
      } else {
42
0
        processSamples = mTotalLength - mReadLength;
43
0
      }
44
0
      memcpy(aBuffer, &mAudioBuffer[mReadLength], processSamples * bytesPerSample);
45
0
      aBuffer += processSamples;
46
0
      mReadLength += processSamples;
47
0
      remaining -= processSamples;
48
0
      if (mReadLength == mTotalLength) {
49
0
        mReadLength = 0;
50
0
      }
51
0
    }
52
0
  }
53
54
private:
55
  UniquePtr<int16_t[]> mAudioBuffer;
56
  TrackTicks mTotalLength;
57
  TrackTicks mReadLength;
58
};
59
60
} // namespace mozilla
61
62
#endif /* SINEWAVEGENERATOR_H_ */