summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/webaudio/the-audio-api/the-convolvernode-interface/convolver-response-4-chan.html
blob: f188d87b71f4c5d134feebd10ba95ffe165debb1 (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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
<!DOCTYPE html>
<html>
  <head>
    <title>
      Test Convolver Channel Outputs for Response with 4 channels
    </title>
    <script src="/resources/testharness.js"></script>
    <script src="/resources/testharnessreport.js"></script>
    <script src="/webaudio/resources/audit-util.js"></script>
    <script src="/webaudio/resources/audit.js"></script>
  </head>
  <body>
    <script id="layout-test-code">
      // Test various convolver configurations when the convolver response has
      // a four channels.

      // This is somewhat arbitrary.  It is the minimum value for which tests
      // pass with both FFmpeg and KISS FFT implementations for 256 points.
      // The value was similar for each implementation.
      const absoluteThreshold = 3 * Math.pow(2, -22);

      // Fairly arbitrary sample rate, except that we want the rate to be a
      // power of two so that 1/sampleRate is exactly representable as a
      // single-precision float.
      let sampleRate = 8192;

      // A fairly arbitrary number of frames, except the number of frames should
      // be more than a few render quanta.
      let renderFrames = 10 * 128;

      let audit = Audit.createTaskRunner();

      // Convolver response
      let response;

      audit.define(
          {
            label: 'initialize',
            description: 'Convolver response with one channel'
          },
          (task, should) => {
            // Convolver response
            should(
                () => {
                  response = new AudioBuffer(
                      {numberOfChannels: 4, length: 8, sampleRate: sampleRate});
                  // Each channel of the response is a simple impulse (with
                  // different delay) so that we can use a DelayNode to simulate
                  // the convolver output.  Channel k is delayed by k+1 frames.
                  for (let k = 0; k < response.numberOfChannels; ++k) {
                    response.getChannelData(k)[k + 1] = 1;
                  }
                },
                'new AudioBuffer({numberOfChannels: 2, length: 4, sampleRate: ' +
                    sampleRate + '})')
                .notThrow();

            task.done();
          });

      audit.define(
          {label: '1-channel input', description: 'produces 2-channel output'},
          (task, should) => {
            fourChannelResponseTest({numberOfInputs: 1, prefix: '1'}, should)
                .then(() => task.done());
          });

      audit.define(
          {label: '2-channel input', description: 'produces 2-channel output'},
          (task, should) => {
            fourChannelResponseTest({numberOfInputs: 2, prefix: '2'}, should)
                .then(() => task.done());
          });

      audit.define(
          {
            label: '3-channel input',
            description: '3->2 downmix producing 2-channel output'
          },
          (task, should) => {
            fourChannelResponseTest({numberOfInputs: 3, prefix: '3'}, should)
                .then(() => task.done());
          });

      audit.define(
          {
            label: '4-channel input',
            description: '4->2 downmix producing 2-channel output'
          },
          (task, should) => {
            fourChannelResponseTest({numberOfInputs: 4, prefix: '4'}, should)
                .then(() => task.done());
          });

      audit.define(
          {
            label: '5.1-channel input',
            description: '5.1->2 downmix producing 2-channel output'
          },
          (task, should) => {
            // Scale tolerance by maximum amplitude expected in down-mix
            // output.
            let threshold = (1.0 + Math.sqrt(0.5) * 2) * absoluteThreshold;

            fourChannelResponseTest({numberOfInputs: 6, prefix: '5.1',
                                     absoluteThreshold: threshold}, should)
                .then(() => task.done());
          });

      audit.define(
          {
            label: 'delayed buffer set',
            description: 'Delayed set of 4-channel response'
          },
          (task, should) => {
            // Don't really care about the output for this test.  It's to verify
            // we don't crash in a debug build when setting the convolver buffer
            // after creating the graph.
            let context = new OfflineAudioContext(1, renderFrames, sampleRate);
            let src = new OscillatorNode(context);
            let convolver =
                new ConvolverNode(context, {disableNormalization: true});
            let buffer = new AudioBuffer({
              numberOfChannels: 4,
              length: 4,
              sampleRate: context.sampleRate
            });

            // Impulse responses for the convolver aren't important, as long as
            // it's not all zeroes.
            for (let k = 0; k < buffer.numberOfChannels; ++k) {
              buffer.getChannelData(k).fill(1);
            }

            src.connect(convolver).connect(context.destination);

            // Set the buffer after a few render quanta have passed.  The actual
            // value must be least one, but is otherwise arbitrary.
            context.suspend(512 / context.sampleRate)
                .then(() => convolver.buffer = buffer)
                .then(() => context.resume());

            src.start();
            context.startRendering()
                .then(audioBuffer => {
                  // Just make sure output is not silent.
                  should(
                      audioBuffer.getChannelData(0),
                      'Output with delayed setting of convolver buffer')
                      .notBeConstantValueOf(0);
                })
                .then(() => task.done());
          });

      audit.define(
          {
            label: 'count 1, 2-channel in',
            description: '2->1 downmix because channel count is 1'
          },
          (task, should) => {
            channelCount1ExplicitTest(
                {numberOfInputs: 1, prefix: 'Convolver count 1, stereo in'},
                should)
                .then(() => task.done());
          });

      audit.define(
          {
            label: 'count 1, 4-channel in',
            description: '4->1 downmix because channel count is 1'
          },
          (task, should) => {
            channelCount1ExplicitTest(
                {numberOfInputs: 4, prefix: 'Convolver count 1, 4-channel in'},
                should)
                .then(() => task.done());
          });

      audit.define(
          {
            label: 'count 1, 5.1-channel in',
            description: '5.1->1 downmix because channel count is 1'
          },
          (task, should) => {
            channelCount1ExplicitTest(
                {
                  numberOfInputs: 6,
                  prefix: 'Convolver count 1, 5.1 channel in'
                },
                should)
                .then(() => task.done());
          });

      audit.run();

      function fourChannelResponseTest(options, should) {
        // Create an 4-channel offline context.  The first two channels are for
        // the stereo output of the convolver and the next two channels are for
        // the reference stereo signal.
        let context = new OfflineAudioContext(4, renderFrames, sampleRate);
        context.destination.channelInterpretation = 'discrete';

        // Create oscillators for use as the input.  The type and frequency is
        // arbitrary except that oscillators must be different.
        let src = new Array(options.numberOfInputs);
        for (let k = 0; k < src.length; ++k) {
          src[k] = new OscillatorNode(
              context, {type: 'square', frequency: 440 + 220 * k});
        }

        // Merger to combine the oscillators into one output stream.
        let srcMerger =
            new ChannelMergerNode(context, {numberOfInputs: src.length});

        for (let k = 0; k < src.length; ++k) {
          src[k].connect(srcMerger, 0, k);
        }

        // Convolver under test.
        let conv = new ConvolverNode(
            context, {disableNormalization: true, buffer: response});
        srcMerger.connect(conv);

        // Splitter to get individual channels of the convolver output so we can
        // feed them (eventually) to the context in the right set of channels.
        let splitter = new ChannelSplitterNode(context, {numberOfOutputs: 2});
        conv.connect(splitter);

        // Reference graph consists of a delays node to simulate the response of
        // the convolver.  (The convolver response is designed this way.)
        let delay = new Array(4);
        for (let k = 0; k < delay.length; ++k) {
          delay[k] = new DelayNode(context, {
            delayTime: (k + 1) / context.sampleRate,
            channelCount: 1,
            channelCountMode: 'explicit'
          });
        }

        // Gain node to mix the sources to stereo in the desired way.  (Could be
        // done in the delay node, but let's keep the mixing separated from the
        // functionality.)
        let gainMixer = new GainNode(
            context, {channelCount: 2, channelCountMode: 'explicit'});
        srcMerger.connect(gainMixer);

        // Splitter to extract the channels of the reference signal.
        let refSplitter =
            new ChannelSplitterNode(context, {numberOfOutputs: 2});
        gainMixer.connect(refSplitter);

        // Connect the left channel to the first two nodes and the right channel
        // to the second two as required for "true" stereo matrix response.
        for (let k = 0; k < 2; ++k) {
          refSplitter.connect(delay[k], 0, 0);
          refSplitter.connect(delay[k + 2], 1, 0);
        }

        // Gain nodes to sum the responses to stereo
        let gain = new Array(2);
        for (let k = 0; k < gain.length; ++k) {
          gain[k] = new GainNode(context, {
            channelCount: 1,
            channelCountMode: 'explicit',
            channelInterpretation: 'discrete'
          });
        }

        delay[0].connect(gain[0]);
        delay[2].connect(gain[0]);
        delay[1].connect(gain[1]);
        delay[3].connect(gain[1]);

        // Final merger to bring back the individual channels from the convolver
        // and the reference in the right order for the destination.
        let finalMerger = new ChannelMergerNode(
            context, {numberOfInputs: context.destination.channelCount});

        // First two channels are for the convolver output, and the next two are
        // for the reference.
        splitter.connect(finalMerger, 0, 0);
        splitter.connect(finalMerger, 1, 1);
        gain[0].connect(finalMerger, 0, 2);
        gain[1].connect(finalMerger, 0, 3);

        finalMerger.connect(context.destination);

        // Start the sources at last.
        for (let k = 0; k < src.length; ++k) {
          src[k].start();
        }

        return context.startRendering().then(audioBuffer => {
          // Extract the various channels out
          let actual0 = audioBuffer.getChannelData(0);
          let actual1 = audioBuffer.getChannelData(1);
          let expected0 = audioBuffer.getChannelData(2);
          let expected1 = audioBuffer.getChannelData(3);

          let threshold = options.absoluteThreshold ?
              options.absoluteThreshold : absoluteThreshold;

          // Verify that each output channel of the convolver matches
          // the delayed signal from the reference
          should(actual0, options.prefix + ': Channel 0')
              .beCloseToArray(expected0, {absoluteThreshold: threshold});
          should(actual1, options.prefix + ': Channel 1')
              .beCloseToArray(expected1, {absoluteThreshold: threshold});
        });
      }

      function fourChannelResponseExplicitTest(options, should) {
        // Create an 4-channel offline context.  The first two channels are for
        // the stereo output of the convolver and the next two channels are for
        // the reference stereo signal.
        let context = new OfflineAudioContext(4, renderFrames, sampleRate);
        context.destination.channelInterpretation = 'discrete';

        // Create oscillators for use as the input.  The type and frequency is
        // arbitrary except that oscillators must be different.
        let src = new Array(options.numberOfInputs);
        for (let k = 0; k < src.length; ++k) {
          src[k] = new OscillatorNode(
              context, {type: 'square', frequency: 440 + 220 * k});
        }

        // Merger to combine the oscillators into one output stream.
        let srcMerger =
            new ChannelMergerNode(context, {numberOfInputs: src.length});

        for (let k = 0; k < src.length; ++k) {
          src[k].connect(srcMerger, 0, k);
        }

        // Convolver under test.
        let conv = new ConvolverNode(
            context, {disableNormalization: true, buffer: response});
        srcMerger.connect(conv);

        // Splitter to get individual channels of the convolver output so we can
        // feed them (eventually) to the context in the right set of channels.
        let splitter = new ChannelSplitterNode(context, {numberOfOutputs: 2});
        conv.connect(splitter);

        // Reference graph consists of a delays node to simulate the response of
        // the convolver.  (The convolver response is designed this way.)
        let delay = new Array(4);
        for (let k = 0; k < delay.length; ++k) {
          delay[k] = new DelayNode(context, {
            delayTime: (k + 1) / context.sampleRate,
            channelCount: 1,
            channelCountMode: 'explicit'
          });
        }

        // Gain node to mix the sources to stereo in the desired way.  (Could be
        // done in the delay node, but let's keep the mixing separated from the
        // functionality.)
        let gainMixer = new GainNode(
            context, {channelCount: 2, channelCountMode: 'explicit'});
        srcMerger.connect(gainMixer);

        // Splitter to extract the channels of the reference signal.
        let refSplitter =
            new ChannelSplitterNode(context, {numberOfOutputs: 2});
        gainMixer.connect(refSplitter);

        // Connect the left channel to the first two nodes and the right channel
        // to the second two as required for "true" stereo matrix response.
        for (let k = 0; k < 2; ++k) {
          refSplitter.connect(delay[k], 0, 0);
          refSplitter.connect(delay[k + 2], 1, 0);
        }

        // Gain nodes to sum the responses to stereo
        let gain = new Array(2);
        for (let k = 0; k < gain.length; ++k) {
          gain[k] = new GainNode(context, {
            channelCount: 1,
            channelCountMode: 'explicit',
            channelInterpretation: 'discrete'
          });
        }

        delay[0].connect(gain[0]);
        delay[2].connect(gain[0]);
        delay[1].connect(gain[1]);
        delay[3].connect(gain[1]);

        // Final merger to bring back the individual channels from the convolver
        // and the reference in the right order for the destination.
        let finalMerger = new ChannelMergerNode(
            context, {numberOfInputs: context.destination.channelCount});

        // First two channels are for the convolver output, and the next two are
        // for the reference.
        splitter.connect(finalMerger, 0, 0);
        splitter.connect(finalMerger, 1, 1);
        gain[0].connect(finalMerger, 0, 2);
        gain[1].connect(finalMerger, 0, 3);

        finalMerger.connect(context.destination);

        // Start the sources at last.
        for (let k = 0; k < src.length; ++k) {
          src[k].start();
        }

        return context.startRendering().then(audioBuffer => {
          // Extract the various channels out
          let actual0 = audioBuffer.getChannelData(0);
          let actual1 = audioBuffer.getChannelData(1);
          let expected0 = audioBuffer.getChannelData(2);
          let expected1 = audioBuffer.getChannelData(3);

          // Verify that each output channel of the convolver matches
          // the delayed signal from the reference
          should(actual0, options.prefix + ': Channel 0')
              .beEqualToArray(expected0);
          should(actual1, options.prefix + ': Channel 1')
              .beEqualToArray(expected1);
        });
      }

      function channelCount1ExplicitTest(options, should) {
        // Create an 4-channel offline context.  The first two channels are
        // for the stereo output of the convolver and the next two channels
        // are for the reference stereo signal.
        let context = new OfflineAudioContext(4, renderFrames, sampleRate);
        context.destination.channelInterpretation = 'discrete';
        // Final merger to bring back the individual channels from the
        // convolver and the reference in the right order for the
        // destination.
        let finalMerger = new ChannelMergerNode(
            context, {numberOfInputs: context.destination.channelCount});
        finalMerger.connect(context.destination);

        // Create source using oscillators
        let src = new Array(options.numberOfInputs);
        for (let k = 0; k < src.length; ++k) {
          src[k] = new OscillatorNode(
              context, {type: 'square', frequency: 440 + 220 * k});
        }

        // Merger to combine the oscillators into one output stream.
        let srcMerger =
            new ChannelMergerNode(context, {numberOfInputs: src.length});
        for (let k = 0; k < src.length; ++k) {
          src[k].connect(srcMerger, 0, k);
        }

        // Convolver under test
        let conv = new ConvolverNode(context, {
          channelCount: 1,
          channelCountMode: 'explicit',
          disableNormalization: true,
          buffer: response
        });
        srcMerger.connect(conv);

        // Splitter to extract the channels of the test signal.
        let splitter = new ChannelSplitterNode(context, {numberOfOutputs: 2});
        conv.connect(splitter);

        // Reference convolver, with a gain node to do the desired mixing.  The
        // gain node should do the same thing that the convolver under test
        // should do.
        let gain = new GainNode(
            context, {channelCount: 1, channelCountMode: 'explicit'});
        let convRef = new ConvolverNode(
            context, {disableNormalization: true, buffer: response});

        srcMerger.connect(gain).connect(convRef);

        // Splitter to extract the channels of the reference signal.
        let refSplitter =
            new ChannelSplitterNode(context, {numberOfOutputs: 2});

        convRef.connect(refSplitter);

        // Merge all the channels into one
        splitter.connect(finalMerger, 0, 0);
        splitter.connect(finalMerger, 1, 1);
        refSplitter.connect(finalMerger, 0, 2);
        refSplitter.connect(finalMerger, 1, 3);

        // Start sources and render!
        for (let k = 0; k < src.length; ++k) {
          src[k].start();
        }

        return context.startRendering().then(buffer => {
          // The output from the test convolver should be identical to
          // the reference result.
          let testOut0 = buffer.getChannelData(0);
          let testOut1 = buffer.getChannelData(1);
          let refOut0 = buffer.getChannelData(2);
          let refOut1 = buffer.getChannelData(3);

          should(testOut0, `${options.prefix}: output 0`)
              .beEqualToArray(refOut0);
          should(testOut1, `${options.prefix}: output 1`)
              .beEqualToArray(refOut1);
        })
      }
    </script>
  </body>
</html>