summaryrefslogtreecommitdiffstats
path: root/dom/media/webaudio/test/test_convolverNodeDelay.html
blob: 2e8caf8027f5011bab21260d0a2ae02c933b8f91 (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
<!DOCTYPE html>
<title>Test convolution to delay a triangle pulse</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
const sampleRate = 48000;
const LENGTH = 12800;
// tolerate 16-bit math.
const EPSILON = 1.0 / Math.pow(2, 15);

// Triangle pulse
var sourceBuffer = new OfflineAudioContext(1, 1, sampleRate).
  createBuffer(1, 2 * 128, sampleRate);
var channelData = sourceBuffer.getChannelData(0);
for (var i = 0; i < 128; ++i) {
  channelData[i] = i/128;
  channelData[128 + i] = 1.0 - i/128;
}

function test_delay_index(delayIndex) {

  var context = new OfflineAudioContext(2, LENGTH, sampleRate);

  var merger = context.createChannelMerger(2);
  merger.connect(context.destination);

  var impulse = context.createBuffer(1, delayIndex + 1, sampleRate);
  impulse.getChannelData(0)[delayIndex] = 1.0;
  var convolver = context.createConvolver();
  convolver.normalize = false;
  convolver.buffer = impulse;
  convolver.connect(merger, 0, 0);

  var delayTime = delayIndex/sampleRate;
  var delay = context.createDelay(delayTime || 1/sampleRate);
  delay.delayTime.value = delayTime;
  delay.connect(merger, 0, 1);

  var source = context.createBufferSource();
  source.buffer = sourceBuffer;
  source.connect(convolver);
  source.connect(delay);
  source.start(0);

  return context.startRendering().
    then((buffer) => {
      var convolverOutput = buffer.getChannelData(0);
      var delayOutput = buffer.getChannelData(1);
      var maxDiff = 0.0;
      var maxIndex = 0;
      for (var i = 0; i < buffer.length; ++i) {
        var diff = Math.abs(convolverOutput[i] - delayOutput[i]);
        if (diff > maxDiff) {
          maxDiff = diff;
          maxIndex = i;
        }
      }
      // The convolver should produce similar output to the delay.
      assert_approx_equals(convolverOutput[maxIndex], delayOutput[maxIndex],
                           EPSILON, "output at " + maxIndex);
    });
}

// The 5/4 ratio provides sampling across a range of delays and offsets within
// blocks.
for (var delayIndex = 0;
     delayIndex < LENGTH;
     delayIndex = Math.floor((5 * (delayIndex + 1)) / 4)) {
  promise_test(test_delay_index.bind(null, delayIndex),
               "Delay " + delayIndex);
}
</script>