<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>mozilla on blog</title>
    <link>https://blog.paul.cx/tags/mozilla/</link>
    <description>Recent content in mozilla on blog</description>
    <generator>Hugo -- gohugo.io</generator>
    <lastBuildDate>Mon, 06 Jun 2022 15:42:00 +0200</lastBuildDate>
    
        <atom:link href="https://blog.paul.cx/tags/mozilla/index.xml" rel="self" type="application/rss+xml" />
    
    
      
    <item>
      <title>A wait-free single-producer single-consumer ring buffer for the Web</title>
      <link>https://blog.paul.cx/post/a-wait-free-spsc-ringbuffer-for-the-web/</link>
      <pubDate>Mon, 06 Jun 2022 15:42:00 +0200</pubDate>
      
      <guid>https://blog.paul.cx/post/a-wait-free-spsc-ringbuffer-for-the-web/</guid>
      <description>&lt;script src=&#34;https://cdn.jsdelivr.net/npm/chart.js&#34;&gt;&lt;/script&gt;
&lt;h1 id=&#34;introduction&#34;&gt;Introduction&lt;/h1&gt;
&lt;p&gt;On top of other performance characteristics desired by most software, such as
execution speed, any audio real-time audio software needs to have predictable
performance. This has been covered in a &lt;a href=&#34;https://blog.paul.cx/post/profiling-firefox-real-time-media-workloads/&#34;&gt;previous post&lt;/a&gt;, and &lt;a href=&#34;http://www.rossbencina.com/code/real-time-audio-programming-101-time-waits-for-nothing&#34;&gt;in this classic article&lt;/a&gt;
(and lots of others). This applies to native software and software written
using web technologies alike.&lt;/p&gt;
&lt;p&gt;The increase in availability and performance of &lt;a href=&#34;https://developer.mozilla.org/en-US/docs/WebAssembly&#34;&gt;Web
Assembly&lt;/a&gt;, and the
somewhat recent
&lt;a href=&#34;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/Planned_changes&#34;&gt;return&lt;/a&gt;
of
&lt;a href=&#34;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer&#34;&gt;&lt;code&gt;SharedArrayBuffer&lt;/code&gt;&lt;/a&gt;
is exciting news for audio programmers. It is especially interesting for
developers used to the usual programming techniques employed when programming
on native platforms, such as SIMD and lock-free concurrency.&lt;/p&gt;
&lt;p&gt;After exposing a number of problems related to communication to and from a
real-time audio thread, the possible alternative, and the reason
why they are not acceptable, this post presents a small JavaScript library
(about 1.3kB gzipped), with no dependency and with a permissive license, that
aims at solving the problem.&lt;/p&gt;
&lt;p&gt;It allows developers to easily communicate with an &lt;code&gt;AudioWorkletGlobalScope&lt;/code&gt;
from the browser main thread or a Web Worker thread, in a way that is both
real-time safe, performant and ergonomic.&lt;/p&gt;
&lt;h1 id=&#34;communicating-with-a-real-time-thread-in-native&#34;&gt;Communicating with a real-time thread, in native&lt;/h1&gt;
&lt;p&gt;In native real-time audio programming, a common design is to have a &lt;em&gt;single&lt;/em&gt;
real-time audio thread. It is set to have a high priority, often using a
different scheduling class. In addition, real-time audio programs run other
threads, such as a main thread to render the UI, threads to perform input/output
operations on disk or using the network, and other threads to offload bits of
real-time processing, such as computing &lt;a href=&#34;https://searchfox.org/mozilla-central/source/dom/media/webaudio/blink/ReverbConvolver.cpp&#34;&gt;expensive
convolutions&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;All those support threads need to communicate with each other, but more
importantly with the real-time audio thread. In turn, the real-time audio thread
frequently wants to send data back to other threads, for example to update
visuals, record audio to a file, or any other task that doesn&amp;rsquo;t &lt;em&gt;have to&lt;/em&gt; or
&lt;em&gt;can&amp;rsquo;t&lt;/em&gt; be on the real-time audio thread.&lt;/p&gt;
&lt;p&gt;Since we can&amp;rsquo;t have the real-time audio thread wait on any other thread, or
otherwise do anything potentially unbounded in time, the following constructs
are &lt;em&gt;usually&lt;/em&gt; not recommended (this list is by no means complete):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;using operating system locks, such as &lt;code&gt;pthread_mutex_t&lt;/code&gt;,
&lt;a href=&#34;https://docs.microsoft.com/en-us/windows/win32/sync/critical-section-objects&#34;&gt;&lt;code&gt;CRITICAL_SECTION&lt;/code&gt;&lt;/a&gt;,
&lt;a href=&#34;https://docs.microsoft.com/en-us/windows/win32/sync/slim-reader-writer--srw--locks&#34;&gt;&lt;code&gt;SRWLOCK&lt;/code&gt;&lt;/a&gt;
to protect data accessed by the real-time audio thread, and other
blocking concurrency mechanism (reading on a &lt;code&gt;pipe&lt;/code&gt;, semaphores, etc.)&lt;/li&gt;
&lt;li&gt;waiting on a condition variable (or even signaling them in some cases)&lt;/li&gt;
&lt;li&gt;making any kind of IO, using quite a lot of system calls&lt;/li&gt;
&lt;li&gt;performing operations that can cause garbage collection pauses, even though
garbage collectors are &lt;em&gt;really&lt;/em&gt; fast these days&lt;/li&gt;
&lt;li&gt;dynamically allocating memory using the system allocator (this uses system calls)&lt;/li&gt;
&lt;li&gt;copying a large amount of memory&lt;/li&gt;
&lt;li&gt;using spin locks, either provided by the OS, or custom (this one is not a hard
rule and is sometimes useful)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It&amp;rsquo;s no surprise that real-time audio programmers are very often using atomic
memory access facilities, and rely on
&lt;a href=&#34;https://www.youtube.com/watch?v=Q0vrQFyAdWI&#34;&gt;tried&lt;/a&gt; and
&lt;a href=&#34;https://www.youtube.com/watch?v=PoZAo2Vikbo&#34;&gt;true&lt;/a&gt; patterns to implement
complex but unavoidable communication schemes between the various threads of an
application.&lt;/p&gt;
&lt;h1 id=&#34;communicating-with-a-real-time-thread-on-the-web&#34;&gt;Communicating with a real-time thread, on the Web&lt;/h1&gt;
&lt;p&gt;In a Web Browser, things are a little different, but largely similar when
squinting a bit.&lt;/p&gt;
&lt;p&gt;The equivalent of the real-time audio thread on the Web is the
&lt;code&gt;AudioWorkletGlobalScope&lt;/code&gt;, inside which reside one or multiple
&lt;code&gt;AudioWorkletProcessor&lt;/code&gt;, with their methods called on a thread made real-time.&lt;/p&gt;
&lt;p&gt;The browser main thread often handles the UI (although
&lt;a href=&#34;https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas&#34;&gt;&lt;code&gt;OffscreenCanvas&lt;/code&gt;&lt;/a&gt;
exists and is an appealing solution). There are multiple ways to do networks and
disk IO, implemented by the browser, communicating the progress of these
operations asynchronously with either Web Workers or the browser main thread.&lt;/p&gt;
&lt;p&gt;Regular OS threads can be spawned using &lt;a href=&#34;https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers&#34;&gt;Web
Workers&lt;/a&gt;.
There is no way to change the priority of the underlying thread of a Worker at
the moment.&lt;/p&gt;
&lt;table&gt;
&lt;caption&gt;Counterparts of native threading concepts on the Web platform&lt;/caption&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;td&gt;
Native
&lt;/td&gt;
&lt;td&gt;
Web
&lt;/td&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;
Real-time audio thread (callback)
&lt;/td&gt;
&lt;td&gt;
AudioWorkletProcessor methods
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
Main application thread
&lt;/td&gt;
&lt;td&gt;
Browser main thread
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
IO threads (sync/async/etc.)
&lt;/td&gt;
&lt;td&gt;
Asynchronous &lt;code&gt;fetch&lt;/code&gt;, &lt;code&gt;IndexedDB&lt;/code&gt;, etc.
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
Regular OS thread
&lt;/td&gt;
&lt;td&gt;
Web Worker
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
High or low-priority OS thread
&lt;/td&gt;
&lt;td&gt;
No equivalent
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;In terms of concurrency mechanism, it&amp;rsquo;s a lot simpler than native. &lt;em&gt;Almost&lt;/em&gt;
everything is synchronized via the event loop of various threads, workers and
worklets. Communication happens using message passing, using the
&lt;code&gt;postMessage(...)&lt;/code&gt; method. It&amp;rsquo;s possible to copy the argument passed to
&lt;code&gt;postMessage(...)&lt;/code&gt;, so that they are still accessible at the call-site, but it&amp;rsquo;s
also possible to &lt;a href=&#34;https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage#transfer&#34;&gt;transfer
ownership&lt;/a&gt;
of the object, and this is
&lt;a href=&#34;https://www.w3.org/2021/03/media-production-workshop/talks/paul-adenot-webcodecs-performance.html&#34;&gt;essential&lt;/a&gt;
when moving &lt;em&gt;large&lt;/em&gt; pieces of memory around. In native lingo, this is like
sending a pointer to a large buffer to another thread.&lt;/p&gt;
&lt;p&gt;There is exactly one object that allows multiple threads to access the same
piece of memory concurrently, called the &lt;code&gt;SharedArrayBuffer&lt;/code&gt;. From a distance,
it looks like a regular &lt;code&gt;ArrayBuffer&lt;/code&gt;, but the key difference is that when
passed to &lt;code&gt;postMessage(...)&lt;/code&gt;, it is still available at the call site, in
addition to being available at the destination. It is to be used in tandem with
the &lt;code&gt;Atomics&lt;/code&gt; objects, that has various static methods to perform the usual
store, load, exchange, arithmetic operations, and compare and exchange
operations.&lt;/p&gt;
&lt;p&gt;Additionally, it provides a &lt;code&gt;wait&lt;/code&gt; and a &lt;code&gt;notify&lt;/code&gt; method, although
&lt;code&gt;wait&lt;/code&gt; is not available in the &lt;code&gt;AudioWorkletGlobalScope&lt;/code&gt;, and &lt;code&gt;notify&lt;/code&gt; is most
probably unsafe to use from a real-time thread cross-platform, since it takes a
lock on at least some platforms.&lt;/p&gt;
&lt;h1 id=&#34;why-is-postmessage-not-ok-&#34;&gt;Why is postMessage(&amp;hellip;) not OK ?&lt;/h1&gt;
&lt;p&gt;One could think that &lt;code&gt;postMessage(...)&lt;/code&gt; is perfect for real-time audio, it&amp;rsquo;s
message passing after all. It could have been, but it&amp;rsquo;s not the case in
practice.&lt;/p&gt;
&lt;p&gt;First &lt;code&gt;postMessage(...)&lt;/code&gt; can be rather slow, depending on the implementation,
but this is fixable by browser vendors. &lt;a href=&#34;https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm&#34;&gt;Structured
cloning&lt;/a&gt;
is applied to objects sent via &lt;code&gt;postMessage(...)&lt;/code&gt; with a serialization and
deserialization step, which is frequently unnecessary for real-time audio. More
concerning is that this &lt;em&gt;structured cloning&lt;/em&gt; algorithm creates new JavaScript
objects on its receiving end when a message is transmitted, which can create
garbage to collect. Garbage Collector are extremely fast, but still not
deterministic in JavaScript VMs. It&amp;rsquo;s best to not risk it for production
software.&lt;/p&gt;
&lt;p&gt;Then, looking under the hood, it becomes clear that implementations are taking
locks and using all sorts of forbidden constructs such as allocating memory and
doing system calls in the innards of &lt;code&gt;postMessage(...)&lt;/code&gt; and the associated event
dispatching machinery (on the receiving end, on the &lt;code&gt;onmessage&lt;/code&gt; handler).&lt;/p&gt;
&lt;p&gt;In any case, one cannot avoid the use of &lt;code&gt;postMessage(...)&lt;/code&gt;, for example to send
large &lt;code&gt;ArrayBuffer&lt;/code&gt;s or Web Assembly modules to an &lt;code&gt;AudioWorkletGlobalScope&lt;/code&gt;,
but it&amp;rsquo;s best to not use it for continuously sending data to the real-time
thread, and receiving results from it. Modern GCs deal with rare and short-lived
object allocations very well in practice.&lt;/p&gt;
&lt;h1 id=&#34;the-alternative-presenting-ringbufjs&#34;&gt;The alternative, presenting &lt;code&gt;ringbuf.js&lt;/code&gt;&lt;/h1&gt;
&lt;p&gt;The Single-Producer Single-Consumer wait-free ring buffer (often called SPSC
ring buffer) is often regarded as the bread and butter data structure for
concurrency in real-time audio programming, and
&lt;a href=&#34;https://github.com/padenot/ringbuf.js&#34;&gt;&lt;code&gt;ringbuf.js&lt;/code&gt;&lt;/a&gt; is a version written in
JavaScript, using &lt;code&gt;SharedArrayBuffer&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;It allows communicating between a producer thread and a consumer thread (which
cannot change roles without external synchronization) without blocking or
waiting.&lt;/p&gt;
&lt;p&gt;The core data structure only supports sending integers and floating point values
of varying width, but it&amp;rsquo;s easy to create adapters for more complex data
transfer. Two abstractions are also provided, one for sending &lt;a href=&#34;https://github.com/padenot/ringbuf.js/blob/master/js/param.js&#34;&gt;parameter
changes&lt;/a&gt;
(consisting of an integer for the parameter index and a float for the parameter
value), and sending an &lt;a href=&#34;https://github.com/padenot/ringbuf.js/blob/master/js/audioqueue.js&#34;&gt;interleaved audio
stream&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;It is written in a strange style of JavaScript, in a way that will not create
any object, so that garbage collection won&amp;rsquo;t happen &lt;sup id=&#34;fnref:1&#34;&gt;&lt;a href=&#34;#fn:1&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;, but it&amp;rsquo;s also quite
readable I find. It clocks in at 137 lines of code for 173 lines of comment in
the current version, which is a sane ratio for any lock-free code.&lt;/p&gt;
&lt;p&gt;Hopefully the API is good enough to use. It has been put to the test in a couple
projects already, and we&amp;rsquo;ve used it for a &lt;a href=&#34;https://github.com/chcunningham/wc-talk&#34;&gt;conference
demo&lt;/a&gt;, reimplementing a toy
&lt;code&gt;HTMLVideoElement&lt;/code&gt; with Web Codecs, the Web Audio API and a &lt;code&gt;&amp;lt;canvas&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s &lt;a href=&#34;https://github.com/padenot/ringbuf.js/blob/main/LICENSE&#34;&gt;MPL-licensed&lt;/a&gt;,
allowing the use in closed-source programs, &lt;a href=&#34;https://github.com/padenot/ringbuf.js/tree/master/tests&#34;&gt;well
tested&lt;/a&gt;, &lt;a href=&#34;https://github.com/padenot/ringbuf.js/actions/workflows/test.yml&#34;&gt;stress tested
in CI&lt;/a&gt;, has
&lt;a href=&#34;https://ringbuf-js.netlify.app/doc/&#34;&gt;extensive documentation&lt;/a&gt; and two practical
example to &lt;a href=&#34;https://ringbuf-js.netlify.app/&#34;&gt;try&lt;/a&gt; and
&lt;a href=&#34;https://github.com/padenot/ringbuf.js/tree/master/public/example&#34;&gt;read&lt;/a&gt; to get
started. Thanks to the help of a &lt;a href=&#34;https://github.com/padenot/ringbuf.js/graphs/contributors&#34;&gt;number of
contributors&lt;/a&gt;, it&amp;rsquo;s
packaged for use in modern web apps, and available on
&lt;a href=&#34;https://www.npmjs.com/package/ringbuf.js&#34;&gt;NPM&lt;/a&gt; &lt;sup id=&#34;fnref:2&#34;&gt;&lt;a href=&#34;#fn:2&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;. It also runs on &lt;code&gt;Node.js&lt;/code&gt;.&lt;/p&gt;
&lt;h1 id=&#34;benchmarks&#34;&gt;Benchmarks&lt;/h1&gt;
&lt;p&gt;In lieu of proper serious benchmarks, I&amp;rsquo;m going to link to &lt;a href=&#34;https://jackschaedler.github.io/&#34;&gt;Jack Schaedler&lt;/a&gt;&amp;lsquo;s
&lt;a href=&#34;https://paul.cx/public/karplus-stress-tester/&#34;&gt;&lt;code&gt;karplus-stress-tester&lt;/code&gt;
page&lt;/a&gt;&lt;sup id=&#34;fnref:3&#34;&gt;&lt;a href=&#34;#fn:3&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;, and offer some
results on the machines I have around &lt;sup id=&#34;fnref:4&#34;&gt;&lt;a href=&#34;#fn:4&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;4&lt;/a&gt;&lt;/sup&gt;, comparing &lt;code&gt;postMessage(...)&lt;/code&gt; and
something based on &lt;code&gt;ringbuf.js&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;This web app runs a large number of identical copies of the &lt;a href=&#34;https://en.wikipedia.org/wiki/Karplus%E2%80%93Strong_string_synthesis&#34;&gt;famous digital
signal processing
algorithm&lt;/a&gt;,
either in JavaScript and WASM, and offers a variety of configuration options.
Its goal is to try to understand what sort of architecture and techniques are
the best for real-time audio on the Web. It then allows to load the real-time
audio thread arbitrarily by adding more strings to simulate. Like a &amp;ldquo;real&amp;rdquo;
real-time audio application, bidirectional communication, to and from the
real-time audio thread, happens periodically, respectively to strum the string,
and to visualize their amplitude and vibration characteristics on the main
thread.&lt;/p&gt;
&lt;p&gt;Here, I&amp;rsquo;m setting 100 strings per worklet, I then choose a particular
communication method (&lt;code&gt;postMessage&lt;/code&gt; or &lt;code&gt;SharedArrayBuffer&lt;/code&gt;), always use the WASM
processor, tick the &amp;ldquo;Visualize string state&amp;rdquo; checkbox to generate some main
thread load.&lt;/p&gt;
&lt;p&gt;I then increase the amount of strings until I can detect &lt;em&gt;any&lt;/em&gt; glitch when &amp;ldquo;strum
all&amp;rdquo; has been clicked. I consider a workload stable when there are precisely zero
glitches for a long period of time, and I scale the number of string down as
soon as &lt;em&gt;any&lt;/em&gt; glitch is heard.&lt;/p&gt;
&lt;p&gt;
  &lt;canvas id=&#34;perf-comparison&#34;&gt;&lt;/canvas&gt;
