summaryrefslogtreecommitdiffstats
path: root/third_party/webkit/PerformanceTests/webaudio/webaudio-bench.js
blob: b4fb99612b33d477127965033719b5fff1248a2b (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
if (window.AudioContext == undefined) {
  window.AudioContext = window.webkitAudioContext;
  window.OfflineAudioContext = window.webkitOfflineAudioContext;
}

$ = document.querySelectorAll.bind(document);

let DURATION = null;
if (location.search) {
  let duration = location.search.match(/rendering-buffer-length=(\d+)/);
  if (duration) {
    DURATION = duration[1];
  } else {
    DURATION = 120;
  }
} else {
  DURATION = 120;
}


// Global sample rate at which we run the context.
var sampleRate = 48000;
// Array containing at first the url of the audio resources to fetch, and the
// the actual buffers audio buffer we have at our disposal to for tests.
var sources = [];
// Array containing the results, for each benchmark.
var results = [];
// Array containing the offline contexts used to run the testcases.
var testcases = [];
// Array containing the functions that can return a runnable testcase.
var testcases_registered = [];
// Array containing the audio buffers for each benchmark
var buffers = [];
var playingSource = null;
// audiocontext used to play back the result of the benchmarks
var ac = new AudioContext();

function getFile(source, callback) {
  var request = new XMLHttpRequest();
  request.open("GET", source.url, true);
  request.responseType = "arraybuffer";

  request.onload = function() {
    // decode buffer at its initial sample rate
    var ctx = new OfflineAudioContext(1, 1, source.sampleRate);

    ctx.decodeAudioData(request.response, function(buffer) {
      callback(buffer, undefined);
    }, function() {
      callback(undefined, "Error decoding the file " + source.url);
    });
  }
  request.send();
}

function recordResult(result) {
  results.push(result);
}

function benchmark(testcase, ended) {
  var context = testcase.ctx;
  var start;

  context.oncomplete = function(e) {
    var end = Date.now();
    recordResult({
      name: testcase.name,
      duration: end - start,
      buffer: e.renderedBuffer
    });
    ended();
  };

  start = Date.now();
  context.startRendering();
}

function getMonoFile() {
  return getSpecificFile({ numberOfChannels: 1 });
}

function getStereoFile() {
  return getSpecificFile({ numberOfChannels: 2 });
}

function matchIfSpecified(a, b) {
  if (b) {
    return a == b;
  }
  return true;
}

function getSpecificFile(spec) {
  for (var i = 0 ; i < sources.length; i++) {
    if (matchIfSpecified(sources[i].numberOfChannels, spec.numberOfChannels) &&
        matchIfSpecified(sources[i].sampleRate, spec.sampleRate)) {
      return sources[i];
    }
  }

  throw new Error("Could not find a file that matches the specs.");
}

function allDone() {
  document.getElementById("in-progress").style.display = "none";
  var result = document.getElementById("results");
  var str = "<table><thead><tr><td>Test name</td><td>Time in ms</td><td>Speedup vs. realtime</td><td>Sound</td></tr></thead>";
  var buffers_base = buffers.length;
  var product_of_durations = 1.0;

  for (var i = 0 ; i < results.length; i++) {
    var r = results[i];
    product_of_durations *= r.duration;
    str += "<tr><td>" + r.name + "</td>" +
               "<td>" + r.duration + "</td>"+
               "<td>" + Math.round((r.buffer.duration * 1000) / r.duration) + "x</td>"+
               "<td><button data-soundindex="+(buffers_base + i)+">Play</button> ("+r.buffer.duration+"s)</td>"
          +"</tr>";
    buffers[buffers_base + i] = r.buffer;
  }
  recordResult({
    name: "Geometric Mean",
    duration: Math.round(Math.pow(product_of_durations, 1.0/results.length)),
    buffer: {}
  });
  str += "</table>";
  result.innerHTML += str;
  result.addEventListener("click", function(e) {
    var t = e.target;
    if (t.dataset.soundindex != undefined) {
      if (playingSource != null) {
        playingSource.button.innerHTML = "Play";
        playingSource.onended = undefined;
        playingSource.stop(0);
        if (playingSource.button == t) {
          playingSource = null;
          return;
        }
      }
      playingSource = ac.createBufferSource();
      playingSource.connect(ac.destination);
      playingSource.buffer = buffers[t.dataset.soundindex];
      playingSource.start(0);
      playingSource.button = t;
      t.innerHTML = "Pause";
      playingSource.onended = function () {
        playingSource = null;
      }
    }
  });

  document.getElementById("run-all").disabled = false;

  if (location.search.includes("raptor")) {
    var _data = ['raptor-benchmark', 'webaudio', JSON.stringify(results)];
    window.postMessage(_data, '*');
    window.sessionStorage.setItem('benchmark_results',  JSON.stringify(_data));
  } else {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/results", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send("results=" + JSON.stringify(results));
  }
}

function runOne(i) {
  benchmark(testcases[i], function() {
    i++;
    $("#progress-bar")[0].value++;
    if (i < testcases.length) {
      runOne(i);
    } else {
      allDone();
    }
  });
}

function runAll() {
  $("#progress-bar")[0].max = testcases_registered.length;
  $("#progress-bar")[0].value = 0;
  initAll();
  results = [];
  runOne(0);
}

function initAll() {
  for (var i = 0; i < testcases_registered.length; i++) {
    testcases[i] = {};
    testcases[i].ctx = testcases_registered[i].func();
    testcases[i].name = testcases_registered[i].name;
  }
}

function loadOne(i, endCallback) {
  getFile(sources[i], function(buffer, err) {
    if (err) {
      throw new Error(msg);
    }

    sources[i] = buffer;
    i++;

    if (i < sources.length) {
      loadOne(i, endCallback);
    } else {
      endCallback();
    }
  });
}

function loadAllSources(endCallback) {
  loadOne(0, endCallback);
}

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("run-all").addEventListener("click", function() {
    document.getElementById("run-all").disabled = true;
    document.getElementById("in-progress").style.display = "inline";
    runAll();
  });
  loadAllSources(function() {
    // auto-run when running in raptor
    document.getElementById("loading").remove();
    document.getElementById("controls").style.display = "block";
    if (location.search.includes("raptor")) {
      document.getElementById("run-all").disabled = true;
      document.getElementById("in-progress").style.display = "inline";
      setTimeout(runAll, 100);
    }
  });
});

/* Public API */
function registerTestCase(testCase) {
  testcases_registered.push(testCase);
}

function registerTestFile(url) {
  sources.push(url);
}