Truly independent web browser
Tests/LibWeb: Import IIRFilterNode and WaveShaperNode tests
Andreas Kling0be520496992
diff --git a/Tests/LibWeb/Crash/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iir-filter-silent-block-crash.html b/Tests/LibWeb/Crash/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iir-filter-silent-block-crash.htmlnew file mode 100644index 00000000000..9148ac30d59--- /dev/null+++ b/Tests/LibWeb/Crash/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iir-filter-silent-block-crash.html@@ -0,0 +1,9 @@+<!doctype html>+<meta charset="utf-8">+<title>Regression test for IIRFilter destination crash</title>+<script>+ var audioContext = new AudioContext();+ var destination = audioContext.destination;+ var filter = destination.context.createIIRFilter([1],[1]);+ filter.connect(destination);+</script>diff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/ctor-iirfilter.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/ctor-iirfilter.txtnew file mode 100644index 00000000000..7142c7685f0--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/ctor-iirfilter.txt@@ -0,0 +1,12 @@+Harness status: OK++Found 6 tests++2 Pass+4 Fail+Pass Initialize OfflineAudioContext+Pass Invalid IIRFilterNode constructor should throw+Fail Default IIRFilterNode constructor with feedforward/feedback+Fail Test AudioNodeOptions on IIRFilterNode+Fail IIRFilterNode constructor should throw with missing required options+Fail Functional test of IIRFilterNode constructor vs. legacy method\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-basic.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-basic.txtnew file mode 100644index 00000000000..0cc88e6fe29--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-basic.txt@@ -0,0 +1,38 @@+Harness status: OK++Found 32 tests++18 Pass+14 Fail+Pass # AUDIT TASK RUNNER STARTED.+Pass Executing "initialize"+Pass Executing "existence"+Fail Executing "parameters"+Pass Executing "exceptions-createIIRFilter"+Fail Executing "exceptions-getFrequencyData"+Pass Audit report+Pass > [initialize]+Pass Initialize context for testing did not throw an exception.+Pass < [initialize] All assertions passed. (total 1 assertions)+Pass > [existence]+Fail X context.createIIRFilter does not exist. Got undefined.+Fail < [existence] 1 out of 1 assertions were failed.+Pass > [parameters]+Pass > [exceptions-createIIRFilter]+Pass createIIRFilter() threw TypeError: "undefined is not a function (evaluated from 'context.createIIRFilter')".+Pass createIIRFilter(new Float32Array(1)) threw TypeError: "undefined is not a function (evaluated from 'context.createIIRFilter')".+Pass createIIRFilter(null, null) threw TypeError: "undefined is not a function (evaluated from 'context.createIIRFilter')".+Fail X createIIRFilter([], []) threw "TypeError" instead of NotSupportedError.+Fail X createIIRFilter([1], []) threw "TypeError" instead of NotSupportedError.+Fail X createIIRFilter([], [1]) threw "TypeError" instead of NotSupportedError.+Fail X createIIRFilter(new Float32Array(20), new Float32Array(20)) incorrectly threw TypeError: "undefined is not a function (evaluated from 'context.createIIRFilter')".+Fail X createIIRFilter(new Float32Array(21), [1]) threw "TypeError" instead of NotSupportedError.+Fail X createIIRFilter([1], new Float32Array(21)) threw "TypeError" instead of NotSupportedError.+Fail X createIIRFilter([1], new Float32Array(2)) threw "TypeError" instead of InvalidStateError.+Fail X createIIRFilter(new Float32Array(10), [1]) threw "TypeError" instead of InvalidStateError.+Pass createIIRFilter([1], [1, NaN, Infinity]) threw TypeError: "undefined is not a function (evaluated from 'context.createIIRFilter')".+Pass createIIRFilter([1, NaN, Infinity], [1]) threw TypeError: "undefined is not a function (evaluated from 'context.createIIRFilter')".+Pass createIIRFilter([1, 'abc', []], [1]) threw TypeError: "undefined is not a function (evaluated from 'context.createIIRFilter')".+Fail < [exceptions-createIIRFilter] 8 out of 14 assertions were failed.+Pass > [exceptions-getFrequencyData]+Fail # AUDIT TASK RUNNER FINISHED: 2 out of 5 tasks were failed.\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-getFrequencyResponse.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-getFrequencyResponse.txtnew file mode 100644index 00000000000..afea9ca7f63--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-getFrequencyResponse.txt@@ -0,0 +1,8 @@+Harness status: OK++Found 3 tests++3 Fail+Fail 1-pole IIR getFrequencyResponse() matches analytic response+Fail IIR filter equivalent to biquad has matching frequency response+Fail Out-of-range frequency values yield NaN responses\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-normalization-precision.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-normalization-precision.txtnew file mode 100644index 00000000000..b3ee3cd8d8b--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-normalization-precision.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Fail+Fail IIR coefficient normalization stays precise when feedback[0] is not exactly representable as a float\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter.txtnew file mode 100644index 00000000000..b47e6e4d2d1--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter.txt@@ -0,0 +1,37 @@+Harness status: OK++Found 31 tests++15 Pass+16 Fail+Pass # AUDIT TASK RUNNER STARTED.+Fail Executing "coefficient-normalization"+Fail Executing "one-zero"+Fail Executing "one-pole"+Fail Executing "0: lowpass"+Fail Executing "1: highpass"+Fail Executing "2: bandpass"+Fail Executing "3: notch"+Fail Executing "4: allpass"+Fail Executing "5: lowshelf"+Fail Executing "6: highshelf"+Fail Executing "7: peaking"+Fail Executing "multi-channel"+Fail Executing "4th-order-iir"+Pass Audit report+Pass > [coefficient-normalization]+Fail X createIIRFilter with normalized coefficients incorrectly threw TypeError: "undefined is not a function (evaluated from 'context.createIIRFilter')".+Fail X createIIRFilter with unnormalized coefficients incorrectly threw TypeError: "undefined is not a function (evaluated from 'context.createIIRFilter')".+Pass > [one-zero]+Pass > [one-pole]+Pass > [0: lowpass]+Pass > [1: highpass]+Pass > [2: bandpass]+Pass > [3: notch]+Pass > [4: allpass]+Pass > [5: lowshelf]+Pass > [6: highshelf]+Pass > [7: peaking]+Pass > [multi-channel]+Pass > [4th-order-iir]+Fail # AUDIT TASK RUNNER FINISHED: 1 out of 13 tasks were failed.\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/test-iirfilternode.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/test-iirfilternode.txtnew file mode 100644index 00000000000..3634dca2433--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/test-iirfilternode.txt@@ -0,0 +1,14 @@+Harness status: OK++Found 8 tests++1 Pass+7 Fail+Pass IIRFilterNode coefficients are checked properly+Fail feedforward coefficients can not be empty+Fail feedback coefficients can not be empty+Fail more than 20 feedforward coefficients can not be used+Fail more than 20 feedback coefficients can not be used+Fail at least one feedforward coefficient must be non-zero+Fail the first feedback coefficient must be non-zero+Fail IIRFilterNode getFrequencyResponse handles invalid frequencies properly\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/ctor-waveshaper.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/ctor-waveshaper.txtnew file mode 100644index 00000000000..ff2774247b4--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/ctor-waveshaper.txt@@ -0,0 +1,28 @@+Harness status: OK++Found 22 tests++15 Pass+7 Fail+Pass # AUDIT TASK RUNNER STARTED.+Pass Executing "initialize"+Pass Executing "incorrect construction"+Fail Executing "valid default construction"+Fail Executing "test AudioNodeOptions"+Fail Executing "valid non-default"+Pass Audit report+Pass > [initialize]+Pass context = new OfflineAudioContext(...) did not throw an exception.+Pass < [initialize] All assertions passed. (total 1 assertions)+Pass > [incorrect construction]+Pass new WaveShaperNode() threw TypeError: "undefined is not a constructor (evaluated from 'window[name]')".+Pass new WaveShaperNode(1) threw TypeError: "undefined is not a constructor (evaluated from 'window[name]')".+Pass new WaveShaperNode(context, 42) threw TypeError: "undefined is not a constructor (evaluated from 'window[name]')".+Pass < [incorrect construction] All assertions passed. (total 3 assertions)+Pass > [valid default construction]+Fail X node0 = new WaveShaperNode(context) incorrectly threw TypeError: "undefined is not a constructor (evaluated from 'window[name]')".+Pass > [test AudioNodeOptions]+Fail X new WaveShaperNode(c, {channelCount: 17}) incorrectly threw TypeError: "undefined is not a constructor (evaluated from 'window[nodeName]')".+Pass > [valid non-default]+Fail X node1 = new WaveShaperNode(, {"curve":{"0":1,"1":2,"2":3},"oversample":"4x"}) incorrectly threw ReferenceError: "'WaveShaperNode' is not defined".+Fail # AUDIT TASK RUNNER FINISHED: 3 out of 5 tasks were failed.\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/curve-tests.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/curve-tests.txtnew file mode 100644index 00000000000..e2d76f932d7--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/curve-tests.txt@@ -0,0 +1,12 @@+Harness status: OK++Found 7 tests++7 Fail+Fail WaveShaperNode - Testing that -1, 0 and +1 map correctly to curve (with 1:1 correlation)+Fail WaveShaperNode - Testing interpolation (where inputs don't correlate directly to curve elements)+Fail WaveShaperNode - Testing out-of-range inputs (should be mapped to the first/last elements of the curve)+Fail WaveShaperNode - Testing a 2-element curve (does not have a middle element)+Fail WaveShaperNode - Testing a 4-element curve (does not have a middle element)+Fail WaveShaperNode - Testing a huge curve+Fail WaveShaperNode - Testing null curve (should return input values)\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/silent-inputs.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/silent-inputs.txtnew file mode 100644index 00000000000..b0a4979afed--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/silent-inputs.txt@@ -0,0 +1,8 @@+Harness status: OK++Found 3 tests++3 Fail+Fail test-0: curve output is non-zero for silent inputs+Fail test-1: 2x curve output is non-zero for silent inputs+Fail test-2: curve output is non-zero for no inputs\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-copy-curve.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-copy-curve.txtnew file mode 100644index 00000000000..53ca4d8ea1f--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-copy-curve.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Fail+Fail test copying: Modifying curve should not modify WaveShaper\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-limits.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-limits.txtnew file mode 100644index 00000000000..a9e67e99589--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-limits.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Fail+Fail WaveShaperNode maps input values outside [-1,1] according to curve and clamps output correctly\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-simple.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-simple.txtnew file mode 100644index 00000000000..75ee1c51175--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-simple.txt@@ -0,0 +1,11 @@+Harness status: OK++Found 5 tests++4 Pass+1 Fail+Pass # AUDIT TASK RUNNER STARTED.+Fail Executing "simple"+Pass Audit report+Pass > [simple]+Pass # AUDIT TASK RUNNER FINISHED: 1 tasks ran successfully.\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper.txtnew file mode 100644index 00000000000..d7c1dd5063f--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Fail+Fail WaveShaperNode applies non-linear distortion correctly\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/resources/biquad-filters.js b/Tests/LibWeb/Text/input/wpt-import/webaudio/resources/biquad-filters.jsnew file mode 100644index 00000000000..467436326a8--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/resources/biquad-filters.js@@ -0,0 +1,376 @@+// A biquad filter has a z-transform of+// H(z) = (b0 + b1 / z + b2 / z^2) / (1 + a1 / z + a2 / z^2)+//+// The formulas for the various filters were taken from+// http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt.+++// Lowpass filter.+function createLowpassFilter(freq, q, gain) {+ let b0;+ let b1;+ let b2;+ let a0;+ let a1;+ let a2;++ if (freq == 1) {+ // The formula below works, except for roundoff. When freq = 1,+ // the filter is just a wire, so hardwire the coefficients.+ b0 = 1;+ b1 = 0;+ b2 = 0;+ a0 = 1;+ a1 = 0;+ a2 = 0;+ } else {+ let theta = Math.PI * freq;+ let alpha = Math.sin(theta) / (2 * Math.pow(10, q / 20));+ let cosw = Math.cos(theta);+ let beta = (1 - cosw) / 2;++ b0 = beta;+ b1 = 2 * beta;+ b2 = beta;+ a0 = 1 + alpha;+ a1 = -2 * cosw;+ a2 = 1 - alpha;+ }++ return normalizeFilterCoefficients(b0, b1, b2, a0, a1, a2);+}++function createHighpassFilter(freq, q, gain) {+ let b0;+ let b1;+ let b2;+ let a0;+ let a1;+ let a2;++ if (freq == 1) {+ // The filter is 0+ b0 = 0;+ b1 = 0;+ b2 = 0;+ a0 = 1;+ a1 = 0;+ a2 = 0;+ } else if (freq == 0) {+ // The filter is 1. Computation of coefficients below is ok, but+ // there's a pole at 1 and a zero at 1, so round-off could make+ // the filter unstable.+ b0 = 1;+ b1 = 0;+ b2 = 0;+ a0 = 1;+ a1 = 0;+ a2 = 0;+ } else {+ let theta = Math.PI * freq;+ let alpha = Math.sin(theta) / (2 * Math.pow(10, q / 20));+ let cosw = Math.cos(theta);+ let beta = (1 + cosw) / 2;++ b0 = beta;+ b1 = -2 * beta;+ b2 = beta;+ a0 = 1 + alpha;+ a1 = -2 * cosw;+ a2 = 1 - alpha;+ }++ return normalizeFilterCoefficients(b0, b1, b2, a0, a1, a2);+}++function normalizeFilterCoefficients(b0, b1, b2, a0, a1, a2) {+ let scale = 1 / a0;++ return {+ b0: b0 * scale,+ b1: b1 * scale,+ b2: b2 * scale,+ a1: a1 * scale,+ a2: a2 * scale+ };+}++function createBandpassFilter(freq, q, gain) {+ let b0;+ let b1;+ let b2;+ let a0;+ let a1;+ let a2;+ let coef;++ if (freq > 0 && freq < 1) {+ let w0 = Math.PI * freq;+ if (q > 0) {+ let alpha = Math.sin(w0) / (2 * q);+ let k = Math.cos(w0);++ b0 = alpha;+ b1 = 0;+ b2 = -alpha;+ a0 = 1 + alpha;+ a1 = -2 * k;+ a2 = 1 - alpha;++ coef = normalizeFilterCoefficients(b0, b1, b2, a0, a1, a2);+ } else {+ // q = 0, and frequency is not 0 or 1. The above formula has a+ // divide by zero problem. The limit of the z-transform as q+ // approaches 0 is 1, so set the filter that way.+ coef = {b0: 1, b1: 0, b2: 0, a1: 0, a2: 0};+ }+ } else {+ // When freq = 0 or 1, the z-transform is identically 0,+ // independent of q.+ coef = { b0: 0, b1: 0, b2: 0, a1: 0, a2: 0 }+ }++ return coef;+}++function createLowShelfFilter(freq, q, gain) {+ // q not used+ let b0;+ let b1;+ let b2;+ let a0;+ let a1;+ let a2;+ let coef;++ let S = 1;+ let A = Math.pow(10, gain / 40);++ if (freq == 1) {+ // The filter is just a constant gain+ coef = {b0: A * A, b1: 0, b2: 0, a1: 0, a2: 0};+ } else if (freq == 0) {+ // The filter is 1+ coef = {b0: 1, b1: 0, b2: 0, a1: 0, a2: 0};+ } else {+ let w0 = Math.PI * freq;+ let alpha = 1 / 2 * Math.sin(w0) * Math.sqrt((A + 1 / A) * (1 / S - 1) + 2);+ let k = Math.cos(w0);+ let k2 = 2 * Math.sqrt(A) * alpha;+ let Ap1 = A + 1;+ let Am1 = A - 1;++ b0 = A * (Ap1 - Am1 * k + k2);+ b1 = 2 * A * (Am1 - Ap1 * k);+ b2 = A * (Ap1 - Am1 * k - k2);+ a0 = Ap1 + Am1 * k + k2;+ a1 = -2 * (Am1 + Ap1 * k);+ a2 = Ap1 + Am1 * k - k2;+ coef = normalizeFilterCoefficients(b0, b1, b2, a0, a1, a2);+ }++ return coef;+}++function createHighShelfFilter(freq, q, gain) {+ // q not used+ let b0;+ let b1;+ let b2;+ let a0;+ let a1;+ let a2;+ let coef;++ let A = Math.pow(10, gain / 40);++ if (freq == 1) {+ // When freq = 1, the z-transform is 1+ coef = {b0: 1, b1: 0, b2: 0, a1: 0, a2: 0};+ } else if (freq > 0) {+ let w0 = Math.PI * freq;+ let S = 1;+ let alpha = 0.5 * Math.sin(w0) * Math.sqrt((A + 1 / A) * (1 / S - 1) + 2);+ let k = Math.cos(w0);+ let k2 = 2 * Math.sqrt(A) * alpha;+ let Ap1 = A + 1;+ let Am1 = A - 1;++ b0 = A * (Ap1 + Am1 * k + k2);+ b1 = -2 * A * (Am1 + Ap1 * k);+ b2 = A * (Ap1 + Am1 * k - k2);+ a0 = Ap1 - Am1 * k + k2;+ a1 = 2 * (Am1 - Ap1 * k);+ a2 = Ap1 - Am1 * k - k2;++ coef = normalizeFilterCoefficients(b0, b1, b2, a0, a1, a2);+ } else {+ // When freq = 0, the filter is just a gain+ coef = {b0: A * A, b1: 0, b2: 0, a1: 0, a2: 0};+ }++ return coef;+}++function createPeakingFilter(freq, q, gain) {+ let b0;+ let b1;+ let b2;+ let a0;+ let a1;+ let a2;+ let coef;++ let A = Math.pow(10, gain / 40);++ if (freq > 0 && freq < 1) {+ if (q > 0) {+ let w0 = Math.PI * freq;+ let alpha = Math.sin(w0) / (2 * q);+ let k = Math.cos(w0);++ b0 = 1 + alpha * A;+ b1 = -2 * k;+ b2 = 1 - alpha * A;+ a0 = 1 + alpha / A;+ a1 = -2 * k;+ a2 = 1 - alpha / A;++ coef = normalizeFilterCoefficients(b0, b1, b2, a0, a1, a2);+ } else {+ // q = 0, we have a divide by zero problem in the formulas+ // above. But if we look at the z-transform, we see that the+ // limit as q approaches 0 is A^2.+ coef = {b0: A * A, b1: 0, b2: 0, a1: 0, a2: 0};+ }+ } else {+ // freq = 0 or 1, the z-transform is 1+ coef = {b0: 1, b1: 0, b2: 0, a1: 0, a2: 0};+ }++ return coef;+}++function createNotchFilter(freq, q, gain) {+ let b0;+ let b1;+ let b2;+ let a0;+ let a1;+ let a2;+ let coef;++ if (freq > 0 && freq < 1) {+ if (q > 0) {+ let w0 = Math.PI * freq;+ let alpha = Math.sin(w0) / (2 * q);+ let k = Math.cos(w0);++ b0 = 1;+ b1 = -2 * k;+ b2 = 1;+ a0 = 1 + alpha;+ a1 = -2 * k;+ a2 = 1 - alpha;+ coef = normalizeFilterCoefficients(b0, b1, b2, a0, a1, a2);+ } else {+ // When q = 0, we get a divide by zero above. The limit of the+ // z-transform as q approaches 0 is 0, so set the coefficients+ // appropriately.+ coef = {b0: 0, b1: 0, b2: 0, a1: 0, a2: 0};+ }+ } else {+ // When freq = 0 or 1, the z-transform is 1+ coef = {b0: 1, b1: 0, b2: 0, a1: 0, a2: 0};+ }++ return coef;+}++function createAllpassFilter(freq, q, gain) {+ let b0;+ let b1;+ let b2;+ let a0;+ let a1;+ let a2;+ let coef;++ if (freq > 0 && freq < 1) {+ if (q > 0) {+ let w0 = Math.PI * freq;+ let alpha = Math.sin(w0) / (2 * q);+ let k = Math.cos(w0);++ b0 = 1 - alpha;+ b1 = -2 * k;+ b2 = 1 + alpha;+ a0 = 1 + alpha;+ a1 = -2 * k;+ a2 = 1 - alpha;+ coef = normalizeFilterCoefficients(b0, b1, b2, a0, a1, a2);+ } else {+ // q = 0+ coef = {b0: -1, b1: 0, b2: 0, a1: 0, a2: 0};+ }+ } else {+ coef = {b0: 1, b1: 0, b2: 0, a1: 0, a2: 0};+ }++ return coef;+}++function filterData(filterCoef, signal, len) {+ let y = new Array(len);+ let b0 = filterCoef.b0;+ let b1 = filterCoef.b1;+ let b2 = filterCoef.b2;+ let a1 = filterCoef.a1;+ let a2 = filterCoef.a2;++ // Prime the pump. (Assumes the signal has length >= 2!)+ y[0] = b0 * signal[0];+ y[1] = b0 * signal[1] + b1 * signal[0] - a1 * y[0];++ // Filter all of the signal that we have.+ for (let k = 2; k < Math.min(signal.length, len); ++k) {+ y[k] = b0 * signal[k] + b1 * signal[k - 1] + b2 * signal[k - 2] -+ a1 * y[k - 1] - a2 * y[k - 2];+ }++ // If we need to filter more, but don't have any signal left,+ // assume the signal is zero.+ for (let k = signal.length; k < len; ++k) {+ y[k] = -a1 * y[k - 1] - a2 * y[k - 2];+ }++ return y;+}++// Map the filter type name to a function that computes the filter coefficents+// for the given filter type.+let filterCreatorFunction = {+ 'lowpass': createLowpassFilter,+ 'highpass': createHighpassFilter,+ 'bandpass': createBandpassFilter,+ 'lowshelf': createLowShelfFilter,+ 'highshelf': createHighShelfFilter,+ 'peaking': createPeakingFilter,+ 'notch': createNotchFilter,+ 'allpass': createAllpassFilter+};++let filterTypeName = {+ 'lowpass': 'Lowpass filter',+ 'highpass': 'Highpass filter',+ 'bandpass': 'Bandpass filter',+ 'lowshelf': 'Lowshelf filter',+ 'highshelf': 'Highshelf filter',+ 'peaking': 'Peaking filter',+ 'notch': 'Notch filter',+ 'allpass': 'Allpass filter'+};++function createFilter(filterType, freq, q, gain) {+ return filterCreatorFunction[filterType](freq, q, gain);+}diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/ctor-iirfilter.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/ctor-iirfilter.htmlnew file mode 100644index 00000000000..622372c3b13--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/ctor-iirfilter.html@@ -0,0 +1,107 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Test Constructor: IIRFilter</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/audionodeoptions.js"></script>+ </head>+ <body>+ <script>+ let context;++ promise_test(async () => {+ context = new OfflineAudioContext(1, 1, 48000);+ }, 'Initialize OfflineAudioContext');++ promise_test(async () => {+ testInvalidConstructor_W3CTH('IIRFilterNode', context);+ }, 'Invalid IIRFilterNode constructor should throw');++ promise_test(async () => {+ const node =+ testDefaultConstructor_W3CTH('IIRFilterNode', context, {+ numberOfInputs: 1,+ numberOfOutputs: 1,+ channelCount: 2,+ channelCountMode: 'max',+ channelInterpretation: 'speakers',+ constructorOptions: {feedforward: [1], feedback: [1, -.9]}+ });+ }, 'Default IIRFilterNode constructor with feedforward/feedback');++ promise_test(async () => {+ testAudioNodeOptions_W3CTH(+ context,+ 'IIRFilterNode',+ {additionalOptions: {feedforward: [1, 1], feedback: [1, .5]}});+ }, 'Test AudioNodeOptions on IIRFilterNode');++ promise_test(async () => {+ let node;++ let options = {feedback: [1, .5]};+ assert_throws_js(TypeError, () => {+ node = new IIRFilterNode(context, options);+ }, 'node = new IIRFilterNode(, {"feedback":[1,0.5]})');++ options = {feedforward: [1, 0.5]};+ assert_throws_js(TypeError, () => {+ node = new IIRFilterNode(context, options);+ }, 'node = new IIRFilterNode(c, {"feedforward":[1,0.5]})');+ }, 'IIRFilterNode constructor should throw with missing required ' ++ 'options');++ // Test functionality of constructor. This is needed because we have no+ // way of determining if the filter coefficients were were actually set+ // appropriately.++ // TODO(rtoy): This functionality test should be moved out to a separate+ // file.+ promise_test(async () => {+ const options = {feedback: [1, .5], feedforward: [1, 1]};++ // Create two-channel offline context; sample rate and length are fairly+ // arbitrary. Channel 0 contains the test output and channel 1 contains+ // the expected output.+ const sampleRate = 48000;+ const renderLength = 0.125;+ const testContext =+ new OfflineAudioContext(2, renderLength * sampleRate, sampleRate);++ // The test node uses the constructor. The reference node creates the+ // same filter but uses the old factory method.+ const testNode = new IIRFilterNode(testContext, options);+ const refNode = testContext.createIIRFilter(+ Float32Array.from(options.feedforward),+ Float32Array.from(options.feedback));++ const source = testContext.createOscillator();+ source.connect(testNode);+ source.connect(refNode);++ const merger = testContext.createChannelMerger(+ testContext.destination.channelCount);++ testNode.connect(merger, 0, 0);+ refNode.connect(merger, 0, 1);++ merger.connect(testContext.destination);++ source.start();++ const resultBuffer = await testContext.startRendering();+ const actual = resultBuffer.getChannelData(0);+ const expected = resultBuffer.getChannelData(1);++ // The output from the two channels should be exactly equal+ // because exactly the same IIR filter should have been created.+ assert_array_approx_equals(+ actual, expected, 0,+ 'Output of filter using new IIRFilter(...) should ' ++ 'match legacy method output');+ }, 'Functional test of IIRFilterNode constructor vs. legacy method');+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-basic.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-basic.htmlnew file mode 100644index 00000000000..dddcdaed42f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-basic.html@@ -0,0 +1,204 @@+<!DOCTYPE html>+<html>+ <head>+ <title>+ Test Basic IIRFilterNode Properties+ </title>+ <script src="../../../resources/testharness.js"></script>+ <script src="../../../resources/testharnessreport.js"></script>+ <script src="../../resources/audit-util.js"></script>+ <script src="../../resources/audit.js"></script>+ </head>+ <body>+ <script id="layout-test-code">+ let sampleRate = 48000;+ let testFrames = 100;++ // Global context that can be used by the individual tasks. It must be+ // defined by the initialize task.+ let context;++ let audit = Audit.createTaskRunner();++ audit.define('initialize', (task, should) => {+ should(() => {+ context = new OfflineAudioContext(1, testFrames, sampleRate);+ }, 'Initialize context for testing').notThrow();+ task.done();+ });++ audit.define('existence', (task, should) => {+ should(context.createIIRFilter, 'context.createIIRFilter').exist();+ task.done();+ });++ audit.define('parameters', (task, should) => {+ // Create a really simple IIR filter. Doesn't much matter what.+ let coef = Float32Array.from([1]);++ let f = context.createIIRFilter(coef, coef);++ should(f.numberOfInputs, 'numberOfInputs').beEqualTo(1);+ should(f.numberOfOutputs, 'numberOfOutputs').beEqualTo(1);+ should(f.channelCountMode, 'channelCountMode').beEqualTo('max');+ should(f.channelInterpretation, 'channelInterpretation')+ .beEqualTo('speakers');++ task.done();+ });++ audit.define('exceptions-createIIRFilter', (task, should) => {+ should(function() {+ // Two args are required.+ context.createIIRFilter();+ }, 'createIIRFilter()').throw(TypeError);++ should(function() {+ // Two args are required.+ context.createIIRFilter(new Float32Array(1));+ }, 'createIIRFilter(new Float32Array(1))').throw(TypeError);++ should(function() {+ // null is not valid+ context.createIIRFilter(null, null);+ }, 'createIIRFilter(null, null)').throw(TypeError);++ should(function() {+ // There has to be at least one coefficient.+ context.createIIRFilter([], []);+ }, 'createIIRFilter([], [])').throw(DOMException, 'NotSupportedError');++ should(function() {+ // There has to be at least one coefficient.+ context.createIIRFilter([1], []);+ }, 'createIIRFilter([1], [])').throw(DOMException, 'NotSupportedError');++ should(function() {+ // There has to be at least one coefficient.+ context.createIIRFilter([], [1]);+ }, 'createIIRFilter([], [1])').throw(DOMException, 'NotSupportedError');++ should(+ function() {+ // Max allowed size for the coefficient arrays.+ let fb = new Float32Array(20);+ fb[0] = 1;+ context.createIIRFilter(fb, fb);+ },+ 'createIIRFilter(new Float32Array(20), new Float32Array(20))')+ .notThrow();++ should(+ function() {+ // Max allowed size for the feedforward coefficient array.+ let coef = new Float32Array(21);+ coef[0] = 1;+ context.createIIRFilter(coef, [1]);+ },+ 'createIIRFilter(new Float32Array(21), [1])')+ .throw(DOMException, 'NotSupportedError');++ should(+ function() {+ // Max allowed size for the feedback coefficient array.+ let coef = new Float32Array(21);+ coef[0] = 1;+ context.createIIRFilter([1], coef);+ },+ 'createIIRFilter([1], new Float32Array(21))')+ .throw(DOMException, 'NotSupportedError');++ should(+ function() {+ // First feedback coefficient can't be 0.+ context.createIIRFilter([1], new Float32Array(2));+ },+ 'createIIRFilter([1], new Float32Array(2))')+ .throw(DOMException, 'InvalidStateError');++ should(+ function() {+ // feedforward coefficients can't all be zero.+ context.createIIRFilter(new Float32Array(10), [1]);+ },+ 'createIIRFilter(new Float32Array(10), [1])')+ .throw(DOMException, 'InvalidStateError');++ should(function() {+ // Feedback coefficients must be finite.+ context.createIIRFilter([1], [1, Infinity, NaN]);+ }, 'createIIRFilter([1], [1, NaN, Infinity])').throw(TypeError);++ should(function() {+ // Feedforward coefficients must be finite.+ context.createIIRFilter([1, Infinity, NaN], [1]);+ }, 'createIIRFilter([1, NaN, Infinity], [1])').throw(TypeError);++ should(function() {+ // Test that random junk in the array is converted to NaN.+ context.createIIRFilter([1, 'abc', []], [1]);+ }, 'createIIRFilter([1, \'abc\', []], [1])').throw(TypeError);++ task.done();+ });++ audit.define('exceptions-getFrequencyData', (task, should) => {+ // Create a really simple IIR filter. Doesn't much matter what.+ let coef = Float32Array.from([1]);++ let f = context.createIIRFilter(coef, coef);++ should(+ function() {+ // frequencyHz can't be null.+ f.getFrequencyResponse(+ null, new Float32Array(1), new Float32Array(1));+ },+ 'getFrequencyResponse(null, new Float32Array(1), new Float32Array(1))')+ .throw(TypeError);++ should(+ function() {+ // magResponse can't be null.+ f.getFrequencyResponse(+ new Float32Array(1), null, new Float32Array(1));+ },+ 'getFrequencyResponse(new Float32Array(1), null, new Float32Array(1))')+ .throw(TypeError);++ should(+ function() {+ // phaseResponse can't be null.+ f.getFrequencyResponse(+ new Float32Array(1), new Float32Array(1), null);+ },+ 'getFrequencyResponse(new Float32Array(1), new Float32Array(1), null)')+ .throw(TypeError);++ should(+ function() {+ // magResponse array must the same length as frequencyHz+ f.getFrequencyResponse(+ new Float32Array(10), new Float32Array(1),+ new Float32Array(20));+ },+ 'getFrequencyResponse(new Float32Array(10), new Float32Array(1), new Float32Array(20))')+ .throw(DOMException, 'InvalidAccessError');++ should(+ function() {+ // phaseResponse array must be the same length as frequencyHz+ f.getFrequencyResponse(+ new Float32Array(10), new Float32Array(20),+ new Float32Array(1));+ },+ 'getFrequencyResponse(new Float32Array(10), new Float32Array(20), new Float32Array(1))')+ .throw(DOMException, 'InvalidAccessError');++ task.done();+ });++ audit.run();+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-getFrequencyResponse.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-getFrequencyResponse.htmlnew file mode 100644index 00000000000..c6d7e9a10f5--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-getFrequencyResponse.html@@ -0,0 +1,137 @@+<!DOCTYPE html>+<html>+ <head>+ <title>+ Test IIRFilter getFrequencyResponse() functionality+ </title>+ <script src="../../../resources/testharness.js"></script>+ <script src="../../../resources/testharnessreport.js"></script>+ <script src="../../resources/audit-util.js"></script>+ <script src="../../resources/biquad-filters.js"></script>+ </head>+ <body>+ <script>++ const sampleRate = 48000;+ // Some short duration; we're not actually looking at the rendered output.+ const testDurationSec = 0.01;++ // Number of frequency samples to take.+ const numberOfFrequencies = 1000;++ // Compute a set of linearly spaced frequencies.+ function createFrequencies(nFrequencies, sampleRate) {+ let frequencies = new Float32Array(nFrequencies);+ let nyquist = sampleRate / 2;+ let freqDelta = nyquist / nFrequencies;++ for (let k = 0; k < nFrequencies; ++k) {+ frequencies[k] = k * freqDelta;+ }++ return frequencies;+ }++ test(t => {+ const context = new OfflineAudioContext(+ 1, testDurationSec * sampleRate, sampleRate);+ const iir = context.createIIRFilter([1], [1, -0.9]);++ const frequencies = createFrequencies(+ numberOfFrequencies, context.sampleRate);+ const iirMag = new Float32Array(numberOfFrequencies);+ const iirPhase = new Float32Array(numberOfFrequencies);+ const trueMag = new Float32Array(numberOfFrequencies);+ const truePhase = new Float32Array(numberOfFrequencies);++ // The IIR filter is+ // H(z) = 1/(1 - 0.9*z^(-1)).+ //+ // The frequency response is+ // H(exp(j*w)) = 1/(1 - 0.9*exp(-j*w)).+ //+ // Thus, the magnitude is+ // |H(exp(j*w))| = 1/sqrt(1.81-1.8*cos(w)).+ //+ // The phase is+ // arg(H(exp(j*w)) = atan(0.9*sin(w)/(.9*cos(w)-1))++ const frequencyScale = Math.PI / (sampleRate / 2);+ for (let k = 0; k < frequencies.length; ++k) {+ const omega = frequencyScale * frequencies[k];+ trueMag[k] = 1 / Math.sqrt(1.81 - 1.8 * Math.cos(omega));+ truePhase[k] =+ Math.atan(0.9 * Math.sin(omega) / (0.9 * Math.cos(omega) - 1));+ }++ iir.getFrequencyResponse(frequencies, iirMag, iirPhase);++ // Thresholds were experimentally determined.+ assert_array_equal_within_eps(+ iirMag, trueMag, 2.8611e-6, '1-pole IIR magnitude response ' ++ 'should be closed to calculated magnitude response');+ assert_array_equal_within_eps(+ iirPhase, truePhase, 1.7882e-7, '1-pole IIR phase response ' ++ ' should be closed to calculated phase response');+ }, '1-pole IIR getFrequencyResponse() matches analytic response');++ test(t => {+ // Create an IIR filter equivalent to the biquad filter. Compute the+ // frequency response for both and verify that they are the same.+ const context = new OfflineAudioContext(+ 1, testDurationSec * sampleRate, sampleRate);++ const biquad = context.createBiquadFilter();+ const coef = createFilter(+ biquad.type,+ biquad.frequency.value / (context.sampleRate / 2),+ biquad.Q.value,+ biquad.gain.value);++ const iir = context.createIIRFilter(+ [coef.b0, coef.b1, coef.b2], [1, coef.a1, coef.a2]);++ const frequencies = createFrequencies(+ numberOfFrequencies, context.sampleRate);+ const biquadMag = new Float32Array(numberOfFrequencies);+ const biquadPhase = new Float32Array(numberOfFrequencies);+ const iirMag = new Float32Array(numberOfFrequencies);+ const iirPhase = new Float32Array(numberOfFrequencies);++ biquad.getFrequencyResponse(frequencies, biquadMag, biquadPhase);+ iir.getFrequencyResponse(frequencies, iirMag, iirPhase);+ // Thresholds were experimentally determined.+ assert_array_equal_within_eps(+ iirMag, biquadMag, 2.7419e-5, 'IIR magnitude response should be' ++ 'close to Biquad magnitude response');+ assert_array_equal_within_eps(+ iirPhase, biquadPhase, 2.7657e-5, 'IIR phase response should be' ++ 'close to Biquad phase response');+ }, 'IIR filter equivalent to biquad has matching frequency response');++ test(t => {+ const context = new OfflineAudioContext(1, 1, sampleRate);+ const filter = new IIRFilterNode(+ context, {feedforward: [1], feedback: [1, -0.9]});+ // Frequencies to test. These are all outside the valid range of+ // frequencies of 0 to Nyquist.+ const freq = new Float32Array([-1, context.sampleRate / 2 + 1]);+ const mag = new Float32Array(freq.length);+ const phase = new Float32Array(freq.length);++ filter.getFrequencyResponse(freq, mag, phase);++ // Verify that the returned magnitude and phase entries are all NaN+ // since the frequencies are outside the valid range+ for (let k = 0; k < freq.length; ++k) {+ assert_true(+ Number.isNaN(mag[k]),+ `Magnitude response at f=${freq[k]} should be NaN`);+ assert_true(+ Number.isNaN(phase[k]),+ `Phase response at f=${freq[k]} should be NaN`);+ }+ }, 'Out-of-range frequency values yield NaN responses');+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-normalization-precision.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-normalization-precision.htmlnew file mode 100644index 00000000000..895c8f3ff55--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter-normalization-precision.html@@ -0,0 +1,41 @@+<!DOCTYPE html>+<html>+ <head>+ <title>+ Test IIRFilter coefficient normalization precision+ </title>+ <script src="../../../resources/testharness.js"></script>+ <script src="../../../resources/testharnessreport.js"></script>+ <script src="../../resources/audit-util.js"></script>+ </head>+ <body>+ <script>+ test(t => {+ const context = new OfflineAudioContext(1, 1, 48000);++ const feedforward = [1, 0, -1];+ const feedback = [1, -2 * 0.9995 * Math.cos(Math.PI / 4), 0.9995 ** 2];+ const reference = context.createIIRFilter(feedforward, feedback);++ const scaled = context.createIIRFilter(+ feedforward.map(v => v / 10), feedback.map(v => v / 10));++ const frequencies = new Float32Array(21);+ for (let k = 0; k < frequencies.length; ++k)+ frequencies[k] = 5980 + 2 * k;+ const referenceMag = new Float32Array(frequencies.length);+ const scaledMag = new Float32Array(frequencies.length);+ const phase = new Float32Array(frequencies.length);++ reference.getFrequencyResponse(frequencies, referenceMag, phase);+ scaled.getFrequencyResponse(frequencies, scaledMag, phase);++ assert_array_equal_within_eps(+ scaledMag, referenceMag, {absoluteThreshold: 1e-3},+ 'Magnitude response normalized by feedback[0]=0.1 should match the ' ++ 'response of the equivalent feedback[0]=1 filter');+ }, 'IIR coefficient normalization stays precise when feedback[0] is not ' ++ 'exactly representable as a float');+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter.htmlnew file mode 100644index 00000000000..d3914f9432b--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/iirfilter.html@@ -0,0 +1,572 @@+<!DOCTYPE html>+<html>+ <head>+ <title>+ Test Basic IIRFilterNode Operation+ </title>+ <script src="../../../resources/testharness.js"></script>+ <script src="../../../resources/testharnessreport.js"></script>+ <script src="../../resources/audit-util.js"></script>+ <script src="../../resources/audit.js"></script>+ <script src="../../resources/biquad-filters.js"></script>+ </head>+ <body>+ <script id="layout-test-code">+ let sampleRate = 24000;+ let testDurationSec = 0.25;+ let testFrames = testDurationSec * sampleRate;++ let audit = Audit.createTaskRunner();++ audit.define('coefficient-normalization', (task, should) => {+ // Test that the feedback coefficients are normalized. Do this be+ // creating two IIRFilterNodes. One has normalized coefficients, and+ // one doesn't. Compute the difference and make sure they're the same.+ let context = new OfflineAudioContext(2, testFrames, sampleRate);++ // Use a simple impulse as the source.+ let buffer = context.createBuffer(1, 1, sampleRate);+ buffer.getChannelData(0)[0] = 1;+ let source = context.createBufferSource();+ source.buffer = buffer;++ // Gain node for computing the difference between the filters.+ let gain = context.createGain();+ gain.gain.value = -1;++ // The IIR filters. Use a common feedforward array.+ let ff = [1];++ let fb1 = [1, .9];++ let fb2 = new Float64Array(2);+ // Scale the feedback coefficients by an arbitrary factor.+ let coefScaleFactor = 2;+ for (let k = 0; k < fb2.length; ++k) {+ fb2[k] = coefScaleFactor * fb1[k];+ }++ let iir1;+ let iir2;++ should(function() {+ iir1 = context.createIIRFilter(ff, fb1);+ }, 'createIIRFilter with normalized coefficients').notThrow();++ should(function() {+ iir2 = context.createIIRFilter(ff, fb2);+ }, 'createIIRFilter with unnormalized coefficients').notThrow();++ // Create the graph. The output of iir1 (normalized coefficients) is+ // channel 0, and the output of iir2 (unnormalized coefficients), with+ // appropriate scaling, is channel 1.+ let merger = context.createChannelMerger(2);+ source.connect(iir1);+ source.connect(iir2);+ iir1.connect(merger, 0, 0);+ iir2.connect(gain);++ // The gain for the gain node should be set to compensate for the+ // scaling of the coefficients. Since iir2 has scaled the coefficients+ // by coefScaleFactor, the output is reduced by the same factor, so+ // adjust the gain to scale the output of iir2 back up.+ gain.gain.value = coefScaleFactor;+ gain.connect(merger, 0, 1);++ merger.connect(context.destination);++ source.start();++ // Rock and roll!++ context.startRendering()+ .then(function(result) {+ // Find the max amplitude of the result, which should be near+ // zero.+ let iir1Data = result.getChannelData(0);+ let iir2Data = result.getChannelData(1);++ // Threshold isn't exactly zero because the arithmetic is done+ // differently between the IIRFilterNode and the BiquadFilterNode.+ should(+ iir2Data,+ 'Output of IIR filter with unnormalized coefficients')+ .beCloseToArray(iir1Data, {absoluteThreshold: 2.1958e-38});+ })+ .then(() => task.done());+ });++ audit.define('one-zero', (task, should) => {+ // Create a simple 1-zero filter and compare with the expected output.+ let context = new OfflineAudioContext(1, testFrames, sampleRate);++ // Use a simple impulse as the source+ let buffer = context.createBuffer(1, 1, sampleRate);+ buffer.getChannelData(0)[0] = 1;+ let source = context.createBufferSource();+ source.buffer = buffer;++ // The filter is y(n) = 0.5*(x(n) + x(n-1)), a simple 2-point moving+ // average. This is rather arbitrary; keep it simple.++ let iir = context.createIIRFilter([0.5, 0.5], [1]);++ // Create the graph+ source.connect(iir);+ iir.connect(context.destination);++ // Rock and roll!+ source.start();++ context.startRendering()+ .then(function(result) {+ let actual = result.getChannelData(0);+ let expected = new Float64Array(testFrames);+ // The filter is a simple 2-point moving average of an impulse, so+ // the first two values are non-zero and the rest are zero.+ expected[0] = 0.5;+ expected[1] = 0.5;+ should(actual, 'IIR 1-zero output').beCloseToArray(expected, {+ absoluteThreshold: 0+ });+ })+ .then(() => task.done());+ });++ audit.define('one-pole', (task, should) => {+ // Create a simple 1-pole filter and compare with the expected output.++ // The filter is y(n) + c*y(n-1)= x(n). The analytical response is+ // (-c)^n, so choose a suitable number of frames to run the test for+ // where the output isn't flushed to zero.+ let c = 0.9;+ let eps = 1e-20;+ let duration = Math.floor(Math.log(eps) / Math.log(Math.abs(c)));+ let context = new OfflineAudioContext(1, duration, sampleRate);++ // Use a simple impulse as the source+ let buffer = context.createBuffer(1, 1, sampleRate);+ buffer.getChannelData(0)[0] = 1;+ let source = context.createBufferSource();+ source.buffer = buffer;++ let iir = context.createIIRFilter([1], [1, c]);++ // Create the graph+ source.connect(iir);+ iir.connect(context.destination);++ // Rock and roll!+ source.start();++ context.startRendering()+ .then(function(result) {+ let actual = result.getChannelData(0);+ let expected = new Float64Array(actual.length);++ // The filter is a simple 1-pole filter: y(n) = -c*y(n-k)+x(n),+ // with an impulse as the input.+ expected[0] = 1;+ for (k = 1; k < testFrames; ++k) {+ expected[k] = -c * expected[k - 1];+ }++ // Threshold isn't exactly zero due to round-off in the+ // single-precision IIRFilterNode computations versus the+ // double-precision Javascript computations.+ should(actual, 'IIR 1-pole output').beCloseToArray(expected, {+ absoluteThreshold: 2.7657e-8+ });+ })+ .then(() => task.done());+ });++ // Return a function suitable for use as a defineTask function. This+ // function creates an IIRFilterNode equivalent to the specified+ // BiquadFilterNode and compares the outputs. The outputs from the two+ // filters should be virtually identical.+ function testWithBiquadFilter(filterType, errorThreshold, snrThreshold) {+ return (task, should) => {+ let context = new OfflineAudioContext(2, testFrames, sampleRate);++ // Use a constant (step function) as the source+ let buffer = createConstantBuffer(context, testFrames, 1);+ let source = context.createBufferSource();+ source.buffer = buffer;+++ // Create the biquad. Choose some rather arbitrary values for Q and+ // gain for the biquad so that the shelf filters aren't identical.+ let biquad = context.createBiquadFilter();+ biquad.type = filterType;+ biquad.Q.value = 10;+ biquad.gain.value = 10;++ // Create the equivalent IIR Filter node by computing the coefficients+ // of the given biquad filter type.+ let nyquist = sampleRate / 2;+ let coef = createFilter(+ filterType, biquad.frequency.value / nyquist, biquad.Q.value,+ biquad.gain.value);++ let iir = context.createIIRFilter(+ [coef.b0, coef.b1, coef.b2], [1, coef.a1, coef.a2]);++ let merger = context.createChannelMerger(2);+ // Create the graph+ source.connect(biquad);+ source.connect(iir);++ biquad.connect(merger, 0, 0);+ iir.connect(merger, 0, 1);++ merger.connect(context.destination);++ // Rock and roll!+ source.start();++ context.startRendering()+ .then(function(result) {+ // Find the max amplitude of the result, which should be near+ // zero.+ let expected = result.getChannelData(0);+ let actual = result.getChannelData(1);++ // On MacOSX, WebAudio uses an optimized Biquad implementation+ // that is different from the implementation used for Linux and+ // Windows. This will cause the output to differ, even if the+ // threshold passes. Thus, only print out a very small number+ // of elements of the array where we have tested that they are+ // consistent.+ should(actual, 'IIRFilter for Biquad ' + filterType)+ .beCloseToArray(expected, errorThreshold);++ let snr = 10 * Math.log10(computeSNR(actual, expected));+ should(snr, 'SNR for IIRFIlter for Biquad ' + filterType)+ .beGreaterThanOrEqualTo(snrThreshold);+ })+ .then(() => task.done());+ };+ }++ // Thresholds here are experimentally determined.+ let biquadTestConfigs = [+ {+ filterType: 'lowpass',+ snrThreshold: 91.221,+ errorThreshold: {relativeThreshold: 4.9834e-5}+ },+ {+ filterType: 'highpass',+ snrThreshold: 105.4590,+ errorThreshold: {absoluteThreshold: 2.9e-6, relativeThreshold: 3e-5}+ },+ {+ filterType: 'bandpass',+ snrThreshold: 104.060,+ errorThreshold: {absoluteThreshold: 2e-7, relativeThreshold: 8.7e-4}+ },+ {+ filterType: 'notch',+ snrThreshold: 91.312,+ errorThreshold: {absoluteThreshold: 0, relativeThreshold: 4.22e-5}+ },+ {+ filterType: 'allpass',+ snrThreshold: 91.319,+ errorThreshold: {absoluteThreshold: 0, relativeThreshold: 4.31e-5}+ },+ {+ filterType: 'lowshelf',+ snrThreshold: 90.609,+ errorThreshold: {absoluteThreshold: 0, relativeThreshold: 2.98e-5}+ },+ {+ filterType: 'highshelf',+ snrThreshold: 103.159,+ errorThreshold: {absoluteThreshold: 0, relativeThreshold: 1.24e-5}+ },+ {+ filterType: 'peaking',+ snrThreshold: 91.504,+ errorThreshold: {absoluteThreshold: 0, relativeThreshold: 5.05e-5}+ }+ ];++ // Create a set of tasks based on biquadTestConfigs.+ for (k = 0; k < biquadTestConfigs.length; ++k) {+ let config = biquadTestConfigs[k];+ let name = k + ': ' + config.filterType;+ audit.define(+ name,+ testWithBiquadFilter(+ config.filterType, config.errorThreshold, config.snrThreshold));+ }++ audit.define('multi-channel', (task, should) => {+ // Multi-channel test. Create a biquad filter and the equivalent IIR+ // filter. Filter the same multichannel signal and compare the results.+ let nChannels = 3;+ let context =+ new OfflineAudioContext(nChannels, testFrames, sampleRate);++ // Create a set of oscillators as the multi-channel source.+ let source = [];++ for (k = 0; k < nChannels; ++k) {+ source[k] = context.createOscillator();+ source[k].type = 'sawtooth';+ // The frequency of the oscillator is pretty arbitrary, but each+ // oscillator should have a different frequency.+ source[k].frequency.value = 100 + k * 100;+ }++ let merger = context.createChannelMerger(3);++ let biquad = context.createBiquadFilter();++ // Create the equivalent IIR Filter node.+ let nyquist = sampleRate / 2;+ let coef = createFilter(+ biquad.type, biquad.frequency.value / nyquist, biquad.Q.value,+ biquad.gain.value);+ let fb = [1, coef.a1, coef.a2];+ let ff = [coef.b0, coef.b1, coef.b2];++ let iir = context.createIIRFilter(ff, fb);+ // Gain node to compute the difference between the IIR and biquad+ // filter.+ let gain = context.createGain();+ gain.gain.value = -1;++ // Create the graph.+ for (k = 0; k < nChannels; ++k)+ source[k].connect(merger, 0, k);++ merger.connect(biquad);+ merger.connect(iir);+ iir.connect(gain);+ biquad.connect(context.destination);+ gain.connect(context.destination);++ for (k = 0; k < nChannels; ++k)+ source[k].start();++ context.startRendering()+ .then(function(result) {+ let errorThresholds = [3.7671e-5, 3.0071e-5, 2.6241e-5];++ // Check the difference signal on each channel+ for (channel = 0; channel < result.numberOfChannels; ++channel) {+ // Find the max amplitude of the result, which should be near+ // zero.+ let data = result.getChannelData(channel);+ let maxError =+ data.reduce(function(reducedValue, currentValue) {+ return Math.max(reducedValue, Math.abs(currentValue));+ });++ should(+ maxError,+ 'Max difference between IIR and Biquad on channel ' ++ channel)+ .beLessThanOrEqualTo(errorThresholds[channel]);+ }++ })+ .then(() => task.done());+ });++ // Apply an IIRFilter to the given input signal.+ //+ // IIR filter in the time domain is+ //+ // y[n] = sum(ff[k]*x[n-k], k, 0, M) - sum(fb[k]*y[n-k], k, 1, N)+ //+ function iirFilter(input, feedforward, feedback) {+ // For simplicity, create an x buffer that contains the input, and a y+ // buffer that contains the output. Both of these buffers have an+ // initial work space to implement the initial memory of the filter.+ let workSize = Math.max(feedforward.length, feedback.length);+ let x = new Float32Array(input.length + workSize);++ // Float64 because we want to match the implementation that uses doubles+ // to minimize roundoff.+ let y = new Float64Array(input.length + workSize);++ // Copy the input over.+ for (let k = 0; k < input.length; ++k)+ x[k + feedforward.length] = input[k];++ // Run the filter+ for (let n = 0; n < input.length; ++n) {+ let index = n + workSize;+ let yn = 0;+ for (let k = 0; k < feedforward.length; ++k)+ yn += feedforward[k] * x[index - k];+ for (let k = 0; k < feedback.length; ++k)+ yn -= feedback[k] * y[index - k];++ y[index] = yn;+ }++ return y.slice(workSize).map(Math.fround);+ }++ // Cascade the two given biquad filters to create one IIR filter.+ function cascadeBiquads(f1Coef, f2Coef) {+ // The biquad filters are:+ //+ // f1 = (b10 + b11/z + b12/z^2)/(1 + a11/z + a12/z^2);+ // f2 = (b20 + b21/z + b22/z^2)/(1 + a21/z + a22/z^2);+ //+ // To cascade them, multiply the two transforms together to get a fourth+ // order IIR filter.++ let numProduct = [+ f1Coef.b0 * f2Coef.b0, f1Coef.b0 * f2Coef.b1 + f1Coef.b1 * f2Coef.b0,+ f1Coef.b0 * f2Coef.b2 + f1Coef.b1 * f2Coef.b1 + f1Coef.b2 * f2Coef.b0,+ f1Coef.b1 * f2Coef.b2 + f1Coef.b2 * f2Coef.b1, f1Coef.b2 * f2Coef.b2+ ];++ let denProduct = [+ 1, f2Coef.a1 + f1Coef.a1,+ f2Coef.a2 + f1Coef.a1 * f2Coef.a1 + f1Coef.a2,+ f1Coef.a1 * f2Coef.a2 + f1Coef.a2 * f2Coef.a1, f1Coef.a2 * f2Coef.a2+ ];++ return {+ ff: numProduct, fb: denProduct+ }+ }++ // Find the magnitude of the root of the quadratic that has the maximum+ // magnitude.+ //+ // The quadratic is z^2 + a1 * z + a2 and we want the root z that has the+ // largest magnitude.+ function largestRootMagnitude(a1, a2) {+ let discriminant = a1 * a1 - 4 * a2;+ if (discriminant < 0) {+ // Complex roots: -a1/2 +/- i*sqrt(-d)/2. Thus the magnitude of each+ // root is the same and is sqrt(a1^2/4 + |d|/4)+ let d = Math.sqrt(-discriminant);+ return Math.hypot(a1 / 2, d / 2);+ } else {+ // Real roots+ let d = Math.sqrt(discriminant);+ return Math.max(Math.abs((-a1 + d) / 2), Math.abs((-a1 - d) / 2));+ }+ }++ audit.define('4th-order-iir', (task, should) => {+ // Cascade 2 lowpass biquad filters and compare that with the equivalent+ // 4th order IIR filter.++ let nyquist = sampleRate / 2;+ // Compute the coefficients of a lowpass filter.++ // First some preliminary stuff. Compute the coefficients of the+ // biquad. This is used to figure out how frames to use in the test.+ let biquadType = 'lowpass';+ let biquadCutoff = 350;+ let biquadQ = 5;+ let biquadGain = 1;++ let coef = createFilter(+ biquadType, biquadCutoff / nyquist, biquadQ, biquadGain);++ // Cascade the biquads together to create an equivalent IIR filter.+ let cascade = cascadeBiquads(coef, coef);++ // Since we're cascading two identical biquads, the root of denominator+ // of the IIR filter is repeated, so the root of the denominator with+ // the largest magnitude occurs twice. The impulse response of the IIR+ // filter will be roughly c*(r*r)^n at time n, where r is the root of+ // largest magnitude. This approximation gets better as n increases.+ // We can use this to get a rough idea of when the response has died+ // down to a small value.++ // This is the value we will use to determine how many frames to render.+ // Rendering too many is a waste of time and also makes it hard to+ // compare the actual result to the expected because the magnitudes are+ // so small that they could be mostly round-off noise.+ //+ // Find magnitude of the root with largest magnitude+ let rootMagnitude = largestRootMagnitude(coef.a1, coef.a2);++ // Find n such that |r|^(2*n) <= eps. That is, n = log(eps)/(2*log(r)).+ // Somewhat arbitrarily choose eps = 1e-20;+ let eps = 1e-20;+ let framesForTest =+ Math.floor(Math.log(eps) / (2 * Math.log(rootMagnitude)));++ // We're ready to create the graph for the test. The offline context+ // has two channels: channel 0 is the expected (cascaded biquad) result+ // and channel 1 is the actual IIR filter result.+ let context = new OfflineAudioContext(2, framesForTest, sampleRate);++ // Use a simple impulse with a large (arbitrary) amplitude as the source+ let amplitude = 1;+ let buffer = context.createBuffer(1, testFrames, sampleRate);+ buffer.getChannelData(0)[0] = amplitude;+ let source = context.createBufferSource();+ source.buffer = buffer;++ // Create the two biquad filters. Doesn't really matter what, but for+ // simplicity we choose identical lowpass filters with the same+ // parameters.+ let biquad1 = context.createBiquadFilter();+ biquad1.type = biquadType;+ biquad1.frequency.value = biquadCutoff;+ biquad1.Q.value = biquadQ;++ let biquad2 = context.createBiquadFilter();+ biquad2.type = biquadType;+ biquad2.frequency.value = biquadCutoff;+ biquad2.Q.value = biquadQ;++ let iir = context.createIIRFilter(cascade.ff, cascade.fb);++ // Create the merger to get the signals into multiple channels+ let merger = context.createChannelMerger(2);++ // Create the graph, filtering the source through two biquads.+ source.connect(biquad1);+ biquad1.connect(biquad2);+ biquad2.connect(merger, 0, 0);++ source.connect(iir);+ iir.connect(merger, 0, 1);++ merger.connect(context.destination);++ // Now filter the source through the IIR filter.+ let y = iirFilter(buffer.getChannelData(0), cascade.ff, cascade.fb);++ // Rock and roll!+ source.start();++ context.startRendering()+ .then(function(result) {+ let expected = result.getChannelData(0);+ let actual = result.getChannelData(1);++ should(actual, '4-th order IIRFilter (biquad ref)')+ .beCloseToArray(expected, {+ // Thresholds experimentally determined.+ absoluteThreshold: 1.59e-7,+ relativeThreshold: 2.11e-5,+ });++ let snr = 10 * Math.log10(computeSNR(actual, expected));+ should(snr, 'SNR of 4-th order IIRFilter (biquad ref)')+ .beGreaterThanOrEqualTo(108.947);+ })+ .then(() => task.done());+ });++ audit.run();+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/test-iirfilternode.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/test-iirfilternode.htmlnew file mode 100644index 00000000000..96237809600--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-iirfilternode-interface/test-iirfilternode.html@@ -0,0 +1,59 @@+<!doctype html>+<meta charset=utf-8>+<title>Test the IIRFilterNode Interface</title>+<script src=../../../resources/testharness.js></script>+<script src=../../../resources/testharnessreport.js></script>+<script>+test(function(t) {+ var ac = new AudioContext();++ function check_args(arg1, arg2, err, desc) {+ test(function() {+ assert_throws_dom(err, function() {+ ac.createIIRFilter(arg1, arg2)+ })+ }, desc)+ }++ check_args([], [1.0], 'NotSupportedError',+ 'feedforward coefficients can not be empty');++ check_args([1.0], [], 'NotSupportedError',+ 'feedback coefficients can not be empty');++ var coeff = new Float32Array(21)+ coeff[0] = 1.0;++ check_args(coeff, [1.0], 'NotSupportedError',+ 'more than 20 feedforward coefficients can not be used');++ check_args([1.0], coeff, 'NotSupportedError',+ 'more than 20 feedback coefficients can not be used');++ check_args([0.0, 0.0], [1.0], 'InvalidStateError',+ 'at least one feedforward coefficient must be non-zero');++ check_args([0.5, 0.5], [0.0], 'InvalidStateError',+ 'the first feedback coefficient must be non-zero');++}, "IIRFilterNode coefficients are checked properly");++test(function(t) {+ var ac = new AudioContext();++ var frequencies = new Float32Array([-1.0, ac.sampleRate*0.5 - 1.0, ac.sampleRate]);+ var magResults = new Float32Array(3);+ var phaseResults = new Float32Array(3);++ var filter = ac.createIIRFilter([0.5, 0.5], [1.0]);+ filter.getFrequencyResponse(frequencies, magResults, phaseResults);++ assert_true(isNaN(magResults[0]), "Invalid input frequency should give NaN magnitude response");+ assert_true(!isNaN(magResults[1]), "Valid input frequency should not give NaN magnitude response");+ assert_true(isNaN(magResults[2]), "Invalid input frequency should give NaN magnitude response");+ assert_true(isNaN(phaseResults[0]), "Invalid input frequency should give NaN phase response");+ assert_true(!isNaN(phaseResults[1]), "Valid input frequency should not give NaN phase response");+ assert_true(isNaN(phaseResults[2]), "Invalid input frequency should give NaN phase response");++}, "IIRFilterNode getFrequencyResponse handles invalid frequencies properly");+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/ctor-waveshaper.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/ctor-waveshaper.htmlnew file mode 100644index 00000000000..63814a7c28d--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/ctor-waveshaper.html@@ -0,0 +1,72 @@+<!DOCTYPE html>+<html>+ <head>+ <title>+ Test Constructor: WaveShaper+ </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>+ <script src="../../../webaudio/resources/audionodeoptions.js"></script>+ </head>+ <body>+ <script id="layout-test-code">+ let context;++ let audit = Audit.createTaskRunner();++ audit.define('initialize', (task, should) => {+ context = initializeContext(should);+ task.done();+ });++ audit.define('incorrect construction', (task, should) => {+ testInvalidConstructor(should, 'WaveShaperNode', context);+ task.done();+ });++ audit.define('valid default construction', (task, should) => {+ let prefix = 'node0';+ let node = testDefaultConstructor(should, 'WaveShaperNode', context, {+ prefix: prefix,+ numberOfInputs: 1,+ numberOfOutputs: 1,+ channelCount: 2,+ channelCountMode: 'max',+ channelInterpretation: 'speakers'+ });++ testDefaultAttributes(should, node, prefix, [+ {name: 'curve', value: null}, {name: 'oversample', value: 'none'}+ ]);++ task.done();+ });++ audit.define('test AudioNodeOptions', (task, should) => {+ testAudioNodeOptions(should, context, 'WaveShaperNode');+ task.done();+ });++ audit.define('valid non-default', (task, should) => {+ // Construct an WaveShaperNode with options+ let options = {curve: Float32Array.from([1, 2, 3]), oversample: '4x'};+ let node;++ let message =+ 'node1 = new WaveShaperNode(, ' + JSON.stringify(options) + ')';+ should(() => {+ node = new WaveShaperNode(context, options);+ }, message).notThrow();+ should(node.curve, 'node1.curve').beEqualToArray(options.curve);+ should(node.oversample, 'node1.oversample')+ .beEqualTo(options.oversample);++ task.done();+ });++ audit.run();+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/curve-tests.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/curve-tests.htmlnew file mode 100644index 00000000000..881a623e003--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/curve-tests.html@@ -0,0 +1,184 @@+<!doctype html>+<html>+<head>+ <title>WaveShaperNode interface - Curve tests | WebAudio</title>++ <script type="text/javascript" src="../../../resources/testharness.js"></script>+ <script type="text/javascript" src="../../../resources/testharnessreport.js"></script>+</head>+<body>+ <div id="log">+ </div>++ <script type="text/javascript">+ var sampleRate=44100.0;+ var tolerance=0.01;++ /*+ Testing that -1, 0 and +1 map correctly to curve (with 1:1 correlation)+ =======================================================================+ From the specification:+ The input signal is nominally within the range -1 -> +1.+ Each input sample within this range will index into the shaping curve with a signal level of zero corresponding+ to the center value of the curve array.+ */+ (function() {+ var threeElementCurve=[2.0, -3.0, 4.0];+ var inputData=[-1.0, 0, 1.0];+ var expectedData=[2.0, -3.0, 4.0];+ executeTest(threeElementCurve, inputData, expectedData, "Testing that -1, 0 and +1 map correctly to curve (with 1:1 correlation)");+ })();++ /*+ Testing interpolation (where inputs don't correlate directly to curve elements)+ ===============================================================================+ From the specification:+ The implementation must perform linear interpolation between adjacent points in the curve.+ */+ (function() {+ var threeElementCurve=[2.0, -3.0, 4.0];+ var inputData=[-0.5, +0.5, +0.75];+ var expectedData=[-0.5, +0.5, +2.25];+ executeTest(threeElementCurve, inputData, expectedData, "Testing interpolation (where inputs don't correlate directly to curve elements)");+ })();++ /*+ Testing out-of-range inputs (should be mapped to the first/last elements of the curve)+ ======================================================================================+ From the specification:+ Any sample value less than -1 will correspond to the first value in the curve array.+ Any sample value greater than +1 will correspond to the last value in the curve array.+ */+ (function() {+ var threeElementCurve=[2.0, -3.0, 4.0];+ var inputData=[-1.5, +1.5];+ var expectedData=[2.0, 4.0];+ executeTest(threeElementCurve, inputData, expectedData, "Testing out-of-range inputs (should be mapped to the first/last elements of the curve)");+ })();++ /*+ Testing a 2-element curve (does not have a middle element)+ ==========================================================+ From the specification:+ Each input sample within this range will index into the shaping curve with a signal level of zero corresponding+ to the center value of the curve array.+ The implementation must perform linear interpolation between adjacent points in the curve.+ */+ (function() {+ var twoElementCurve=[2.0, -2.0];+ var inputData=[-1.0, 0, 1.0];+ var expectedData=[2.0, 0.0, -2.0];+ executeTest(twoElementCurve, inputData, expectedData, "Testing a 2-element curve (does not have a middle element)");+ })();++ /*+ Testing a 4-element curve (does not have a middle element)+ ==========================================================+ From the specification:+ Each input sample within this range will index into the shaping curve with a signal level of zero corresponding+ to the center value of the curve array.+ The implementation must perform linear interpolation between adjacent points in the curve.+ */+ (function() {+ var fourElementCurve=[1.0, 2.0, 4.0, 7.0];+ var inputData=[-1.0, 0, 1.0];+ var expectedData=[1.0, 3.0, 7.0];+ executeTest(fourElementCurve, inputData, expectedData, "Testing a 4-element curve (does not have a middle element)");+ })();++ /*+ Testing a huge curve+ ====================+ From the specification:+ Each input sample within this range will index into the shaping curve with a signal level of zero corresponding+ to the center value of the curve array.+ */+ (function() {+ var bigCurve=[];+ for(var i=0;i<=60000;i++) { bigCurve.push(i/3.5435); }+ var inputData=[-1.0, 0, 1.0];+ var expectedData=[bigCurve[0], bigCurve[30000], bigCurve[60000]];+ executeTest(bigCurve, inputData, expectedData, "Testing a huge curve");+ })();++ /*+ Testing single-element curve (boundary condition)+ =================================================+ From the specification:+ Each input sample within this range will index into the shaping curve with a signal level of zero corresponding+ to the center value of the curve array.+ Any sample value less than -1 will correspond to the first value in the curve array.+ Any sample value greater than +1 will correspond to the last value in the curve array.+ The implementation must perform linear interpolation between adjacent points in the curve.+ */++ /*+ Testing null curve (should return input values)+ ===============================================+ From the specification:+ Initially the curve attribute is null, which means that the WaveShaperNode will pass its input to its output+ without modification.+ */+ (function() {+ var inputData=[-1.0, 0, 1.0, 2.0];+ var expectedData=[-1.0, 0.0, 1.0, 2.0];+ executeTest(null, inputData, expectedData, "Testing null curve (should return input values)");+ })();++ /**+ * Function that does the actual testing (using an asynchronous test).+ * @param {?Array.<number>} curveData - Array containing values for the WaveShaper curve.+ * @param {!Array.<number>} inputData - Array containing values for the input stream.+ * @param {!Array.<number>} expectedData - Array containing expected results for each of the corresponding inputs.+ * @param {!string} testName - Name of the test case.+ */+ function executeTest(curveData, inputData, expectedData, testName) {+ var stTest=async_test("WaveShaperNode - "+testName);+ stTest.step(function() {++ // Create offline audio context.+ var ac=new OfflineAudioContext(1, inputData.length, sampleRate);++ // Create the WaveShaper and its curve.+ var waveShaper=ac.createWaveShaper();+ if(curveData!=null) {+ var curve=new Float32Array(curveData.length);+ for(var i=0;i<curveData.length;i++) { curve[i]=curveData[i]; }+ waveShaper.curve=curve;+ }+ waveShaper.connect(ac.destination);++ // Create buffer containing the input values.+ var inputBuffer=ac.createBuffer(1, Math.max(inputData.length, 2), sampleRate);+ var d=inputBuffer.getChannelData(0);+ for(var i=0;i<inputData.length;i++) { d[i]=inputData[i]; }++ // Play the input buffer through the WaveShaper.+ var src=ac.createBufferSource();+ src.buffer=inputBuffer;+ src.connect(waveShaper);+ src.start();++ // Test the outputs match the expected values.+ ac.oncomplete=stTest.step_func_done(function(ev) {+ var d=ev.renderedBuffer.getChannelData(0);++ for(var i=0;i<expectedData.length;i++) {+ var curveText="null";+ if(curve!=null) {+ if(curveData.length<20) {+ curveText=curveData.join(",");+ } else {+ curveText="TooBigToDisplay ("+(curveData.length-1)+" elements)";+ }+ }+ var comment="Input="+inputData[i]+", Curve=["+curveText+"] >>> ";+ assert_approx_equals(d[i], expectedData[i], tolerance, comment);+ }+ });+ ac.startRendering();+ });+ }+ </script>+</body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/silent-inputs.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/silent-inputs.htmlnew file mode 100644index 00000000000..ac9589a4347--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/silent-inputs.html@@ -0,0 +1,77 @@+<!DOCTYPE html>+<html>+ <head>+ <title>+ Test Silent Inputs to WaveShaperNode+ </title>+ <script src="../../../resources/testharness.js"></script>+ <script src="../../../resources/testharnessreport.js"></script>+ <script src="../../../webaudio/resources/audit-util.js"></script>+ </head>+ <body>+ <script>+ const sampleRate = 16000;++ // Identity curve for the wave shaper: the input value is mapped directly+ // to the output value.+ const identityCurve = [-1, 0, 1];+ const nonZeroCurve = [0.5, 0.5, 0.5];++ promise_test(async (t) => {+ const {context, source, shaper} =+ setupGraph(nonZeroCurve, sampleRate, sampleRate);++ source.offset.setValueAtTime(0, 0);++ const audioBuffer = await context.startRendering();++ assert_array_equals(+ audioBuffer.getChannelData(0),+ new Float32Array(sampleRate).fill(0.5),+ 'WaveShaper with silent inputs and curve ' ++ JSON.stringify(shaper.curve));+ }, 'test-0: curve output is non-zero for silent inputs');++ promise_test(async (t) => {+ const {context, source, shaper} =+ setupGraph(nonZeroCurve, sampleRate, sampleRate);++ source.offset.setValueAtTime(0, 0);+ shaper.overSample = '2x';++ const audioBuffer = await context.startRendering();++ assert_array_equals(+ audioBuffer.getChannelData(0),+ new Float32Array(sampleRate).fill(0.5),+ `WaveShaper with ${shaper.overSample} oversample, ` ++ `silent inputs, and curve ${JSON.stringify(shaper.curve)}`);+ }, 'test-1: 2x curve output is non-zero for silent inputs');++ promise_test(async (t) => {+ const {context, source, shaper} =+ setupGraph(nonZeroCurve, sampleRate, sampleRate);++ source.disconnect();++ const audioBuffer = await context.startRendering();++ assert_array_equals(+ audioBuffer.getChannelData(0),+ new Float32Array(sampleRate).fill(0.5),+ 'WaveShaper with no inputs and curve ' ++ JSON.stringify(shaper.curve));+ }, 'test-2: curve output is non-zero for no inputs');++ function setupGraph(curve, testFrames, sampleRate) {+ const context = new OfflineAudioContext(1, testFrames, sampleRate);+ const source = new ConstantSourceNode(context);+ const shaper = new WaveShaperNode(context, {curve: curve});++ source.connect(shaper).connect(context.destination);++ return {context: context, source: source, shaper: shaper};+ }+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-copy-curve.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-copy-curve.htmlnew file mode 100644index 00000000000..9fb1a372e25--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-copy-curve.html@@ -0,0 +1,80 @@+<!DOCTYPE html>+<html>+ <head>+ <title>+ Test WaveShaper Copies Curve Data+ </title>+ <script src="../../../resources/testharness.js"></script>+ <script src="../../../resources/testharnessreport.js"></script>+ <script src="../../resources/audit-util.js"></script>+ </head>+ <body>+ <script>+ // Sample rate and number of frames are fairly arbitrary. We need to+ // render, however, at least 384 frames. 1024 is a nice small value.+ const sampleRate = 16000;+ const renderFrames = 1024;++ promise_test(async () => {+ // Two-channel context; channel 0 contains the test data and channel+ // 1 contains the expected result. Channel 1 has the normal+ // WaveShaper output and channel 0 has the WaveShaper output with a+ // modified curve.+ const context = new OfflineAudioContext(2, renderFrames, sampleRate);++ // Wave shaper curves. Doesn't really matter what we use as long as+ // it modifies the input in some way. Thus, keep it simple and just+ // invert the input.+ const desiredCurve = [1, 0, -1];+ const curve0 = Float32Array.from(desiredCurve);+ const curve1 = Float32Array.from(desiredCurve);++ // Just use a default oscillator as the source. Doesn't really+ // matter what we use.+ const src = new OscillatorNode(context, {type: 'sawtooth'});++ // Create the wave shapers: ws0 is the test shaper, and ws1 is the+ // reference wave shaper.+ const ws0 = new WaveShaperNode(context, {curve: curve0});+ const ws1 = new WaveShaperNode(context, {curve: curve1});++ // Channel merger for comparing outputs (ch 0: modified-curve shaper,+ // ch 1: reference shaper).+ const merger = new ChannelMergerNode(context, {numberOfInputs: 2});++ src.connect(ws0).connect(merger, 0, 0);+ src.connect(ws1).connect(merger, 0, 1);++ merger.connect(context.destination);++ // Let the context run for a bit and then modify the curve for ws0.+ // Doesn't really matter what we modify the curve to as long as it's+ // different.+ const suspendTime = 256 / context.sampleRate;+ context.suspend(suspendTime).then(() => {+ // Mutate the original array we passed to ws0;+ // node should have copied it.+ curve0[0] = -0.5;+ curve0[1] = 0.125;+ curve0[2] = 0.75;+ return context.resume();+ });++ src.start();++ const renderedBuffer = await context.startRendering();+ const actual = renderedBuffer.getChannelData(0);+ const expected = renderedBuffer.getChannelData(1);++ // Modifying the wave shaper curve should not modify the+ // output so the outputs from the two wave shaper nodes should+ // be exactly identical.+ assert_array_equals(+ actual,+ expected,+ 'Output of WaveShaper with modified curve ' ++ 'should equal reference output');+ }, `test copying: Modifying curve should not modify WaveShaper`);+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-limits.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-limits.htmlnew file mode 100644index 00000000000..2237c3fd56a--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-limits.html@@ -0,0 +1,96 @@+<!DOCTYPE html>+<html>+ <head>+ <title>+ waveshaper-limits.html+ </title>+ <script src="../../../resources/testharness.js"></script>+ <script src="../../../resources/testharnessreport.js"></script>+ <script src="../../resources/audit-util.js"></script>+ </head>+ <body>+ <script>+ let context;+ let bufferData;+ let outputData;+ let reference;++ const sampleRate = 48000;+ // Must be odd so we have an exact middle point.+ const testFrames = 23;+ const scale = 1 / ((testFrames - 1) / 2 - 1);+ // Number of decimal digits to print+ const decimals = 6;+ // Required accuracy+ const diffThreshold = Math.pow(10, -decimals);++ // Generate reference data+ const generateReference = () => {+ // The curve data is 0, 1, 0, and the input data is a ramp from -1+eps+ // to 1+eps. Then the output is a ramp from 0 to 1 back to 0.+ const ref = new Float32Array(testFrames);+ const midPoint = (testFrames - 1) / 2;+ // First sample is below -1 at -1-scale.+ ref[0] = 0;+ // Generate ramp up to the mid-point+ for (let k = 0; k < midPoint; ++k) {+ ref[k + 1] = k * scale;+ }+ // The value at the mid-point must be 1, from the curve+ ref[midPoint] = 1;+ // Generate a ramp from 1 down to 0+ for (let k = midPoint; k < testFrames - 1; ++k) {+ ref[k + 1] = 2 - k * scale;+ }+ // The last sample is out of range at 1+scale+ ref[testFrames - 1] = 0;+ return ref;+ };++ const checkResult = renderedBuffer => {+ outputData = renderedBuffer.getChannelData(0);+ reference = generateReference();+ for (let k = 0; k < outputData.length; ++k) {+ const diff = outputData[k] - reference[k];+ assert_less_than_equal(+ Math.abs(diff),+ diffThreshold,+ `Max error mapping ${bufferData[k].toFixed(decimals)} to ` ++ `${outputData[k].toFixed(decimals)}`);+ }+ };++ promise_test(async t => {+ context = new OfflineAudioContext(1, testFrames, sampleRate);+ // Create input values between -1.1 and 1.1+ const buffer = new AudioBuffer({ length: testFrames,+ numberOfChannels: 1, sampleRate: context.sampleRate });+ bufferData = new Float32Array(testFrames);+ const start = -1 - scale;+ for (let k = 0; k < testFrames; ++k) {+ bufferData[k] = k * scale + start;+ }+ buffer.copyToChannel(bufferData, 0);++ const source = new AudioBufferSourceNode(context, { buffer });++ // Create simple waveshaper. It should map -1 to 0, 0 to 1, and +1+ // to 0 and interpolate all points in between using a simple linear+ // interpolator.+ const curve = new Float32Array(3);+ curve[0] = 0;+ curve[1] = 1;+ curve[2] = 0;++ const shaper = new WaveShaperNode(context, { curve });+ source.connect(shaper);+ shaper.connect(context.destination);++ source.start();+ const renderedBuffer = await context.startRendering();+ checkResult(renderedBuffer);+ }, 'WaveShaperNode maps input values outside [-1,1] according to curve' ++ ' and clamps output correctly');+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-simple.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-simple.htmlnew file mode 100644index 00000000000..69a2c281a4a--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper-simple.html@@ -0,0 +1,61 @@+<!DOCTYPE html>+<html>+ <head>+ <title>+ Simple Tests of WaveShaperNode+ </title>+ <script src="../../../resources/testharness.js"></script>+ <script src="../../../resources/testharnessreport.js"></script>+ <script src="../../resources/audit-util.js"></script>+ <script src="../../resources/audit.js"></script>+ </head>+ <body>+ <script id="layout-test-code">+ let audit = Audit.createTaskRunner();++ audit.define('simple', (task, should) => {+ let context = new OfflineAudioContext(1, 1, 48000);+ let shaper = context.createWaveShaper();++ // Verify default values are correct.+ should(shaper.curve, 'Initial WaveShaper.curve').beEqualTo(null);+ should(shaper.oversample, 'Initial WaveShaper.oversample')+ .beEqualTo('none');++ // Set oversample and verify that it is set correctly.+ should(() => shaper.oversample = '2x', 'Setting oversample to "2x"')+ .notThrow();+ should(shaper.oversample, 'Waveshaper.oversample = "2x"')+ .beEqualTo('2x');++ should(() => shaper.oversample = '4x', 'Setting oversample to "4x"')+ .notThrow();+ should(shaper.oversample, 'Waveshaper.oversample = "4x"')+ .beEqualTo('4x');++ should(+ () => shaper.oversample = 'invalid',+ 'Setting oversample to "invalid"')+ .notThrow();+ should(shaper.oversample, 'Waveshaper.oversample = "invalid"')+ .beEqualTo('4x');++ // Set the curve and verify that the returned curve is the same as what+ // it was set to.+ let curve = Float32Array.from([-1, 0.25, .75]);+ should(() => shaper.curve = curve, 'Setting curve to [' + curve + ']')+ .notThrow();+ should(shaper.curve, 'WaveShaper.curve').beEqualToArray(curve);++ // Verify setting the curve to null works.+ should(() => shaper.curve = null, 'Setting curve back to null')+ .notThrow();+ should(shaper.curve, 'Waveshaper.curve = null').beEqualTo(null);++ task.done();+ });++ audit.run();+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper.htmlnew file mode 100644index 00000000000..fdb9fc1c1c2--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-waveshapernode-interface/waveshaper.html@@ -0,0 +1,133 @@+<!DOCTYPE html>+<html>+ <head>+ <title>+ waveshaper.html+ </title>+ <script src="../../../resources/testharness.js"></script>+ <script src="../../../resources/testharnessreport.js"></script>+ </head>+ <body>+ <script>++ const sampleRate = 44100;+ const lengthInSeconds = 4;+ const numberOfRenderFrames = sampleRate * lengthInSeconds;+ const numberOfCurveFrames = 65536;++ let context;+ let inputBuffer;+ let waveShapingCurve;++ function generateInputBuffer() {+ // Create mono input buffer.+ const buffer = new AudioBuffer({+ length: numberOfRenderFrames,+ numberOfChannels: 1,+ sampleRate: context.sampleRate+ });+ const data = buffer.getChannelData(0);++ // Generate an input vector with values from -1 -> +1 over a duration of+ // lengthInSeconds. This exercises the full nominal input range and will+ // touch every point of the shaping curve.+ for (let i = 0; i < numberOfRenderFrames; ++i) {+ let x = i / numberOfRenderFrames;+ x = 2 * x - 1;+ data[i] = x;+ }++ return buffer;+ }++ // Generates a symmetric curve: Math.atan(5 * x) / (0.5 * Math.PI)+ // (with x == 0 corresponding to the center of the array)+ // This curve is arbitrary, but would be useful in the real-world.+ // To some extent, the actual curve we choose is not important in this+ // test, since the input vector walks through all possible curve values.+ function generateWaveShapingCurve() {+ const curve = new Float32Array(numberOfCurveFrames);+ const n = numberOfCurveFrames;+ const n2 = n / 2;++ for (let i = 0; i < n; ++i) {+ const x = (i - n2) / n2;+ curve[i] = Math.atan(5 * x) / (0.5 * Math.PI);+ }+ return curve;+ }+ // Following spec algorithm from+ // https://webaudio.github.io/web-audio-api/#WaveShaperNode-attributes+ function checkShapedCurve(buffer) {+ const inputData = inputBuffer.getChannelData(0);+ const outputData = buffer.getChannelData(0);+ const c = waveShapingCurve;+ const N = numberOfCurveFrames;+ const tolerance = 1e-6;++ let firstMismatchIndex = -1;+ let actual = 0;+ let expected = 0;++ // Go through every sample and make sure it has been shaped exactly+ // according to the shaping curve we gave it.+ for (let i = 0; i < buffer.length; ++i) {+ const x = inputData[i];++ const v = ((N - 1) * 0.5) * (x + 1);+ const k = Math.floor(v);+ const f = v - k;++ let y;+ if (v < 0) {+ y = c[0];+ } else if (v >= N - 1) {+ y = c[N - 1];+ } else {+ y = (1 - f) * c[k] + f * c[k + 1];+ }++ if (Math.abs(outputData[i] - y) > tolerance) {+ firstMismatchIndex = i;+ actual = outputData[i];+ expected = y;+ break;+ }+ }++ assert_equals(+ firstMismatchIndex,+ -1,+ firstMismatchIndex === -1+ ? 'WaveShaperNode output should match the spec.'+ : `Mismatch at sample ${firstMismatchIndex}: ` ++ `actual = ${actual}, expected = ${expected}, ` ++ `tolerance = ${tolerance}`);+ }++ promise_test(async t => {+ // Create offline audio context.+ context = new OfflineAudioContext(1, numberOfRenderFrames, sampleRate);++ // source -> waveshaper -> destination+ const source = new AudioBufferSourceNode(context);+ const waveshaper = new WaveShaperNode(context);+ source.connect(waveshaper);+ waveshaper.connect(context.destination);++ // Create an input test vector.+ inputBuffer = generateInputBuffer();+ source.buffer = inputBuffer;++ // We'll apply non-linear distortion according to this shaping curve.+ waveShapingCurve = generateWaveShapingCurve();+ waveshaper.curve = waveShapingCurve;++ source.start();++ const renderedBuffer = await context.startRendering();+ checkShapedCurve(renderedBuffer);+ }, 'WaveShaperNode applies non-linear distortion correctly');+ </script>+ </body>+</html>