&lt;/p&gt;
&lt;script&gt;
const data = {
  labels: [
    &#34;Firefox Nightly, Linux&#34;,
    &#34;Chrome Beta, Linux&#34;,
    &#34;Firefox Nightly, macOS&#34;,
    &#34;Chrome Beta, macOS&#34;
  ],
  datasets: [
    {
      label: &#39;postMessage&#39;,
      data: [400, 600, 600, 600],
      borderColor: &#34;rgb(34, 136, 51)&#34;,
      backgroundColor: &#34;rgba(34, 136, 51, 0.5)&#34;,
      borderRadius: &#34;4&#34;
    },
    {
      label: &#39;SharedArrayBuffer&#39;,
      data: [1500, 1500, 3000, 3000],
      borderColor: &#34;rgb(68, 119, 170)&#34;,
      backgroundColor: &#34;rgba(68, 119, 170, 0.5)&#34;,
      borderRadius: &#34;4&#34;
    }
  ]
};
const config = {
  type: &#39;bar&#39;,
  data: data,
  options: {
    responsive: true,
    plugins: {
      legend: {
        position: &#39;bottom&#39;,
      },
      title: {
        display: true,
        text: &#39;SharedArrayBuffer vs. postMessage&#39;,
        position: &#39;top&#39;,
        padding: { bottom: 10 }
      },
      subtitle: {
        display: true,
        text: &#39;String count without under-runs, higher is better&#39;,
        position: &#39;top&#39;,
        padding: { bottom: 20 }
      }
    },
    scales:{
      y: { min: 0, max: 3500 }
    }
  }
};
const perfComparison = new Chart(
  document.getElementById(&#39;perf-comparison&#39;),
  config
);
&lt;/script&gt;
&lt;p&gt;On the macOS machine, Chrome and Firefox don&amp;rsquo;t even glitch at 3000 string, but
that&amp;rsquo;s the maximum the page&amp;rsquo;s user interface allows setting. Here, we see that
one can expect 2.5x to 6x increase in load capacity if switching to a wait-free
communication technique, compared to using &lt;code&gt;postMessage&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;In summary, &lt;strong&gt;it&amp;rsquo;s night and day&lt;/strong&gt; on this benchmark. Wait-free concurrency is
bound to be superior to superior to &lt;code&gt;postMessage(...)&lt;/code&gt; in most real-time audio
use-cases. The same type of results have been observed by other users of this
library.&lt;/p&gt;
&lt;h1 id=&#34;api-primer&#34;&gt;API primer&lt;/h1&gt;
&lt;p&gt;The API of &lt;code&gt;ringbuf.js&lt;/code&gt; is maybe slightly non-standard for JavaScript
developers, but there are good reasons for this: limiting allocations, and
limiting memory copies.&lt;/p&gt;
&lt;p&gt;Given a 1000 element ring buffer that can hold 32-bits floating point values:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre class=&#34;chroma&#34;&gt;&lt;code class=&#34;language-js&#34; data-lang=&#34;js&#34;&gt;&lt;span class=&#34;kd&#34;&gt;var&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;backingStorage&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;RingBuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;getStorageForCapacity&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;mi&#34;&gt;1000&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;Float32Array&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;span class=&#34;kd&#34;&gt;var&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;ringbuffer&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;k&#34;&gt;new&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;RingBuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;backingStorage&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;Float32Array&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Enqueueing data into the ring buffer looks pretty straightforward:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre class=&#34;chroma&#34;&gt;&lt;code class=&#34;language-js&#34; data-lang=&#34;js&#34;&gt;&lt;span class=&#34;kd&#34;&gt;var&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;noise&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;k&#34;&gt;new&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;Float32Array&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;mi&#34;&gt;32&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;span class=&#34;k&#34;&gt;for&lt;/span&gt; &lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;kd&#34;&gt;let&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;0&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;32&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt;&lt;span class=&#34;o&#34;&gt;++&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;)&lt;/span&gt; &lt;span class=&#34;p&#34;&gt;{&lt;/span&gt; 
  &lt;span class=&#34;nx&#34;&gt;noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;[&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;]&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nb&#34;&gt;Math&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;random&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;()&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;*&lt;/span&gt; &lt;span class=&#34;mf&#34;&gt;0.5&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;-&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;1&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt;
&lt;span class=&#34;p&#34;&gt;}&lt;/span&gt;

&lt;span class=&#34;kd&#34;&gt;let&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;enqueued&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;ringbuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;push&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;span class=&#34;nx&#34;&gt;console&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;log&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;sb&#34;&gt;`{enqueued} elements enqueued`&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The &lt;code&gt;push&lt;/code&gt; operation is real-time safe, and is guaranteed to never block. The
input array can be a view on another memory region, or alternatively the method
can take an offset and an element count, so it&amp;rsquo;s possible to push only a portion
of a larger buffer, for example here the last 32 elements of a 512 elements
buffer:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre class=&#34;chroma&#34;&gt;&lt;code class=&#34;language-js&#34; data-lang=&#34;js&#34;&gt;&lt;span class=&#34;kd&#34;&gt;var&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;noise&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;k&#34;&gt;new&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;Float32Array&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;mi&#34;&gt;512&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;span class=&#34;k&#34;&gt;for&lt;/span&gt; &lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;kd&#34;&gt;let&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;0&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;512&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt;&lt;span class=&#34;o&#34;&gt;++&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;)&lt;/span&gt; &lt;span class=&#34;p&#34;&gt;{&lt;/span&gt; 
  &lt;span class=&#34;nx&#34;&gt;noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;[&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;]&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nb&#34;&gt;Math&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;random&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;()&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;*&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;2&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;-&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;1&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt;
&lt;span class=&#34;p&#34;&gt;}&lt;/span&gt;

&lt;span class=&#34;kd&#34;&gt;let&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;enqueued&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;ringbuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;push&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;512&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;-&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;32&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;32&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;span class=&#34;nx&#34;&gt;console&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;log&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;sb&#34;&gt;`{enqueued} elements enqueued`&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;In any case the number of elements successfully enqueued is returned, and the
source array is not modified, so it&amp;rsquo;s possible to push them at a later time.&lt;/p&gt;
&lt;p&gt;Dequeuing from a ring buffer is less natural, but will be familiar to
native developers:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre class=&#34;chroma&#34;&gt;&lt;code class=&#34;language-js&#34; data-lang=&#34;js&#34;&gt;&lt;span class=&#34;kd&#34;&gt;var&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;output&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;k&#34;&gt;new&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;Float32Array&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;mi&#34;&gt;512&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;span class=&#34;kd&#34;&gt;let&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;dequeued&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;ringbuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;pop&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;output&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;32&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;128&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;span class=&#34;nx&#34;&gt;console&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;log&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;sb&#34;&gt;`{dequeued} elements dequeued`&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Passing in an array into the &lt;code&gt;pop&lt;/code&gt; method allows saving an allocation, and
potentially a copy. This method is also real-time safe, specifically wait-free.&lt;/p&gt;
&lt;p&gt;It is possible to ask if the buffer is full, empty, and the number of elements
available for reading or writing with the methods of the same name:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre class=&#34;chroma&#34;&gt;&lt;code class=&#34;language-js&#34; data-lang=&#34;js&#34;&gt;&lt;span class=&#34;nx&#34;&gt;console&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;log&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;ringbuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;empty&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;());&lt;/span&gt;
&lt;span class=&#34;nx&#34;&gt;console&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;log&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;ringbuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;full&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;());&lt;/span&gt;
&lt;span class=&#34;nx&#34;&gt;console&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;log&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;ringbuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;available_read&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;());&lt;/span&gt;
&lt;span class=&#34;nx&#34;&gt;console&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;log&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;ringbuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;available_read&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Two last methods are available in the API. By passing a number of elements to
write and a callback to the ring buffer, the callback is called with two
buffers, where elements can be written to. This can potentially help to save
copies or allocations, for example to have a particular processing or synthesis
pass write its output directly in the ring buffer.&lt;/p&gt;
&lt;p&gt;This method has two versions: one that doesn&amp;rsquo;t GC but has a slightly
lower level API (suitable for real-time threads), and a version that can GC
because it creates small object wrappers, but the API is a bit more ergonomic:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre class=&#34;chroma&#34;&gt;&lt;code class=&#34;language-js&#34; data-lang=&#34;js&#34;&gt;&lt;span class=&#34;kd&#34;&gt;function&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;fill_noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;buf&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;count&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;buf&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;len&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;offset&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;0&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;)&lt;/span&gt; &lt;span class=&#34;p&#34;&gt;{&lt;/span&gt;
  &lt;span class=&#34;kd&#34;&gt;var&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;len&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;offset&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;==&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;0&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;?&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;count&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;:&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;count&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;+&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;offset&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt;
  &lt;span class=&#34;k&#34;&gt;for&lt;/span&gt; &lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;kd&#34;&gt;var&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;offset&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;len&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt;&lt;span class=&#34;o&#34;&gt;++&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;)&lt;/span&gt; &lt;span class=&#34;p&#34;&gt;{&lt;/span&gt;
    &lt;span class=&#34;nx&#34;&gt;buf&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;[&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;i&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;]&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nb&#34;&gt;Math&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;random&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;()&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;*&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;2&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;-&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;1&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt;
  &lt;span class=&#34;p&#34;&gt;}&lt;/span&gt;
&lt;span class=&#34;p&#34;&gt;}&lt;/span&gt;

&lt;span class=&#34;kd&#34;&gt;function&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;write_noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;storage&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;offset1&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;count1&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;offset2&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;count2&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;)&lt;/span&gt; &lt;span class=&#34;p&#34;&gt;{&lt;/span&gt;
  &lt;span class=&#34;nx&#34;&gt;fill_noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;first_part&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;count1&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;offset1&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
  &lt;span class=&#34;nx&#34;&gt;fill_noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;second_part&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;count2&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;offset2&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
  &lt;span class=&#34;c1&#34;&gt;// implied if no return value, can be lower
&lt;/span&gt;&lt;span class=&#34;c1&#34;&gt;&lt;/span&gt;  &lt;span class=&#34;k&#34;&gt;return&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;count1&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;+&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;count2&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt;
&lt;span class=&#34;p&#34;&gt;}&lt;/span&gt;

&lt;span class=&#34;c1&#34;&gt;// The maximum number of elements to be appended to the queue in the following
&lt;/span&gt;&lt;span class=&#34;c1&#34;&gt;// calls, it&amp;#39;s possible to notify the ring buffer that less elements have been
&lt;/span&gt;&lt;span class=&#34;c1&#34;&gt;// enqueued.
&lt;/span&gt;&lt;span class=&#34;c1&#34;&gt;&lt;/span&gt;&lt;span class=&#34;kd&#34;&gt;let&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;element_count&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;mi&#34;&gt;256&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt;

&lt;span class=&#34;c1&#34;&gt;// GC-free version
&lt;/span&gt;&lt;span class=&#34;c1&#34;&gt;&lt;/span&gt;&lt;span class=&#34;kd&#34;&gt;let&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;wrote&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;ringbuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;writeCallbackWithOffset&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;element_count&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;write_noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;span class=&#34;nx&#34;&gt;console&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;log&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;sb&#34;&gt;`{wrote} elements enqueued.`&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;

&lt;span class=&#34;c1&#34;&gt;// Ergonomic version that can trigger GC
&lt;/span&gt;&lt;span class=&#34;c1&#34;&gt;&lt;/span&gt;&lt;span class=&#34;kd&#34;&gt;let&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;wrote&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;=&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;ringbuffer&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;writeCallback&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;
  &lt;span class=&#34;nx&#34;&gt;element_count&lt;/span&gt;
  &lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;buffer1&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;,&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;buffer2&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;)&lt;/span&gt; &lt;span class=&#34;p&#34;&gt;=&amp;gt;&lt;/span&gt; &lt;span class=&#34;p&#34;&gt;{&lt;/span&gt;
    &lt;span class=&#34;nx&#34;&gt;fill_noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;buffer1&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
    &lt;span class=&#34;nx&#34;&gt;fill_noise&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;buffer2&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
    &lt;span class=&#34;c1&#34;&gt;// implied if no return value, can be lower
