<!DOCTYPE html>
<html>
  <head>
    <title>
      OfflineAudioContext - Thread Smoke Test
    </title>
    <script src="../../imported/w3c/web-platform-tests/resources/testharness.js"></script>
    <script src="../../resources/testharnessreport.js"></script>
    <script src="../resources/audit.js"></script>
  </head>
  <body>
    <script id="layout-test-code">
      const audit = Audit.createTaskRunner();

      // The common sample rate.
      const sampleRate = 48000;

      // To make channel count and buffer length irrelevant to this test.
      const numberOfChannels = 1;
      const renderLength = 1;

      // 1000 concurrent contexts caused this test to time out on Mac OS and
      // Linux. (See: crbug.com/1092145, crbug.com/741699)
      const maxNumberOfContexts = 500;

      let contexts = [];

      // For recursive and sequential rendering of multiple context.
      function recurseContextRendering(index, oncomplete) {
        if (index < maxNumberOfContexts) {
          contexts[index].startRendering().then(() => {
            recurseContextRendering(index + 1, oncomplete);
          });
        } else {
          oncomplete(index);
        }
      }

      // Create contexts up front, but do not start rendering. Based on
      // crbug.com/716800, this caused a crash with out-of-threads error.
      audit.define(
          {
            label: 'context-creation-smoketest',
            description:
                'Creating ' + maxNumberOfContexts + ' contexts up front.'
          },
          (task, should) => {
            let i;
            for (i = 0; i < maxNumberOfContexts; ++i) {
              contexts.push(new OfflineAudioContext(
                  numberOfChannels, renderLength, sampleRate));
            }
            should(i, 'The number of created contexts without a crash')
                .beEqualTo(maxNumberOfContexts);
            task.done();
          });

      // Create contexts, render and drop them sequentially. This should not
      // crash the browser with out-of-threads error.
      audit.define(
          {
            label: 'rendering-thread-smoketest',
            description:
                'Rendering ' + maxNumberOfContexts + ' contexts sequentially.'
          },
          (task, should) => {
            recurseContextRendering(0, (counter) => {
              should(counter, 'The number of contexts rendered without a crash')
                  .beEqualTo(maxNumberOfContexts);
              task.done();
            });
          });

      audit.run();
    </script>
  </body>
</html>