&lt;/span&gt;&lt;span class=&#34;c1&#34;&gt;&lt;/span&gt;    &lt;span class=&#34;k&#34;&gt;return&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;buffer1&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;length&lt;/span&gt; &lt;span class=&#34;o&#34;&gt;+&lt;/span&gt; &lt;span class=&#34;nx&#34;&gt;buffer2&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;length&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;;&lt;/span&gt;
  &lt;span class=&#34;p&#34;&gt;}&lt;/span&gt;
&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;span class=&#34;nx&#34;&gt;console&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;.&lt;/span&gt;&lt;span class=&#34;nx&#34;&gt;log&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;(&lt;/span&gt;&lt;span class=&#34;sb&#34;&gt;`{wrote} elements enqueued.`&lt;/span&gt;&lt;span class=&#34;p&#34;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h1 id=&#34;examples&#34;&gt;Examples&lt;/h1&gt;
&lt;p&gt;Two examples are available, to show two tasks audio developers frequently
have to implement (warning: they make noise, clicking the start button will
produce sound):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://ringbuf-js.netlify.app/example/audioworklet-to-worker/&#34;&gt;Recording the output&lt;/a&gt; of an
&lt;code&gt;AudioWorkletProcessor&lt;/code&gt;, sending it to a Web Worker for further non-real-time
or soft-real-time processing such as encoding, and then performing some IO on
the encoded data. This demonstrates how to communicate directly between a
Web Worker and an &lt;code&gt;AudioWorkletProcessor&lt;/code&gt;, without touching the main thread.&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://ringbuf-js.netlify.app/example/main-thread-to-audioworklet/&#34;&gt;Generating audio on the main thread&lt;/a&gt;,
and playing it using an &lt;code&gt;AudioWorkletProcessor&lt;/code&gt;, &lt;em&gt;e.g.&lt;/em&gt; to implement a &lt;a href=&#34;https://wiki.libsdl.org/SDL_QueueAudio&#34;&gt;push-based audio
API&lt;/a&gt;. While not recommended in general,
this is very useful, for example to implement emulators for older systems (where
everything was on a single thread). This demonstrates how to use &lt;code&gt;audioqueue.js&lt;/code&gt;
and &lt;code&gt;param.js&lt;/code&gt;, the two thin abstractions over the base class provided in the
library.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;They are interactive and hosted on a mini-site that has other pieces of info:
&lt;a href=&#34;https://ringbuf-js.netlify.app/&#34;&gt;https://ringbuf-js.netlify.app/&lt;/a&gt;.&lt;/p&gt;
&lt;h1 id=&#34;outro&#34;&gt;Outro&lt;/h1&gt;
&lt;p&gt;Despite &lt;em&gt;dramatically&lt;/em&gt; increasing the performance of most real-time audio
workloads that use &lt;code&gt;AudioWorkletProcessor&lt;/code&gt;s, I don&amp;rsquo;t really find using a
solution based on &lt;code&gt;ringbuf.js&lt;/code&gt; particularly more complex than something using
&lt;code&gt;postMessage(...)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Developers should probably consider this library as a building block, and use
higher-level but zero-cost abstractions in their code. Again, two very common
abstractions are available in the same package:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://github.com/padenot/ringbuf.js/blob/main/js/audioqueue.js&#34;&gt;&lt;code&gt;audioqueue.js&lt;/code&gt;&lt;/a&gt;
allows sending &lt;a href=&#34;https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#planar_versus_interleaved_buffers&#34;&gt;interleaved audio frames
&lt;/a&gt; through the queue&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://github.com/padenot/ringbuf.js/blob/main/js/param.js&#34;&gt;&lt;code&gt;params.js&lt;/code&gt;&lt;/a&gt;
allows sending parameter changes through the queue. A parameter is defined as
a pair, composed of an index and a floating point value, but one could imagine
sending any &lt;code&gt;struct&lt;/code&gt; using very similar code.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The library is at &lt;a href=&#34;https://www.npmjs.com/package/ringbuf.js&#34;&gt;version 0.3&lt;/a&gt;, but
should be fairly stable in terms of API, with no breaking change expected. The
only requirement really is the availability of &lt;code&gt;SharedArrayBuffer&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;As always, I welcome all contributions, and make sure to let me know if you find
something to improve!&lt;/p&gt;
&lt;p&gt;Now, let&amp;rsquo;s all push our real-time audio web app further with the new performance
budget, and then we&amp;rsquo;ll find the next thing to optimize!&lt;/p&gt;
&lt;p&gt;And who knows, maybe other types of applications can benefit from it?&lt;/p&gt;
&lt;section class=&#34;footnotes&#34; role=&#34;doc-endnotes&#34;&gt;
&lt;hr&gt;
&lt;ol&gt;
&lt;li id=&#34;fn:1&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;At least in Firefox, I&amp;rsquo;m not sure about others, but probably the same? &lt;a href=&#34;#fnref:1&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:2&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;Something that might be missing is binding definitions for folks using
TypeScript, but I&amp;rsquo;m not sure how to do this yet, please get in touch if you
want to help. &lt;a href=&#34;#fnref:2&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:3&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;Re-hosted with permission on a server that sets the
&lt;a href=&#34;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/Planned_changes&#34;&gt;appropriate headers&lt;/a&gt;
for  &lt;code&gt;SharedArrayBuffer&lt;/code&gt; to be available. The source is at &lt;a href=&#34;https://github.com/jackschaedler/karplus-stress-tester&#34;&gt;https://github.com/jackschaedler/karplus-stress-tester&lt;/a&gt; &lt;a href=&#34;#fnref:3&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:4&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;The macOS machine is an M1 Max. It can do a full Firefox build in about
13-14 minutes. The Linux machine is an HP workstation desktop based on an
Intel i9-7940X, running Ubuntu LTS 22.04 (running stock PulseAudio config,
explaining the low performance &amp;mdash; anybody serious with real-time audio would
install &lt;a href=&#34;https://jackaudio.org/&#34;&gt;JACK&lt;/a&gt;, but only Firefox supports it
natively). This machine compiles Firefox in about 12 minutes. &lt;a href=&#34;#fnref:4&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</description>
    </item>
    
    
      
    <item>
      <title>Profiling real-time audio workloads in Firefox</title>
      <link>https://blog.paul.cx/post/profiling-firefox-real-time-media-workloads/</link>
      <pubDate>Wed, 01 Jul 2020 14:00:00 +0200</pubDate>
      
      <guid>https://blog.paul.cx/post/profiling-firefox-real-time-media-workloads/</guid>
      <description>&lt;p&gt;Web browsers in 2020 can handle real-time audio workloads quite well. It&amp;rsquo;s not
hard to be able to be around the 10 millisecond mark for round-trip latency &lt;sup id=&#34;fnref:1&#34;&gt;&lt;a href=&#34;#fn:1&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;
without any fear of glitches. While WASM is not as fast as the carefully
optimized assembly code you often find in DSP routines, it can go a long way.&lt;/p&gt;
&lt;p&gt;In a &lt;a href=&#34;https://blog.paul.cx/post/profiling-firefox-media-workloads/&#34;&gt;previous post&lt;/a&gt;,
we discussed the Firefox Profiler and its presets, specifically how to profile a
regular media workload (say, playing video and audio with high latency in the
hundreds of milliseconds) and how easy it is to use and share profiles. An
attentive reader may have noticed that the subject of low-latency real-time
audio was not mentioned. This is because the Firefox Profiler is a statistical
profiler. While perfectly adapted to most regular workloads, a statistical
profiler falls short when profiling real-time workloads, where what matters is
not the average of the speed of an operation, but rather the worst case
scenario. &lt;sup id=&#34;fnref:2&#34;&gt;&lt;a href=&#34;#fn:2&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;p&gt;This is a &lt;strong&gt;fairly long post&lt;/strong&gt;, that starts with a bit of theory, explaining in
more detail why the usual performance profiling tools are not enough. Then we&amp;rsquo;ll
briefly chat about the previous version of the tools we had to measure real-time
performance, and it&amp;rsquo;s newest incarnation, directly integrated in the Firefox
Profiler. We&amp;rsquo;ll see that the Firefox Profiler is extensible via a custom Web
Extension. A final discussion about the incompatibilities between statistical
profiling and tracing in the current state of things conclude the post.&lt;/p&gt;
&lt;h2 id=&#34;a-short-real-time-audio-performance-assessment-primer&#34;&gt;A short real-time audio performance assessment primer&lt;/h2&gt;
&lt;p&gt;In real-time audio programming in user programs, the model that is generally
used is a callback function, that is called with a buffer of &lt;em&gt;n&lt;/em&gt; audio frames to
render, at a particular sample-rate. This callback is called over and over
again, each time the rest of the system needs more audio to output. It follows
that the only way to render the audio without missing a deadline is to render
the audio in less time that it takes to play it out. For example, in the Web
Audio API, and for now, audio is rendered in blocks of 128 frames. If the
&lt;code&gt;AudioContext&lt;/code&gt; is running at 44100Hz, a block MUST be rendered in less than:&lt;/p&gt;
&lt;p&gt;$$ \frac{128}{44100} \approx 0.0029s = 2.9ms $$&lt;/p&gt;
&lt;p&gt;On top of this there is some processing done by the OS (mixing, possibly
resampling, various other things) and the hardware, etc., but generally this is
a reasonable target.&lt;/p&gt;
&lt;p&gt;We can now compute a &lt;em&gt;load&lt;/em&gt; value for a particular call of this callback: this
represents the time it takes to render the audio when called back with a buffer
of &lt;em&gt;n&lt;/em&gt; frames, divided by the budget available to render it.  If it takes one
millisecond to render 128 frames of audio, our load a this point in time is
around \( \frac{1}{3} \). We then have a time series for the load, and a time
series with the same number of data point for the budget (the budget can be
constant or variable for each callback, it depends on the platform). We now have
two time series that allow us to derive a third time series:&lt;/p&gt;
&lt;p&gt;$$ load[t] = \frac{render\ time[t]}{real\ time\ budget[t]} $$&lt;/p&gt;
&lt;p&gt;A glitch happens when this load is over 1.0 (a bit less because the rest of
the audio system needs some time as well). Because the audio system often has
internal buffers, it might well not glitch each time the load crosses the 1.0
threshold: if a particular callback &lt;em&gt;t&lt;/em&gt; has a load of 1.5, but the very next one
has a load of 0.3, and if the system has internal buffers to smooth the load,
the OS is going to absorb the load to a certain extent.  Repeatedly crossing the
1.0 load mark will glitch for sure. Going over budget in a real-time audio
system (and in general, any real-time system) is considered a critical failure of
the system.&lt;/p&gt;
&lt;p&gt;It follows that &lt;strong&gt;any operation that performs an aggregation on this computed
time series will hide the truth&lt;/strong&gt;. For example, getting the mean of the data is
not useful: a mean is a low pass filter and will hide spikes, which is what is
of interest here. A mean and its standard deviation is better (and is only
really useful if the distribution has a normal distribution).&lt;/p&gt;
&lt;p&gt;As often in statistics, having aggregate metrics is not enough. This is clearly and
simply explained for example by the &lt;a href=&#34;https://en.wikipedia.org/wiki/Anscombe&#39;s_quartet&#34;&gt;Anscombe&amp;rsquo;s
quartet&lt;/a&gt;, where various
aggregation functions are computed over four data sets, that are very different
from each other, and the results of the aggregation functions are really
similar.&lt;/p&gt;
&lt;p&gt;What is really needed is &lt;em&gt;all&lt;/em&gt; the data points to be able to
understand what happened when things went over budget and fix it, and the actual
distribution shape, to try to understand what happened in a particular scenario.&lt;/p&gt;
&lt;p&gt;To illustrate this really important point, look at the following curve and
histograms:&lt;/p&gt;
&lt;figure class=&#34;seamless&#34;&gt;
    &lt;img src=&#34;https://blog.paul.cx/bimodal.jpg&#34;/&gt; &lt;figcaption&gt;
            &lt;h4&gt;Real-life example of a bimodal distribution caused by sending back info from the audio callback thread, that renders at 300Hz to the main thread, that renders at 60Hz&lt;/h4&gt;
        &lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;The mean, the median, and the standard deviation don&amp;rsquo;t tell the truth. Maybe if
we had the minimum and maximum values of the series, and a breakdown per
percentile, it would have been possible to understand the trend. Plotting it
immediately makes everything clear and allows spending more time fixing the
problem instead of measuring and understanding the data.&lt;/p&gt;
&lt;h2 id=&#34;the-old-solution-for-firefox-developers&#34;&gt;The old solution, for Firefox developers&lt;/h2&gt;
&lt;p&gt;Being able to measure real-time callback time and understand why things don&amp;rsquo;t
always take the same amount of time is extremely important when working on
real-time systems. For Firefox, this was invaluable to diagnose WebRTC audio or
video glitches. Browsers are made of lots of code, and it&amp;rsquo;s easy to do something
without tracing down to the bottom of the call stack. It&amp;rsquo;s also possible to have
a class or library change under you, and suddenly a lock is taken somewhere on
the critical path, and once every few thousand callbacks, the deadline isn&amp;rsquo;t
met, and a glitch or a frame drop occurs, and it&amp;rsquo;s hard to know why because it&amp;rsquo;s
gone.&lt;/p&gt;
&lt;p&gt;To solve those issues, I
&lt;a href=&#34;https://bugzilla.mozilla.org/show_bug.cgi?id=1444976&#34;&gt;implemented&lt;/a&gt; a simple
MPSC wait-free queue &lt;sup id=&#34;fnref:3&#34;&gt;&lt;a href=&#34;#fn:3&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;3&lt;/a&gt;&lt;/sup&gt; a couple years ago. Now, any thread of interests post
structured messages containing measurements to an instance of this queue. This
is not an innovation by any mean, any big system must have a tracing system to
diagnose it &lt;sup id=&#34;fnref:4&#34;&gt;&lt;a href=&#34;#fn:4&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;4&lt;/a&gt;&lt;/sup&gt;, or diagnosing performance problems is a lost cause. This queue
is then be emptied regularly by a thread (every 10ms currently), and a
structured log file is written to disk, via &lt;code&gt;MOZ_LOG&lt;/code&gt;, which is the logging
system of Firefox. The main purpose of this design is to move all the overhead
of the measurement, except the only part necessary, to a thread that sits idle.
In particular, here it means getting a time-stamp, getting the thread ID, and
appending to the queue.&lt;/p&gt;
&lt;p&gt;The format used was the one that is overwhelmingly commonly picked by anybody
that doesn&amp;rsquo;t want to reinvent the wheel, called the &amp;ldquo;Trace event format&amp;rdquo;,
&amp;ldquo;&lt;code&gt;systrace&lt;/code&gt;&amp;rdquo; or &amp;ldquo;the file format that can be loaded in Chrome when typing
&lt;code&gt;chrome://tracing&lt;/code&gt;&amp;rdquo;. Its spec is
&lt;a href=&#34;https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview&#34;&gt;here&lt;/a&gt;.
It&amp;rsquo;s (simplifying) a massive but extremely simple JSON array. Loading it in
&lt;code&gt;chrome://tracing&lt;/code&gt; allowed displaying it, it&amp;rsquo;s very nice.&lt;/p&gt;
&lt;p&gt;Then I made a &lt;a href=&#34;https://padenot.github.io/msg-load-analyzer/&#34;&gt;very small website&lt;/a&gt;
(the image above is a screen-shot from that) that consumes the same format,
and plot the load against time, carefully doing it in a way that spikes would be
easy to find visually. By having the time values match between the tools, it
is easy to find the problematic point in time using the graphical
representation, and then one can drill down in the other tool. A histogram
completes the visualization, because the shape of the distribution is often
useful.&lt;/p&gt;
&lt;p&gt;This system, while built quickly and by piling hacks on top of hacks, proved
itself very useful over the years.  Being able to run and measure the same
scenario in two different version of Firefox, and see the improvement (for
example) in terms of load and standard deviation of the load (the goal generally
being to have less load and a tighter standard deviation) allow optimizing with
confidence.&lt;/p&gt;
&lt;p&gt;However, this system had numerous issues:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;It required &lt;strong&gt;disabling the sandbox&lt;/strong&gt;, because the Firefox processes that run the
web content can&amp;rsquo;t write to disk&lt;/li&gt;
&lt;li&gt;It required running Firefox with &lt;strong&gt;specific environment variables&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;It allowed &lt;strong&gt;only one measurement&lt;/strong&gt; per run&lt;/li&gt;
&lt;li&gt;The trace files themselves were &lt;strong&gt;quite big&lt;/strong&gt;, uncompressed redundant JSON
quickly pile up on the disk (it compressed extremely well of course, which was
useful)&lt;/li&gt;
&lt;li&gt;If the traces were too big, &lt;strong&gt;no tool would accept the file&lt;/strong&gt;, and we had to
implement programs to filter the data to lower the size of the file&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;At the same time, &lt;code&gt;AudioWorklet&lt;/code&gt; was shipping and would allow developers to
write arbitrary code on the real-time thread. Developers doing so immediately
wanted to assess the performance of their code, and we had no real answer
apart our hacky &lt;code&gt;MOZ_LOG&lt;/code&gt; based tracing system.&lt;/p&gt;
&lt;p&gt;But also at the same time, I became increasingly familiar with the Firefox
Profiler, and its amazing UI.&lt;/p&gt;
&lt;h2 id=&#34;the-new-solution&#34;&gt;The new solution&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&#34;https://profiler.firefox.com/&#34;&gt;Firefox Profiler&lt;/a&gt; (&lt;a href=&#34;https://blog.paul.cx/post/profiling-firefox-media-workloads/&#34;&gt;praised&lt;/a&gt;, in a previous post, and
probably in future posts) has a concept of markers, that are similar to the
previous&amp;rsquo; format tracepoints, so I &lt;a href=&#34;https://bugzilla.mozilla.org/show_bug.cgi?id=1626918&#34;&gt;ported my
system&lt;/a&gt; to use the Firefox
Profiler Markers instead of &lt;code&gt;MOZ_LOG&lt;/code&gt;. I kept the MPSC queue, because inserting
a marker is for the moment not real-time safe and quite expensive. The markers
code is in the process of being overhauled by the Firefox Profiler team, but I
needed this now to measure and optimize things today.&lt;/p&gt;
&lt;p&gt;It works similarly as the solution described previously, except it&amp;rsquo;s now
absolutely trivial to record a profile and upload it to Mozilla&amp;rsquo;s server and
being able to share it with a simple URL: here is a video that shows, from a
stock Firefox (Nightly for now), how to get a real-time trace of any Web Audio
API app:&lt;/p&gt;
&lt;video controls preload=auto&gt;
  &lt;source src=&#34;https://paul.cx/public/fx-rt-profiler-part-a.webm&#34;&gt;
  &lt;source src=&#34;https://paul.cx/public/fx-rt-profiler-part-a.mp4&#34;&gt;
&lt;/video&gt;
&lt;p&gt;A quick description of what happens in the video:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:00&lt;/span&gt;, I start with an &lt;strong&gt;fresh Firefox Nightly&lt;/strong&gt;, in
which I&amp;rsquo;ve loaded a Web Audio API stress testing app,
&lt;a href=&#34;https://jackschaedler.github.io/karplus-stress-tester/&#34;&gt;https://jackschaedler.github.io/karplus-stress-tester/&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;As usual, activating the Firefox Profiler is as simple as visiting
&lt;a href=&#34;https://profiler.firefox.com&#34;&gt;https://profiler.firefox.com&lt;/a&gt; and clicking the button. At &lt;span
class=seek&gt;0:04&lt;/span&gt; we are &lt;strong&gt;all set up&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:07&lt;/span&gt;, I&amp;rsquo;m selecting the &lt;strong&gt;&lt;code&gt;Media&lt;/code&gt; preset&lt;/strong&gt;, because I&amp;rsquo;m
about to profile a real-time media workload.&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:12&lt;/span&gt;, I&amp;rsquo;m &lt;strong&gt;executing a scenario&lt;/strong&gt;. This is a rather
low load for the machine. The &lt;a href=#going-further&gt;last section&lt;/a&gt; of this
blog post explains why and how to profile higher load scenarios.&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:18&lt;/span&gt; I &lt;strong&gt;capture the profile&lt;/strong&gt;. This opens a tab to
display the profile. Shortly after, I close the tab I was profiling, because I
don&amp;rsquo;t need it anymore.&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:28&lt;/span&gt; I &lt;strong&gt;play around in the interface&lt;/strong&gt;, and by
zooming in, I can observe the audio callback budget, and how long our
computation has taken for each callback. In Firefox, the &lt;code&gt;DataCallback&lt;/code&gt; is the
audio callback that deal with input and output audio data and comes from the
OS. There also is a &lt;code&gt;StateCallback&lt;/code&gt; that is called when asynchronous
operations are finished (stream start/stop/error, etc.).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A similar profile (captured from a macOS machine) is available
at &lt;a href=&#34;https://share.firefox.dev/3gjwL6H&#34;
target=&#34;_blank&#34;&gt;&lt;code&gt;https://share.firefox.dev/3gjwL6H&lt;/code&gt;&lt;/a&gt; for looking around.&lt;/p&gt;
&lt;p&gt;The profiler&amp;rsquo;s marker UI is for now quite similar to other trace visualisation
tool, except it&amp;rsquo;s currently per thread. It&amp;rsquo;s well-suited to look at data when
zoomed in quite high on a particular portion of a trace, probably a point in
time where something weird happened.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;problem&lt;/strong&gt; is that finding an issue is not easy when you have that much
data: 10 seconds of profiling is about 3000 rendered audio blocks. Zoomed out,
it&amp;rsquo;s just a continuous blue line, so a graphical visualization is really needed,
but probably too specific to be built-in the profiler.&lt;/p&gt;
&lt;h2 id=&#34;the-solution-to-the-new-problem&#34;&gt;The solution to the new problem&lt;/h2&gt;
&lt;p&gt;Chatting with the developers working on the profiler, they immediately mentioned
something that I found quite smart: the markers (and other data) are exposed as
a simple JavaScript array of objects, with all the data available to tinker
with, as an &lt;a href=&#34;https://developer.mozilla.org/en-US/docs/Glossary/Expando&#34;&gt;expando&lt;/a&gt;
property on &lt;code&gt;window&lt;/code&gt;. Even cooler, if you select a particular time span, this
property, aptly called &lt;code&gt;window.filteredMarkers&lt;/code&gt; is exactly that: the filtered
markers that correspond to what is on the screen.&lt;/p&gt;
&lt;p&gt;Armed with some courage, knowing that I know nothing about this &lt;sup id=&#34;fnref:5&#34;&gt;&lt;a href=&#34;#fn:5&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;5&lt;/a&gt;&lt;/sup&gt;, I went ahead
and decided to write &lt;a href=&#34;https://github.com/padenot/fx-profiler-audio-cb&#34;&gt;a Firefox extension&lt;/a&gt; that would read
those &lt;code&gt;filteredMarkers&lt;/code&gt; and then I copy/pasted the previous hackish website&amp;rsquo;s
code into the extension, asked for help for the CSS bits, and voilà, I had the
best of all worlds:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Real-time tracing of audio processing at the click of a button on a stock
Firefox&lt;/li&gt;
&lt;li&gt;A very good UI to understand problems, and tracing that doesn&amp;rsquo;t aggregate the
data&lt;/li&gt;
&lt;li&gt;Custom data visualisation that visually shows the data&lt;/li&gt;
&lt;li&gt;The ability to share profiles via a simple URL&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here is a short video showing it in action:&lt;/p&gt;
&lt;video controls preload=auto&gt;
  &lt;source src=&#34;https://paul.cx/public/fx-rt-profiler-part-b.webm&#34;&gt;
  &lt;source src=&#34;https://paul.cx/public/fx-rt-profiler-part-b.mp4&#34;&gt;
&lt;/video&gt;
&lt;p&gt;Here is a breakdown of what happens in this videos:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:00&lt;/span&gt;, I start with the profiler recorded above.&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:10&lt;/span&gt;, I install my Web Extension for the Firefox
Profiler. It is for now on a &lt;a href=&#34;https://github.com/padenot/fx-profiler-audio-cb/tree/master/dist&#34;&gt;GitHub
repo&lt;/a&gt;,
and has been validated and signed by &lt;a href=&#34;https://addons.mozilla.org&#34;&gt;https://addons.mozilla.org&lt;/a&gt; (it wouldn&amp;rsquo;t
install otherwise). This adds a little icon with a stopwatch where the hands
have been replaces by an eighth note.&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:31&lt;/span&gt;, when the thread &lt;code&gt;NativeAudioCallback&lt;/code&gt; (also
called &lt;code&gt;AudioIPC0&lt;/code&gt; on some platforms) has been selected, I trigger the
extension. This displays a couple metrics and the two graphical
representations talked about previously.&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:43&lt;/span&gt;, I&amp;rsquo;m selecting a particular time region, I
reselect the correct thread, trigger the extension again, and I see that the
data is now computed from the selected time range.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&#34;going-further&#34;&gt;Going further&lt;/h1&gt;
&lt;p&gt;By default, the Firefox profiler periodically collects the stacks for all
threads that are being profiled. This is very useful for most workloads, but
it&amp;rsquo;s sometimes problematic for real-time workloads.&lt;/p&gt;
&lt;p&gt;Stack collection is done by pausing a thread and unwinding its stack, and then
recording this stack information into a global buffer. This pauses and locks (in
the current implementation), so isn&amp;rsquo;t suitable to assess performances of a
system where any jitter is an integral part of the quality.&lt;/p&gt;
&lt;p&gt;In the Media preset for the Firefox Profiler, stack sampling is running at
1000Hz (every millisecond) while the audio callback is running at around 300Hz
as seen above (depending on the sample-rate). This means that each callback (on
average), the thread is paused three times and a lock with a rather high
contention is taken three time, a setup that is bound to fail for a real-time
workload.&lt;/p&gt;
&lt;p&gt;Thankfully, the Firefox Profiler allows disabling the stack collection, while
still getting the markers for the threads:&lt;/p&gt;
&lt;video controls preload=auto&gt;
  &lt;source src=&#34;https://paul.cx/public/fx-rt-profiler-part-c.webm&#34;&gt;
  &lt;source src=&#34;https://paul.cx/public/fx-rt-profiler-part-c.mp4&#34;&gt;
&lt;/video&gt;
&lt;ul&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:04&lt;/span&gt; I show a little gymnastic that is useful: to
customize a preset, choose this preset and then switch to &lt;code&gt;Custom&lt;/code&gt;, this allows
to use a particular preset as a template.&lt;/li&gt;
&lt;li&gt;At &lt;span  class=seek&gt;0:07&lt;/span&gt;, I disable a few features, and tick the
check-box labeled &lt;code&gt;No periodic sampling&lt;/code&gt;, that is pretty self-explanatory.&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:22&lt;/span&gt;, I close the tab and start a profile using
those &lt;code&gt;Custom&lt;/code&gt; settings.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This also happens to greatly decrease the size of the profile and allow
recording traces for a very long time, which is sometimes essential to diagnose
problems that happen rarely.&lt;/p&gt;
&lt;p&gt;That said, statical sampling is extremely useful to quickly find spots to
optimize: having it on by default, but being able to disable by simply un-ticking
a check-box is very powerful. After finding a potential optimization candidate
using statistical sampling, and writing the patch to make the code run faster,
the performance comparison is best done by un-ticking the check-box and looking
at the raw or aggregated data.&lt;/p&gt;
&lt;h1 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Tracing is a very powerful tool, and I&amp;rsquo;m glad the Firefox Profiler
team is investing in making it better. I frequently use it to debug quality
issues, or just regularly to see if the real-time threads of Firefox are not
doing something they shouldn&amp;rsquo;t.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s now accessible to web developers, for example to A/B test between two
implementation strategies, or to ensure a code changes that was intended as an
optimization actually makes the code run faster. The current state of the
extension is pretty rough, and patches are of course welcome. As often with
open-source contributions, starting by &lt;a href=&#34;https://github.com/padenot/fx-profiler-audio-cb/issues&#34;&gt;opening an issue&lt;/a&gt; to discuss a non-trivial
change is appreciated. When profiling, it&amp;rsquo;s always better to use a &lt;a href=&#34;https://www.mozilla.org/en-US/firefox/all/#product-desktop-nightly&#34;&gt;Firefox
Nightly&lt;/a&gt;
build: we&amp;rsquo;re constantly making improvements, any slowdown or problem you see in
release might already be fixed.&lt;/p&gt;
&lt;p&gt;I have plans to fix the fact that this measuring system is not really
wait-free next, but if my measurements are correct (and I verified with a few
different techniques, such as &lt;a href=&#34;https://lttng.org/&#34;&gt;LTTng&lt;/a&gt; and
&lt;a href=&#34;https://en.wikipedia.org/wiki/Berkeley_Packet_Filter#Extensions_and_optimizations&#34;&gt;eBPF&lt;/a&gt;),
the data is consistent between the various tools, and the Firefox Profiler is
vastly superior in terms of ease of use, and is cross-platform.&lt;/p&gt;
&lt;section class=&#34;footnotes&#34; role=&#34;doc-endnotes&#34;&gt;
&lt;hr&gt;
&lt;ol&gt;
&lt;li id=&#34;fn:1&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;10 millisecond input-to-output is generally considered adequate for performing music or otherwise interact with a musical instruments although it depends on a variety of factor such as the type of instruments, the performer, the type of music being played, and a host of other details. To reach this, take any Firefox and have an OS that is suitable for music, such as macOS or a Linux Desktop with Jack, possibly with a dedicated sound card. Windows works well for music with ASIO drivers, but the license of the ASIO SDK would violate the SDK&amp;rsquo;s license and the MPL 2.0 so we can&amp;rsquo;t use it in Firefox.  &lt;a href=&#34;https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nn-audioclient-iaudioclient3&#34;&gt;&lt;code&gt;IAudioClient3&lt;/code&gt;&lt;/a&gt; is promising but hasn&amp;rsquo;t been used successfully in browsers at the latency figures other platforms reach. &lt;a href=&#34;#fnref:1&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:2&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;This is a gross generalization. The classic article &lt;a href=&#34;http://www.rossbencina.com/code/real-time-audio-programming-101-time-waits-for-nothing&#34;&gt;&amp;ldquo;Real-time programming 101: time waits for nothing&amp;rdquo;&lt;/a&gt; explains the problems and constraints in more details. &lt;a href=&#34;#fnref:2&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:3&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;I&amp;rsquo;m lying, this is not exactly correct, but it has been measured to be wait-free enough to be able to do its job in the type of scenario it&amp;rsquo;s being used for. It will be replaced by something proper in the long run, I knowingly made an engineering trade-off. &lt;a href=&#34;#fnref:3&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:4&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;&lt;code&gt;chrome://tracing&lt;/code&gt;, Window&amp;rsquo;s ETW, Linux&amp;rsquo;s &lt;code&gt;ftrace&lt;/code&gt;, &lt;a href=&#34;https://bitbucket.org/wolfpld/tracy/src/master/&#34;&gt;Tracy&lt;/a&gt; etc. are a few example of those systems, that are rather mature and industry standards. The Chrome team has very recently published &lt;a href=&#34;https://web.dev/profiling-web-audio-apps-in-chrome/&#34;&gt;an article&lt;/a&gt; about profiling Web Audio API workloads in Chrome. The tracing system in Chrome seems more mature and widely used by their developers than what we have in Firefox for now. &lt;a href=&#34;#fnref:4&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:5&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;As it turned out, Mozilla has a really good website that explain how to make extensions, &lt;a href=&#34;https://extensionworkshop.com/&#34;&gt;https://extensionworkshop.com/&lt;/a&gt;, that had all the info I needed, and rather good tooling to get going in no time. As a system programmer that has learnt web technology by osmosis over the years, I was surprised at how fast it was to write a web extension that would take some data from the page and open an overlay to display the data differently. &lt;a href=&#34;#fnref:5&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</description>
    </item>
    
    
      
    <item>
      <title>Profiling media workloads in Firefox</title>
      <link>https://blog.paul.cx/post/profiling-firefox-media-workloads/</link>
      <pubDate>Tue, 14 Apr 2020 18:42:00 +0200</pubDate>
      
      <guid>https://blog.paul.cx/post/profiling-firefox-media-workloads/</guid>
      <description>&lt;p&gt;It will come as no surprise that playing video and audio in a web browser
requires a certain attention to performance. Whether it is by getting the
design right, using good implementations of codecs (potentially with hardware
acceleration), taking care of using memory properly and avoiding unnecessary
copies, or ultimately micro-optimizing some particular hot paths using flashy
assembly routines or a clever algorithm, a good experience for an end user
doesn&amp;rsquo;t come without hard work.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s well known that it&amp;rsquo;s quite hard for a programmer to know ahead of time what
part of a program is going to be expensive in terms of CPU, if possible at all.
Software profiling, the practice of measuring the performances of a software
while it&amp;rsquo;s running, and often doing a specific task in a specific environment is
essential for producing good quality software in the first place, and to verify
that optimizations are, in fact, making things faster.&lt;/p&gt;
&lt;p&gt;Moreover,  the web platform being particularly flexible, it&amp;rsquo;s quite possible
that a web developer uses a particular feature in a way that the implementor and
the specification author didn&amp;rsquo;t anticipate. In those instances, it happens that
the browser code is not optimal (or &lt;em&gt;really&lt;/em&gt; slow, up to the point of being
unusable), and reporting the bug to the developers of the web browser is much
appreciated.&lt;/p&gt;
&lt;p&gt;Finally, browsers being widely used software that runs on a rather large
range of hardware and operating systems, it&amp;rsquo;s expected that the experience of
users varies (for example, attempting to play a 4k 60fps video might or might
not work on old hardware with outdated drivers). If a developer has no way of
reproducing the issue, nor a way to understand what is causing the problem, it
becomes harder to fix the issue for the end user &lt;sup id=&#34;fnref:1&#34;&gt;&lt;a href=&#34;#fn:1&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;1&lt;/a&gt;&lt;/sup&gt; .&lt;/p&gt;
&lt;h1 id=&#34;the-firefox-profiler&#34;&gt;The Firefox Profiler&lt;/h1&gt;
&lt;p&gt;The &lt;a href=&#34;https://profiler.firefox.com/&#34;&gt;Firefox profiler&lt;/a&gt; has been introduced years
ago, and it has a few characteristics that make it extremely efficient to
improve Firefox:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;It&amp;rsquo;s &lt;strong&gt;lightweight&lt;/strong&gt; and can be &lt;strong&gt;run for long periods of time&lt;/strong&gt;. It
records its data into an in-memory ring buffer, and when a problem happens, if
the user clicks the button to capture the profile, more often than not the issue
has been captured.&lt;/li&gt;
&lt;li&gt;It can &lt;strong&gt;upload the recorded profile&lt;/strong&gt; to a Mozilla server, with optional
privacy scrubbing of course. Users have the choice of what they share with us
with a clear set of check-boxes.&lt;/li&gt;
&lt;li&gt;It supports &lt;strong&gt;recording multiple-processes&lt;/strong&gt; at once, which is critical in
those time of multi-process browser and hardened sand-boxing.&lt;/li&gt;
&lt;li&gt;It supports &lt;strong&gt;tracepoints&lt;/strong&gt; and the classic &lt;strong&gt;statistical profiling&lt;/strong&gt; with
stack unwinding, and supports interleaved JavaScript/WASM and native stacks
interleaved, with full symbol
&lt;a href=&#34;https://en.wikipedia.org/wiki/Name_mangling&#34;&gt;demangling&lt;/a&gt; and automatic symbol
decoding and matching, for builds released by Mozilla&lt;/li&gt;
&lt;li&gt;It also has &lt;strong&gt;advanced integration&lt;/strong&gt; for important parts of a web browser:
network requests, frame drops, garbage collection events, the main thread
being blocked on something, and overall browser responsiveness&lt;/li&gt;
&lt;li&gt;A view of a particular profile can be shared (simply via the hash on the URL),
so that we can discuss between Mozilla developers, and point to a particular
location in a profile, for example via email or on
&lt;a href=&#34;https://chat.mozilla.org&#34;&gt;chat.m.o&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In addition it can import not only Firefox&amp;rsquo;s internal recording, but can also
take a &lt;a href=&#34;https://en.wikipedia.org/wiki/Perf_(Linux)&#34;&gt;&lt;code&gt;perf&lt;/code&gt;&lt;/a&gt; profiles &lt;a href=&#34;https://profiler.firefox.com/docs/#/./guide-perf-profiling&#34;&gt;as
input&lt;/a&gt; (and maybe
more system profilers in the future), recorded on other programs than Firefox,
and the UI of the profiler is better than most other profiler UI, so it&amp;rsquo;s quite
nice. But that&amp;rsquo;s a story for another post.&lt;/p&gt;
&lt;h1 id=&#34;the-media-preset&#34;&gt;The Media preset&lt;/h1&gt;
&lt;p&gt;Going back to media, we of course use a certain amount of threads in Firefox,
to have video and audio play smoothly while the user is using other tabs or
interacting with the page. This makes it a bit hard to set up the profiler to
record the right set of threads, with the right settings, especially for someone
less technically inclined that a Firefox developer. The instructions
used to look &lt;a href=&#34;https://bugzilla.mozilla.org/show_bug.cgi?id=1568286#c5&#34;&gt;like
this&lt;/a&gt;. On quite a few
request to get profiles (on bugzilla, hacker news, randomly on reddit, etc.),
only a handful people manageed to submit usable profile that allowed us to
understand what was going on. We can&amp;rsquo;t blame anyone but ourselves for this; it&amp;rsquo;s
not a user&amp;rsquo;s job to understand the innards of our software, and we can be
nothing but grateful when they take time out of their day to report a problem
they encountered.&lt;/p&gt;
&lt;p&gt;But all this is over, since the introduction of profiling presets by my
colleague &lt;a href=&#34;https://twitter.com/TatumCreative&#34;&gt;Greg Tatum&lt;/a&gt; (with &lt;a href=&#34;https://twitter.com/jwasjberg&#34;&gt;Julien
Wajsberg&lt;/a&gt; on review duties, and I&amp;rsquo;m sure other
people from their team). Let&amp;rsquo;s imagine I have a performance problem when seeking
in videos on YouTube. To profile Firefox when it&amp;rsquo;s doing something that
is media-related , here are now the &lt;strong&gt;complete&lt;/strong&gt; steps, from a stock Firefox
&lt;sup id=&#34;fnref:2&#34;&gt;&lt;a href=&#34;#fn:2&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;video controls preload=auto&gt;
  &lt;source src=&#34;https://paul.cx/public/firefox-profiler-button.webm&#34;&gt;
  &lt;source src=&#34;https://paul.cx/public/firefox-profiler-button-x264.mp4&#34;&gt;
&lt;/video&gt;
&lt;p&gt;A few words about some specific steps in this video, with links:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;I start with a fresh Firefox Nightly, which is often better to check for
performance issues (since it contains more code and therefore, often more
fixes)&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:06&lt;/span&gt; I have loaded &lt;a href=&#34;https://profiler.firefox.com&#34;&gt;https://profiler.firefox.com&lt;/a&gt;
and I click on the big button to show the profiling item in the tool bar. It&amp;rsquo;s
also possible to activate it by going into the Customize button, and dragging
it to the tool bar.&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:09&lt;/span&gt; I select the &lt;code&gt;Media&lt;/code&gt; profiling preset (in my
case it&amp;rsquo;s already selected, but I&amp;rsquo;m clicking the drop-down to show that there
are other options for other use-cases)&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:16&lt;/span&gt; I&amp;rsquo;ve loaded a web page I want to profile, and
clicked the profiler button, to start profiling.&lt;/li&gt;
&lt;li&gt;Around the 20 seconds mark, I play and randomly seek in the video, as if I had
a performance problem with seeking.&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:31&lt;/span&gt;, I capture the profile. This stops profiling,
and opens a tab where Firefox will display the profile&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:38&lt;/span&gt;, the Firefox profiler symbolicates the profile
(it knows I&amp;rsquo;m running a particular version of Firefox Nightly)&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:43&lt;/span&gt;, I&amp;rsquo;m showing how to view the important threads
for media playback, and I unfold the call stack until I find something that
talks about &lt;code&gt;ffmpeg&lt;/code&gt;, that must be about decoding something&lt;/li&gt;
&lt;li&gt;At &lt;span class=seek&gt;0:58&lt;/span&gt;, I&amp;rsquo;m uploading the profile, noting that some
information can be removed from the profile (this is a simple test, I don&amp;rsquo;t
un-tick any boxes).  The upload step can be skipped and the profile downloaded
(it has not left the machine at this point), and sent and loaded manually to
another developer, for example via &lt;a href=&#34;https://send.firefox.com&#34;&gt;Firefox Send&lt;/a&gt;,
which is encrypted.&lt;/li&gt;
&lt;li&gt;After some time (&lt;span class=seek&gt;1:31&lt;/span&gt;), the profile URL is available,
and I load it into a different browser tab.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&#34;closing-words&#34;&gt;Closing words&lt;/h1&gt;
&lt;p&gt;Sending the profile URL to a Firefox developer (for example on a Bugzilla
ticket, on reddit, hacker news, or via email) immensely increases the chance
that the problem will be fixed.&lt;/p&gt;
&lt;p&gt;It is rare that a problem affects only one person when the number of users of
your software is in the hundreds of millions. By reporting performance issues
with profiles, anybody who has an interest in making the web better can
contribute.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s rather easy to file a ticket on our &lt;a href=&#34;https://bugzilla.mozilla.org&#34;&gt;Bugzilla
instance&lt;/a&gt;. Logging in with a GitHub or Bugzilla
account, and clicking the following link:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;&lt;a href=&#34;https://bugzilla.mozilla.org/enter_bug.cgi?product=Core&amp;amp;component=Audio%2FVideo&#34;&gt;https://bugzilla.mozilla.org/enter_bug.cgi?product=Core&amp;amp;component=Audio%2FVideo&lt;/a&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;directly sends the bug to the media team, that triages regularly. They will
reorient the ticket to the right people, that will then try to diagnose or
debug. Adding a copy of &lt;code&gt;about:support&lt;/code&gt; (type this in the address bar if you&amp;rsquo;re
reading this in Firefox), and any weirdness about your setup goes a long way to
have whatever your report fixed in an future release of Firefox.&lt;/p&gt;
&lt;p&gt;On behalf of the media team, thanks in advance!&lt;/p&gt;
&lt;section class=&#34;footnotes&#34; role=&#34;doc-endnotes&#34;&gt;
&lt;hr&gt;
&lt;ol&gt;
&lt;li id=&#34;fn:1&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;But not impossible, there are lots of stories about crazy ideas lighting up in the head of developers in the middle of taking a shower while half awake, finding crazy connections between multiple subsystems to find a weird edge case that happened to be what was causing the issue. &lt;a href=&#34;#fnref:1&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:2&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;I&amp;rsquo;m on macOS, but this is the same on all desktop platforms, mobile is also supported of course but the workflow is different since the Firefox being profiled is on a different machine than the Firefox displaying the profile. &lt;a href=&#34;#fnref:2&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</description>
    </item>
    
    
      
    <item>
      <title>A robust metronome using the Web Audio API</title>
      <link>https://blog.paul.cx/post/metronome/</link>
      <pubDate>Wed, 11 Sep 2019 14:13:00 +0000</pubDate>
      
      <guid>https://blog.paul.cx/post/metronome/</guid>
      <description>&lt;p&gt;A metronome is, by essence, something that needs to have very precise scheduling.&lt;/p&gt;
&lt;p&gt;The web is an environment where precise scheduling is often challenging, and
increasingly so with the security mitigations put in place since the
publication of Spectre/Meltdown.&lt;/p&gt;
&lt;p&gt;Writing a good metronome using the Web Audio API seems at first to be a rather
complicated task, and &lt;a href=&#34;https://meowni.ca/posts/metronomes/&#34;&gt;this post&lt;/a&gt; by Monica
Dinculescu does a very good job at explaining all the things that can (and does)
go wrong when dealing with timers in JavaScript. By the end of the post, the
technique proposed is fairly robust, at the expense of having to do more than
one complicated tricks and trying a few different techniques. Since it uses
threads that are not real-time for the scheduling, it&amp;rsquo;s bound to have some
jitter at some point, which may or may not be a problem, depending on the
context.&lt;/p&gt;
&lt;p&gt;But what if we could use the Web Audio API differently to do most of the work
for us, so we can forget about clock domains, &lt;code&gt;setTimeout&lt;/code&gt; throttle in the
background, Workers, and all that?&lt;/p&gt;
&lt;p&gt;This tutorial will serve as an example of a more general Web Audio API advice:
&lt;strong&gt;don&amp;rsquo;t use the main thread if you don&amp;rsquo;t have to&lt;/strong&gt;: you can&amp;rsquo;t predict how much
it is doing. It&amp;rsquo;s hard enough to keep it under control in your own app, and it&amp;rsquo;s
borderline impossible is you happen to write a library that is going to be used
by a number of people to do various things that you didn&amp;rsquo;t anticipate.&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;ve written a web page that is a metronome in literate JavaScript using
&lt;a href=&#34;https://github.com/jashkenas/docco&#34;&gt;docco&lt;/a&gt;, and the output is below. The
sources are &lt;a href=&#34;https://github.com/padenot/metro/&#34;&gt;on GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;iframe src=&#34;https://paul.cx/public/metro&#34; width=100% height=&#34;4500em&#34; frameborder=&#34;0&#34;&gt;&lt;/iframe&gt;
&lt;h1 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;The metronome shown here is extremely robust, it can be tested
&lt;a href=&#34;https://paul.cx/public/metro/demo.html&#34;&gt;here&lt;/a&gt;. It will never glitch or drift or
have any jitter or anything except in case of bugs in the Web Audio API
implementation. Which is certainly something that can happen (I&amp;rsquo;ve
certainly written my fair share of those in Firefox).&lt;/p&gt;
&lt;p&gt;A similar technique can be applied to other audio programs: connecting audio
signal to &lt;code&gt;AudioParam&lt;/code&gt;s in the Web Audio API is a good way to have very robust
parameter changes even under load. Under normal circumstances, the real-time
thread on which the Web Audio API does its processing will not be preempted by
other thread, and its scheduling will be really precise.&lt;/p&gt;
&lt;p&gt;Of course, for apps that need a lot of interactivity, the main thread load will
still be a factor, but when it&amp;rsquo;s possible to not use it, it&amp;rsquo;s always better to
do so.&lt;/p&gt;
</description>
    </item>
    
    
      
    <item>
      <title>Audio/Video synchronization with the Web Audio API</title>
      <link>https://blog.paul.cx/post/audio-video-synchronization-with-the-web-audio-api/</link>
      <pubDate>Tue, 23 Jul 2019 12:00:00 +0000</pubDate>
      
      <guid>https://blog.paul.cx/post/audio-video-synchronization-with-the-web-audio-api/</guid>
      <description>&lt;p&gt;When working with real-time audio, latency is always a concern. Today, devices
(computer, laptops) can often reach really low audio latency, but a variety of
factors contribute to this latency.&lt;/p&gt;
&lt;p&gt;The OS and its version, the hardware used (external sound card, built-in audio
chip, Bluetooth headset, etc.), how carefully the program making the sound is
written, which API it uses, how big the buffers chosen either by the developers
or the users are, how expensive is the computation performed are some of the
factors that play a role in the final end to end latency.&lt;/p&gt;
&lt;figure&gt;
    &lt;img src=&#34;https://blog.paul.cx/cassettes.jpg&#34;/&gt; 
&lt;/figure&gt;

&lt;p&gt;Typical round-trip &lt;sup id=&#34;fnref:1&#34;&gt;&lt;a href=&#34;#fn:1&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;1&lt;/a&gt;&lt;/sup&gt; latency figures on modern configurations, when using
wired hardware are as follow:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Windows&lt;/strong&gt;: it really depends on the driver and API used, WASAPI can be very
low (tens of milliseconds with modern drivers on Windows 10 when the program
uses the correct APIs) or high (on the order of hundreds of milliseconds).
ASIO drivers (usually for professionals, and often paired with external sound
cards) can have much lower latencies, but the SDK is proprietary and cannot
really be used in open-source web browsers, as far as I know.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Apple&lt;/strong&gt;: devices (Macs, iPads, iPhones): usually the best choice for pro audio,
sub-10 millisecond can be achieved without trouble on default hardware, with
very high reliability.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Linux&lt;/strong&gt;: ALSA and PulseAudio, with proper real-time thread scheduling can be
pretty solid at low latencies. 50 milliseconds round-trip is achievable. When
running Jack and/or a real-time kernel, a latency of a few frames (hundreds of
microseconds) is doable, which is hard to beat.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Android&lt;/strong&gt; uses its own audio stack, sometimes on top of ALSA. Latency figures
vary widely, and the reliability of the audio threads is sometimes not the best.
It really differs from device to device (see &lt;a href=&#34;https://superpowered.com/latency&#34;&gt;this
page&lt;/a&gt; for real data and more explanations). It
is certainly much better &lt;em&gt;on average&lt;/em&gt; than it used to be a few years ago.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Round trip latency is often used when characterizing latencies on a particular
device, because it&amp;rsquo;s easy to do it with a high degree of confidence. Equipped
with a program that opens a input/output duplex audio stream, simply copy the
input frames into the output buffer. Then, in a quiet
room, generate a short tone/click on the output stream. Measure the time
it takes in the program between generating the audio to recording it, and (not
always but often) divide by 2 to get the audio output latency. Usually this
results in larsens so be careful.&lt;/p&gt;
&lt;p&gt;Variation on this procedure can be done: touch to sound latency can be important
for virtual instruments on phone, MIDI key press to sound is critical for
musicians, the tilt sensor to sound contributes a lot to immersion, in VR
experiences.&lt;/p&gt;
&lt;h1 id=&#34;audio-latencies-on-the-web&#34;&gt;Audio latencies on the web&lt;/h1&gt;
&lt;p&gt;On the Web, low latency is really important when playing video games (or any
other interactive experience, such as VR or AR), when doing voice calls, when
playing a virtual instrument &lt;a href=&#34;http://webaudio.github.io/web-midi-api/&#34;&gt;using a
controller&lt;/a&gt;, or simply processing a
real instrument, such as an electric guitar amplifier and cabinet, using the Web
Audio API.
It is generally accepted that latency is not perceptible when below the 20
milliseconds range. This however varies quite a lot depending on the type of
interaction, the frequency content of the sound and quite a lot of other
factors, such as the experience of the person tested: an experienced drummer
might be annoyed even with sub-10 milliseconds output latency. It&amp;rsquo;s important to
put those numbers in perspective: an electric guitar player playing 5 meters
away from the amplifier cabinet has a latency of:&lt;/p&gt;
&lt;p&gt;$$ \begin{aligned} \frac{d}{V_s} &amp;amp;= \ \frac{5m}{343m \cdot s^{-1}} &amp;amp;\approx  0.0146s \ &amp;amp;=  14.6ms \end{aligned} $$&lt;/p&gt;
&lt;p&gt;Where \( V_s \) is the speed of sound (at 20°C, but from experience when
playing the guitar furiously, things heat up quickly and the air gets moist,
lowering the speaker to ear latency), \(d\) the distance in meter, and \(l\)
the latency.&lt;/p&gt;
&lt;p&gt;Low latency is often unnecessary: when playing non-real time content (such as a
song, a movie, or a twitch stream), it&amp;rsquo;s only necessary to &lt;em&gt;know&lt;/em&gt; the exact
latency figure, to perform proper audio/video synchronization. Humans don&amp;rsquo;t
notice it too much when audio is late compared to video (up to a point &lt;sup id=&#34;fnref:2&#34;&gt;&lt;a href=&#34;#fn:2&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;),
but the opposite has an horrible effect and is really noticeable.&lt;/p&gt;
&lt;p&gt;By delaying the video frames an appropriate amount of milliseconds, and by
knowing the latency of the audio output device, perfect audio/video
synchronization can be achieved, regardless of the inherent audio output latency
of the setup. This really is important when watching a movie with a Bluetooth
headset, which is a rather common case. Some software allow users to shift the
audio or video track a few milliseconds each way, but it&amp;rsquo;s always best to have
it working automatically.&lt;/p&gt;
&lt;p&gt;Playing video on the web is very often (but not always) done using the
&lt;code&gt;HTMLVideoElement&lt;/code&gt; object (&lt;code&gt;&amp;lt;video&amp;gt;&lt;/code&gt; in markup). In most browsers, this will do
audio output latency compensation automatically. All is well.&lt;/p&gt;
&lt;p&gt;However when authors want to do things that are a bit more advanced, they often
use the Web Audio API to do their audio processing, and render the video frames
using a canvas (either 2D or 3D, depending on the application). When doing
things manually like this, the browser cannot automatically shift the video
frames based on the audio output latency anymore. Because, by default, Web Audio
API implementations try to use low-latency audio output streams, and because on
desktop audio output latencies on a lot of configurations are comparable to the
display latency &lt;sup id=&#34;fnref:3&#34;&gt;&lt;a href=&#34;#fn:3&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;, this is fine. However when this is not the case,
synchronization is incorrect, and authors had no real solution.&lt;/p&gt;
&lt;h1 id=&#34;new-members-on-the-audiocontext-interface&#34;&gt;New members on the AudioContext interface&lt;/h1&gt;
&lt;p&gt;The &lt;code&gt;AudioContext&lt;/code&gt; is the go-to interface for doing anything non-trivial with
audio on the Web. It was originally only doing low-latency audio, and the
latency was not configurable, but we later added a way to request
&lt;a href=&#34;https://webaudio.github.io/web-audio-api/#dom-audiocontextoptions-latencyhint&#34;&gt;higher-latency
streams&lt;/a&gt;,
which can be helpful for two reasons.&lt;/p&gt;
&lt;p&gt;First, low-latency audio streams often consume much more CPU and
energy than higher-latency audio streams: the audio thread has to wake up more
often. Second, because of various reasons, it&amp;rsquo;s often faster to perform a
computation on, say, a 2048 frames buffer, than it it to perform the same
computation 16 times on a 128 frames buffer, each computation happening in an
audio callback being called in a roughly isochronous fashion.&lt;/p&gt;
&lt;p&gt;When instantiating an &lt;code&gt;AudioContext&lt;/code&gt;, authors can ask for an arbitrarily
low-latency (expressed in seconds), and implementations will try to honor the
request, down to a minimum under which it can&amp;rsquo;t. In the Web Audio API, the hard
limit is 128 frames (≈2.66ms at 48kHz, because we&amp;rsquo;ve specified all the
processing based on 128 frames block processing), but in practice, this depends
on the setup of the device.&lt;/p&gt;
&lt;p&gt;In any way, knowing the &lt;em&gt;real&lt;/em&gt; audio output latency is really something that was
missing from the Web plaform. To solve this in the Web Audio API, we added three
members to the &lt;code&gt;AudioContext&lt;/code&gt; interface, and I just landed patches in Firefox to
implement them:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;baseLatency&lt;/code&gt; is a floating point number that represent the number of seconds
the &lt;code&gt;AudioContext&lt;/code&gt; uses for its internal processing, once the audio reaches
the &lt;code&gt;AudioDestinationNode&lt;/code&gt;. In Firefox, this is always 0 because we process the
audio directly in the audio callback.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;outputLatency&lt;/code&gt; is another floating point number that represents the number of
seconds of latency between the audio reaching the &lt;code&gt;AudioDestinationNode&lt;/code&gt;
(conceptually the audio sink of the audio processing graph) and the audio output
device. This is the number that varies widely depending on the setup.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;getOutputTimestamp&lt;/code&gt; is a method that returns a JavaScript dictionary that
contains two members: &lt;code&gt;contextTime&lt;/code&gt; is in the same unit and clock domain as
&lt;code&gt;AudioContext.currentTime&lt;/code&gt;, and is the sample-frame that is currently being
output by the audio output device, converted to seconds. &lt;code&gt;performanceTime&lt;/code&gt; is
the same number, but in the same clock domain and unit as &lt;code&gt;performance.now()&lt;/code&gt;
(in milliseconds).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The system clock and the audio clock can (and do very frequently) drift apart,
and this third member allow easily mapping the two clock domains together.&lt;/p&gt;
&lt;p&gt;Authors working on an application that need audio/video synchronization can use
&lt;code&gt;outputLatency&lt;/code&gt; to synchronize their rendering: instead of painting video frames
as soon as they are rendered, they can shift the clock of the rendering by
&lt;code&gt;outputLatency&lt;/code&gt;, and audio and video will be in sync. This mostly matters with
high-latency audio output devices (often, Bluetooth headset in A2DP profile),
which is very common these days, but it&amp;rsquo;s a good habit to always use this, so
that people that are, for example, on low end Android device, that are known to
have an audio output latency that is in the longer end of the spectrum, have a
better experience.&lt;/p&gt;
&lt;h1 id=&#34;now-the-catch&#34;&gt;Now, the catch&lt;/h1&gt;
&lt;p&gt;While it&amp;rsquo;s easy to measure the round-trip latency, and reasonably
straightforward to estimate the output latency, it&amp;rsquo;s a bit harder to find this
number in the program running, for a variety of reasons:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Sometimes the drivers are &lt;strong&gt;just lying&lt;/strong&gt; when reporting the value.  If the
device is very common, we can hard-code a sensible value. Otherwise, it&amp;rsquo;s just
too bad.&lt;/li&gt;
&lt;li&gt;Sometimes the call to get the value &lt;strong&gt;does not work&lt;/strong&gt; on certain versions of
the OS. This is the case on Windows 10 where &lt;code&gt;GetStreamLatency&lt;/code&gt; on the
&lt;code&gt;IAudioClient&lt;/code&gt; interface seem to always return 0 on my (very standard) Dell
XPS15. I&amp;rsquo;m fairly certain it worked when I implemented this feature back in 2013
on Windows 7. I&amp;rsquo;ll be working around this bug in the near future, but it won&amp;rsquo;t
be accurate until then.&lt;/li&gt;
&lt;li&gt;There is &lt;strong&gt;time that is hard to account for&lt;/strong&gt;, in the audio input/output
pipeline.  A/D and D/A converters usually take a short but non-zero amount of
sample, often because they run some filtering on the audio data. Some
platforms also are a bit better than other at including more bits of the
pipeline in the latency value they report.&lt;/li&gt;
&lt;li&gt;The setup between the device and the audio output device can be &lt;strong&gt;a bit more
complicated&lt;/strong&gt;: the audio output can go to a mixing desk and or proper sound
system with more digital or analog effects, and we can&amp;rsquo;t really account for
this. If the setup is somewhat under control and fixed (for example for an art
installation, or a live performance where the performers control part of the
setup), adding hard-coded values can help.&lt;/li&gt;
&lt;li&gt;Some audio APIs change the buffer size &lt;strong&gt;dynamically&lt;/strong&gt; depending on the load of
the system, and/or the presence or absence of other streams with different
characteristics (Windows 10 and WASAPI when using the &lt;code&gt;IAudioClient3&lt;/code&gt; interface,
and PulseAudio). This is surfaced in the &lt;code&gt;AudioContext&lt;/code&gt; API (calling it again
yields a different value), but there is no event fired when this value changes.
Querying it as part of rendering a video frame each time might be useful, but I
am yet to quantify the time it takes to do so. It depends widely on the
platform, it can be as easy as reading a integer or two (sometimes atomics,
which is a lot more expensive) and performing a couple divisions, or it can be a
system call, that I hope is not too expensive.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When running Firefox Nightly (for now, this is going to release on the
22&lt;sup&gt;nd&lt;/sup&gt; of October 2019), have a look at those values on your setup, and
if they don&amp;rsquo;t make sense, please open a bug in the &lt;a href=&#34;https://bugzilla.mozilla.org/enter_bug.cgi?product=Core&amp;amp;component=Web%20Audio&#34;&gt;Web Audio API Bugzilla
component&lt;/a&gt;
(simply login with a GitHub account if you don&amp;rsquo;t have a Bugzilla account on our
instance), explain your setup, and the values you see, and I&amp;rsquo;ll try to get it
fixed.&lt;/p&gt;
&lt;section class=&#34;footnotes&#34; role=&#34;doc-endnotes&#34;&gt;
&lt;hr&gt;
&lt;ol&gt;
&lt;li id=&#34;fn:1&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;Round-trip latency refers to the time it takes between the moment a sound wave enters a system (say, a microphone, for a recording system) to the moment it&amp;rsquo;s output by the output device (speaker, headphones, etc.), when routing directly the input device to the output device. The system can be a human however, the case of key-press to ear latency, or another measurement device, or anything, as long as it&amp;rsquo;s useful for the problem at hand and clearly defined. &lt;a href=&#34;#fnref:1&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:2&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;Humans are used to see things earlier than they hear it, because sound speed in the air is &lt;em&gt;much&lt;/em&gt; slower than the speed of light in air. If someone is speaking 10 meters away from you, it takes about 30ms for the sound waves to reach your ear. The first few chapters of the first volume of &lt;a href=&#34;https://audioanecdotes.com/the-books/&#34;&gt;Audio Anecdotes&lt;/a&gt; are a good introduction to the field of auditory perception for practical purposes. &lt;a href=&#34;#fnref:2&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:3&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;Input and screen latency are certainly not to be ignored when doing interactive programes. For very good reasons (&lt;a href=&#34;https://en.wikipedia.org/wiki/Multiple_buffering&#34;&gt;double/triple buffering&lt;/a&gt;) and &lt;a href=&#34;https://danluu.com/keyboard-latency/&#34;&gt;less good reasons&lt;/a&gt;, the time it takes from pressing a key on a keyboard to the display changing on a typical computer can be quite long. And this is the ideal scenario, it&amp;rsquo;s not uncommon for rendering pipelines to have a frame or more of additional latency. Quite a lot of tradeoffs of various complexity can be made to achieve a better overall experience. &lt;a href=&#34;#fnref:3&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</description>
    </item>
    
    
      
    <item>
      <title>Media Stream Track Audio Source Node available in Firefox Nightly</title>
      <link>https://blog.paul.cx/post/mediastreamtrackaudiosourcenode/</link>
      <pubDate>Mon, 29 Apr 2019 08:15:17 +0000</pubDate>
      
      <guid>https://blog.paul.cx/post/mediastreamtrackaudiosourcenode/</guid>
      <description>&lt;p&gt;Firefox Nightly now has an implementation of &lt;code&gt;MediaStreamTrackAudioSourceNode&lt;/code&gt;.
It&amp;rsquo;s very similar to &lt;code&gt;MediaStreamAudioSourceNode&lt;/code&gt;, and might even be
poly-fillable on implementations that don&amp;rsquo;t have this new &lt;code&gt;AudioNode&lt;/code&gt;. It&amp;rsquo;s not
a particularly complicated feature. However, it can serve as a demonstration of
how a new feature is added to the Web Platform  (at least in the Audio Working
Group), and as an opportunity to touch upon the problems browser engineers and
standards people can run into.&lt;/p&gt;
&lt;p&gt;In this post, I’ll detail the standard process and the Firefox implementation of
this feature, then try to shed some light on why such a simple feature is needed
in the first place, and why it took so long to finish and ship.&lt;/p&gt;
&lt;figure class=&#34;fullwidth&#34;&gt;
    &lt;img src=&#34;https://blog.paul.cx/tracks.jpg&#34;/&gt; &lt;figcaption&gt;
            &lt;h4&gt;MediaStreamTrackAudioSourceNode is useful only if you have multiple audio tracks on a single MediaStream&lt;/h4&gt;
        &lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h1 id=&#34;why-we-really-needed-this-and-the-backstory&#34;&gt;Why we really needed this, and the backstory&lt;/h1&gt;
&lt;p&gt;When the Web Audio API specification &lt;a href=&#34;https://www.w3.org/TR/2011/WD-webaudio-20111215/&#34;&gt;first
dropped&lt;/a&gt; in the early 2011,
there wasn&amp;rsquo;t anything to connect a &lt;code&gt;MediaStream&lt;/code&gt; to a processing graph built
using the Web Audio API.  This was a big problem: &lt;code&gt;MediaStream&lt;/code&gt;s are the
backbone of real-time media routing on the Web, and can be the input or output
of WebRTC &lt;code&gt;PeerConnection&lt;/code&gt;s, &lt;code&gt;MediaRecorder&lt;/code&gt;, audio device input via
&lt;code&gt;getUserMedia&lt;/code&gt;, and various other bits of the Web Platform.&lt;/p&gt;
&lt;p&gt;It was always possible to &lt;em&gt;render&lt;/em&gt; the output of a &lt;code&gt;MediaStream&lt;/code&gt; using an
&lt;code&gt;HTMLMediaElement&lt;/code&gt; (either a &lt;code&gt;&amp;lt;video&amp;gt;&lt;/code&gt; or &lt;code&gt;&amp;lt;audio&amp;gt;&lt;/code&gt; tag), but the only
processing one could do to the audio stream was perhaps to change its output
volume. When richer audio processing is needed in a Web application, using an
&lt;code&gt;AudioContext&lt;/code&gt; is always the answer. At the time, the two constructs couldn&amp;rsquo;t
be used together.&lt;/p&gt;
&lt;p&gt;A year later, in the &lt;a href=&#34;https://www.w3.org/TR/2012/WD-webaudio-20121213/#MediaStreamAudioSourceNode&#34;&gt;2012 Working
Draft&lt;/a&gt;
appeared a new &lt;code&gt;AudioNode&lt;/code&gt;, called &lt;code&gt;MediaStreamAudioSourceNode&lt;/code&gt;, that allowed a
Web Audio API processing graph to have an input that was a &lt;code&gt;MediaStream&lt;/code&gt;. It was
described like so:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;This interface represents an audio source from a MediaStream. The first
AudioMediaStreamTrack from the MediaStream will be used as a source of audio.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;With a constructor, in WebIDL, that looked like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-webidl&#34; data-lang=&#34;webidl&#34;&gt;partial interface AudioContext {
    MediaStreamAudioSourceNode createMediaStreamSource(MediaStream mediaStream);
};
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This was all and well, and this node has been absolutely instrumental to the
success of the Web Audio API, along with its counterpart,
&lt;code&gt;MediaStreamAudioDestinationNode&lt;/code&gt;, that does the opposite: from a Web Audio API
graph, you can get a &lt;code&gt;MediaStream&lt;/code&gt; that contains the audio generated by the
graph, that you can then use to do something else.&lt;/p&gt;
&lt;p&gt;But then we received this message on the &lt;code&gt;public-audio&lt;/code&gt; W3C mailing list &lt;sup id=&#34;fnref:1&#34;&gt;&lt;a href=&#34;#fn:1&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;1&lt;/a&gt;&lt;/sup&gt; on
October 2013, from Stefan Håkansson LK from Ericsson:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Hi,&lt;/p&gt;
&lt;p&gt;I have a comment triggered by the new public draft being announced:&lt;/p&gt;
&lt;p&gt;In section 4.24 it is said that &amp;ldquo;The first AudioMediaStreamTrack from
the MediaStream will be used as a source of audio.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;Which audio track that is the first one is undefined (in the case when
there is more than one). I think it would make much more sense to deal
directly with a MediaStreamTrack (of kind audio) in this API (which
should as a consequence be renamed to &amp;quot; MediaStreamTrackAudioSourceNode&amp;rdquo;).&lt;/p&gt;
&lt;p&gt;And it would probably make sense to rename
&amp;ldquo;MediaStreamAudioDestinationNode&amp;rdquo; to
&amp;ldquo;MediaStreamTrackAudioDestinationNode&amp;rdquo;, and have it produce a
MediaStreamTrack.&lt;/p&gt;
&lt;p&gt;Br,&lt;br&gt;
Stefan&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Now, this makes a lot of sense, looking at the specification that defines
&lt;code&gt;MediaStream&lt;/code&gt;, &lt;a href=&#34;https://w3c.github.io/mediacapture-main/#track-set&#34;&gt;Media Capture and
Streams&lt;/a&gt;, we can read:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The tracks of a &lt;code&gt;MediaStream&lt;/code&gt; are stored in a track set. The track set MUST
contain the &lt;code&gt;MediaStreamTrack&lt;/code&gt; objects that correspond to the tracks of the
stream. The relative order of the tracks in the set is User Agent defined and
the API will never put any requirements on the order. The proper way to find a
specific &lt;code&gt;MediaStreamTrack&lt;/code&gt; object in the set is to look it up by its id.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So we had the Web Audio API spec saying something that was simply incorrect, and
two implementations (and three browsers, at the time, Safari and Chromium were
both based on WebKit) had implemented it &lt;sup id=&#34;fnref:2&#34;&gt;&lt;a href=&#34;#fn:2&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;, that was great.&lt;/p&gt;
&lt;p&gt;It took a few GitHub issues (ported from the w3c bugzilla instance) to sort the
situation out.&lt;/p&gt;
&lt;p&gt;In &lt;a href=&#34;https://github.com/WebAudio/web-audio-api/issues/132&#34;&gt;issue #132&lt;/a&gt;, an
alternative design was proposed. Instead of picking a hypothetical &amp;ldquo;first
track&amp;rdquo;, the &lt;code&gt;MediaStreamAudioSourceNode&lt;/code&gt; would output all tracks, each one in a
different output. However it was quickly noticed that this wouldn&amp;rsquo;t
solve the problem completely, as there would be no way for authors to know which
input track in the &lt;code&gt;MediaStream&lt;/code&gt; matched which output of the
&lt;code&gt;AudioNode&lt;/code&gt;. In the Web Audio API, the order of the output is meaningful and
based on a numeric index: the first output of a &lt;code&gt;ChannelSplitterNode&lt;/code&gt; is always
the first channel in its single, possibly multichannel input: the mapping is
straightforward. The order of the tracks in a &lt;code&gt;MediaStream&lt;/code&gt; is not defined, and
is based on identifiers, which are most of the time UUIDs (this is recommended
by the spec but not mandatory), that do not map naturally to outputs. This
design was abandoned.&lt;/p&gt;
&lt;p&gt;It felt easier to simply let authors enumerate the tracks on their
&lt;code&gt;MediaStream&lt;/code&gt;, pick the right one for their use case, and have only this track
routed to the audio graph: this lets the browser engine perform optimizations on
the other tracks, such as, doing absolutely nothing with them if possible (which
is the best optimization one can do).&lt;/p&gt;
&lt;p&gt;In &lt;a href=&#34;https://github.com/WebAudio/web-audio-api/issues/264&#34;&gt;issue #264&lt;/a&gt;, it was
decided that the solution would be two-fold:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create a new &lt;code&gt;AudioNode&lt;/code&gt;, &lt;code&gt;MediaStreamTrackAudioSourceNode&lt;/code&gt;, that would let
authors choose which track was to be routed to the &lt;code&gt;AudioContext&lt;/code&gt; ;&lt;/li&gt;
&lt;li&gt;Specify correctly which track would be picked when creating a
&lt;code&gt;MediaStreamAudioSourceNode&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The first bit was easy, done in &lt;a href=&#34;https://github.com/WebAudio/web-audio-api/commit/59734de1310d623e02c0f818b7e24d1266036d5a&#34;&gt;PR #982&lt;/a&gt;.
Of course it was initially incorrect when merged: I typo-ed the factory method
&lt;sup id=&#34;fnref:3&#34;&gt;&lt;a href=&#34;#fn:3&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;, and then added the fact that trying to create a
&lt;code&gt;MediaStreamTrackAudioSourceNode&lt;/code&gt; should throw when passed in a track that is
not a track of &lt;code&gt;kind&lt;/code&gt; &lt;code&gt;&amp;quot;audio&amp;quot;&lt;/code&gt;. But after those fixups, it was done and
correct. Usually, those mistakes at caught during the review, but not this time
it seems.&lt;/p&gt;
&lt;p&gt;The second bit was not too hard, but a bit arbitrary, which is often a bit
annoying in software, where we like to know why things happen or are the way
they are. We wanted to have a way (any way really) to pick the first track, in a
manner that would be stable across implementations.  We ended up ordering by
their &lt;code&gt;id&lt;/code&gt; property. Now, this works, but sorting strings is a surprisingly
complicated affair: you can&amp;rsquo;t just wing it and hope to be correct when you&amp;rsquo;re
a programmer that mostly deal with audio.  When trying to move a W3C
specification to a state of &lt;a href=&#34;https://www.w3.org/2004/02/Process-20040205/tr.html#q73&#34;&gt;Candidate
Recommendation&lt;/a&gt;, a
document has to be reviewed by a few groups, for example for security or privacy
issues, but also by the internationalization working group (usually referred to
by its abbreviation, i18n). We don&amp;rsquo;t deal with text too much in the Web Audio
API, but they did find that we were trying to sort things &amp;ldquo;alphabetically&amp;rdquo;,
which makes little sense in reality, and is very vague.&lt;/p&gt;
&lt;p&gt;Quoting &lt;a href=&#34;https://github.com/w3c/i18n-activity/issues/598&#34;&gt;the review&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Sorting alphabetically seems to be underspecified. Given that MediaStreamTrack
id attributes are recommended to be UUIDs and that the &amp;ldquo;alphabetic&amp;rdquo; sorting
appears to be an arbitrary way to prioritize the item selection, defining the
comparison as ASCII case-insensitive might be a good choice. However, since
there is no actual restriction on what the values can be, I&amp;rsquo;d suggest that you
replace &amp;ldquo;alphabetically&amp;rdquo; with ordering by code point (which means that it is
case-sensitive, please note)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I ended up doing that in &lt;a href=&#34;https://github.com/WebAudio/web-audio-api/pull/1811&#34;&gt;PR #1811&lt;/a&gt;
, by specifiying that the tracks were to be sorted by Unicode code point value,
which is the way the &lt;code&gt;sort&lt;/code&gt; method in EcmaScript sort things. When picking
things arbitrarily, it&amp;rsquo;s often best to do the same things as elsewhere.&lt;/p&gt;
&lt;p&gt;The old and incorrect prose for &lt;code&gt;MediaStreamAudioSourceNode&lt;/code&gt; was now correct and
defined: on construction, a sort is performed on the tracks, based on their &lt;code&gt;id&lt;/code&gt;
property, that is a string, the first element in the resulting collection is
picked as the input.&lt;/p&gt;
&lt;p&gt;It only took 5 years from the time we became aware of the problem to having a
correct text.  Granted, if we were to tally the cumulative hours spent working
on this particular feature, they would amount to no more than a dozen, spent
pinpointing the issue, finding a viable solution, writing and reviewing the spec
text, tweaking the prose, performing fixes, and reviewing them.&lt;/p&gt;
&lt;p&gt;This is a prime example of why things like this take time: the W3C Audio Working
Group was certainly not inactive during this time (other things, like
&lt;code&gt;AudioWorklet&lt;/code&gt;, or other more pressing matters, took precedence). There were
simply too many other things on our plate to finish this task in a timely
manner.&lt;/p&gt;
&lt;h1 id=&#34;the-implementation-part&#34;&gt;The implementation part&lt;/h1&gt;
&lt;p&gt;Most of the implementation work wasn&amp;rsquo;t done by me: I was mentoring students from
the Lyon 1 University in Lyon, France, where &lt;a href=&#34;https://matthieu-moy.fr/&#34;&gt;Matthieu
Moy&lt;/a&gt; leads a school project where students work
on open source or free software projects. I&amp;rsquo;ve been doing that with him for a
few years now, it&amp;rsquo;s great.&lt;/p&gt;
&lt;p&gt;Sometimes multiple people work on a single bug in this project, sometimes it&amp;rsquo;s
only a single person. What I know is that this was started in October 2017, and
that the name on the patch is Léo Paquet, apologies if other people worked on
this feature!&lt;/p&gt;
&lt;p&gt;This was worked on in &lt;a href=&#34;https://bugzilla.mozilla.org/show_bug.cgi?id=1324548&#34;&gt;Bug
1324548&lt;/a&gt;, I did the
initial review pass, and my colleague &lt;a href=&#34;https://twitter.com/pehrsons&#34;&gt;Andreas
Pehrson&lt;/a&gt; did most of the in-depth review work.
There were tests of course, there is no chance that a web-facing feature would
be merged in Gecko without comprehensive tests. Those were written using Gecko&amp;rsquo;s
&lt;a href=&#34;https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Mochitest&#34;&gt;Mochitest&lt;/a&gt;
test harness. Mochitest, at the time, was the harness of choice when testing
features that are exposed to Web. These days, &lt;a href=&#34;https://web-platform-tests.org/&#34;&gt;Web Platform
Tests&lt;/a&gt; are a better option, but have a number
of limitations still.&lt;/p&gt;
&lt;p&gt;Later, the school project ended, and this was abandoned somewhat.&lt;/p&gt;
&lt;p&gt;I picked it up when my manager noticed that it seemed like we were sitting on a
mostly finished patch with tests. Of course things had become somewhat bit
rotten &lt;sup id=&#34;fnref:4&#34;&gt;&lt;a href=&#34;#fn:4&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;4&lt;/a&gt;&lt;/sup&gt; and there was a &lt;code&gt;MediaStreamTrack&lt;/code&gt; leaking at shutdown &lt;sup id=&#34;fnref:5&#34;&gt;&lt;a href=&#34;#fn:5&#34; class=&#34;footnote-ref&#34; role=&#34;doc-noteref&#34;&gt;5&lt;/a&gt;&lt;/sup&gt;, so I
fixed that with, again, the help of Andreas, at the back of a conference room
during a big meeting in &lt;a href=&#34;https://wiki.mozilla.org/All_Hands/Orlando2018&#34;&gt;Mozlando 2018&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;He wanted a bit more tests before landing, so I started doing that.
Specifically, more testing around the security sensitive bit of the patch: what
happens if the &lt;code&gt;MediaStreamTrack&lt;/code&gt; that is being routed to the &lt;code&gt;AudioContext&lt;/code&gt;
processing graph has content that is not
&lt;a href=&#34;https://en.wikipedia.org/wiki/Same-origin_policy&#34;&gt;same-origin&lt;/a&gt;? The content of
the &lt;code&gt;MediaStreamTrack&lt;/code&gt; has to be replaced by silence, otherwise it&amp;rsquo;s a pretty
severe cross-origin information leakage: a website could open a URL that is not
from the same origin, and that has not agreed to be read from another origin,
and inspect the contents of the audio file. We also tried to determine whether
it was possible to have a source that was same-origin, that would then switch to
a cross-origin, for example because of an HTTP redirect.&lt;/p&gt;
&lt;p&gt;For a long time, in Firefox, this was possible. This is another good story
outlined in Jake Archibald&amp;rsquo;s
&lt;a href=&#34;https://jakearchibald.com/2018/i-discovered-a-browser-bug/&#34;&gt;post&lt;/a&gt; called &amp;ldquo;I
found a browser bug&amp;rdquo;. In current Firefox, since &lt;a href=&#34;https://bugzilla.mozilla.org/show_bug.cgi?id=1443942&#34;&gt;bug
1443942&lt;/a&gt; landed,
mid-flight redirects to cross-origin destinations are now blocked when loading
media resources so this is not possible anymore. I do believe Firefox would
have been safe (read: would have silenced the cross-origin media dynamically
after the redirect) even if this was still possible the cross-origin
status on media sources is dynamically updated on the
&lt;code&gt;MediaStreamTrackAudioSourceNode&lt;/code&gt;, from its source.&lt;/p&gt;
&lt;p&gt;Another test was to check whether everything continues working correctly if all
the references to the input &lt;code&gt;MediaStreamTrack&lt;/code&gt; were to be dropped by the
JavaScript code. Historically, this was a bug that Firefox had: if you were to
use a &lt;code&gt;MediaStreamAudioSourceNode&lt;/code&gt;, with, say, a &lt;code&gt;MediaStream&lt;/code&gt; that was from a
&lt;code&gt;getUserMedia&lt;/code&gt; call, and you dropped all references in the code, the
&lt;code&gt;MediaStream&lt;/code&gt; would suddently be collected, and you stopped getting input data
in the &lt;code&gt;MediaStreamAudioSourceNode&lt;/code&gt;. This is why you still see authors sticking
expandos with &lt;code&gt;MediaStream&lt;/code&gt;s from &lt;code&gt;getUserMedia&lt;/code&gt; calls on global objects to work
around this Firefox bug, which was fixed in &lt;a href=&#34;https://bugzilla.mozilla.org/show_bug.cgi?id=934512&#34;&gt;bug
934512&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;It would have been better to write Web Platform Tests, and this is something
I&amp;rsquo;ll try to get done in the future. It&amp;rsquo;s possible to write involved redirect
tests, but it does not seem possible to trigger garbage collection yet, from a
Web Platform Test (we use a &lt;a href=&#34;https://searchfox.org/mozilla-central/source/dom/media/webaudio/test/test_mediaStreamAudioSourceNodeNoGC.html#62&#34;&gt;privileged Gecko
API&lt;/a&gt; do do so in our tests).&lt;/p&gt;
&lt;h1 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Nothing about &lt;code&gt;MediaStreamTrackAudioSourceNode&lt;/code&gt; is inherently difficult or
complex, but it still took a very long time to specify and implement. Looking
back, we can isolate a few problems that caused this simple feature to
take a very long time to be finished and shipped.&lt;/p&gt;
&lt;p&gt;First, there are very few people that are interested in working on standards, and
amongst them even fewer people have an interest in working on
fixing historical problems in a specification. It&amp;rsquo;s the eternal problem of
maintenance of existing work: it&amp;rsquo;s always more interesting to work on new
things, but it&amp;rsquo;s more often than not more useful to work on older things that
have bugs. Fortunately, everybody can comment on a W3C spec, and the process
invites a number of groups, with specific skill sets, to do formal reviews of
the work, when it&amp;rsquo;s considered advanced enough.&lt;/p&gt;
&lt;p&gt;Then, we&amp;rsquo;ve seen that this is a feature that is somewhat important, but not
important enough to be fixed quickly. To come back to our problem here, if a
particular problem required to route a particular &lt;code&gt;MediaStreamTrack&lt;/code&gt; to a Web
Audio API graph, it was always possible to create a new &lt;code&gt;MediaStream&lt;/code&gt;, find the
track in the initial &lt;code&gt;MediaStream&lt;/code&gt; that needs to be routed to the graph, clone
it, and add this track to this new &lt;code&gt;MediaStream&lt;/code&gt;, and use
&lt;code&gt;MediaStreamAudioSourceNode&lt;/code&gt;. It&amp;rsquo;s however nicer to not have to do that.&lt;/p&gt;
&lt;p&gt;On the implementation part, it is very often much faster to finish things
without waiting. Bit rot will cause lots of churn, sometimes rebases are not
trivial.  Forgetting about the code and re-learning it to finish a patch is a
waste of time, but sometimes you have no choice: I&amp;rsquo;m certainly not going to
finish a feature that is nice to have when I have a couple crashes with security
implications to work on.&lt;/p&gt;
&lt;p&gt;And finally, the web is always evolving: the thing that was important to test
here (the behaviour of cross-origin resources during redirects) was made
impossible by another platform change (for the better, this time around): I
probably spent a few hours to try to consider all possible cross-origin status
changes, to make sure we were not leaving a little hole that an attacker could
have used to exfiltrate private data.&lt;/p&gt;
&lt;p&gt;Things take time, it&amp;rsquo;s fine.&lt;/p&gt;
&lt;section class=&#34;footnotes&#34; role=&#34;doc-endnotes&#34;&gt;
&lt;hr&gt;
&lt;ol&gt;
&lt;li id=&#34;fn:1&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;This is where most of the standards discussion used to happen, before we switched to using GitHub issues. We still use it for official annoucements, such as details for meetings, working draft release, etc. The archive is available publicly at &lt;a href=&#34;https://lists.w3.org/Archives/Public/public-audio/&#34;&gt;https://lists.w3.org/Archives/Public/public-audio/&lt;/a&gt; &lt;a href=&#34;#fnref:1&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:2&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;Gecko had an implementation at the time, and we shipped the Web Audio API in Firefox 25, that was released exactly 11 days after Stefan&amp;rsquo;s post to the list. That is to say, the code was already written &lt;a href=&#34;#fnref:2&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:3&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;In Web Audio API spec lingo, this is how we call the methods that are on the &lt;code&gt;BaseAudioContext&lt;/code&gt;, such as &lt;code&gt;createGain&lt;/code&gt;, vs. the constructors, such as &lt;code&gt;new GainNode(ctx, {gain: 0.3})&lt;/code&gt; &lt;a href=&#34;#fnref:3&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:4&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;In Mozilla jargon, this refers to a patch or a set of patches that does not apply anymore because the underlying code has changed &lt;a href=&#34;#fnref:4&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:5&#34; role=&#34;doc-endnote&#34;&gt;
&lt;p&gt;We use reference counting heavily in Firefox, this was a case of a cycle of references between objects, that weren&amp;rsquo;t registered to the &lt;a href=&#34;https://blog.kylehuey.com/post/27564411715/cycle-collection&#34;&gt;cycle collector&lt;/a&gt;. Here, the objects were alive at shutdown (instead of being collected a lot earlier), and this kind of error make the tests fail &lt;a href=&#34;#fnref:5&#34; class=&#34;footnote-backref&#34; role=&#34;doc-backlink&#34;&gt;&amp;#x21a9;&amp;#xfe0e;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</description>
    </item>
    
    
  </channel>
</rss>
