Skip to content

Commit 9ad6a3c

Browse files
committed
Add example with WASM audio worklet
1 parent 6daa3d1 commit 9ad6a3c

16 files changed

+380
-1
lines changed

.github/workflows/main.yml

+19-1
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ jobs:
228228
ln -snf `pwd`/target/debug/wasm-bindgen $(dirname `which cargo`)/wasm-bindgen
229229
- run: mv _package.json package.json && npm install && rm package.json
230230
- run: |
231-
for dir in `ls examples | grep -v README | grep -v asm.js | grep -v raytrace | grep -v without-a-bundler | grep -v wasm-in-web-worker | grep -v websockets | grep -v webxr | grep -v deno | grep -v synchronous-instantiation`; do
231+
for dir in `ls examples | grep -v README | grep -v asm.js | grep -v raytrace | grep -v without-a-bundler | grep -v wasm-in-web-worker | grep -v websockets | grep -v webxr | grep -v deno | grep -v synchronous-instantiation | grep -v wasm-audio-worklet`; do
232232
(cd examples/$dir &&
233233
ln -fs ../../node_modules . &&
234234
npm run build -- --output-path ../../exbuild/$dir) || exit 1;
@@ -255,6 +255,23 @@ jobs:
255255
name: examples2
256256
path: exbuild
257257

258+
build_wasm_audio_worklet:
259+
runs-on: ubuntu-latest
260+
steps:
261+
- uses: actions/checkout@v2
262+
- run: rustup default nightly-2022-07-10
263+
- run: rustup target add wasm32-unknown-unknown
264+
- run: rustup component add rust-src
265+
- run: |
266+
sed -i 's/python/#python/' examples/wasm-audio-worklet/build.sh
267+
(cd examples/wasm-audio-worklet && ./build.sh)
268+
mkdir exbuild
269+
cp examples/wasm-audio-worklet/*.{js,html,wasm} exbuild
270+
- uses: actions/upload-artifact@v2
271+
with:
272+
name: examples3
273+
path: exbuild
274+
258275
build_benchmarks:
259276
runs-on: ubuntu-latest
260277
steps:
@@ -394,6 +411,7 @@ jobs:
394411
mv target/doc gh-pages/api
395412
mv artifacts/examples1 gh-pages/exbuild
396413
mv artifacts/examples2 gh-pages/exbuild/raytrace-parallel
414+
mv artifacts/examples3 gh-pages/exbuild/wasm-audio-worklet
397415
mv artifacts/benchmarks gh-pages/benchmarks
398416
tar czf gh-pages.tar.gz gh-pages
399417
- uses: actions/upload-artifact@v2

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ members = [
7777
"examples/raytrace-parallel",
7878
"examples/request-animation-frame",
7979
"examples/todomvc",
80+
"examples/wasm-audio-worklet",
8081
"examples/wasm-in-wasm",
8182
"examples/wasm-in-wasm-imports",
8283
"examples/wasm-in-web-worker",
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
[package]
2+
name = "wasm-audio-worklet"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
7+
console_log = "0.2.0"
8+
js-sys = "0.3.59"
9+
wasm-bindgen = "0.2.82"
10+
wasm-bindgen-futures = "0.4.32"
11+
web-sys = {version = "0.3.59", features = ["AudioContext", "AudioDestinationNode", "AudioWorklet", "AudioWorkletNode", "AudioWorkletNodeOptions", "Blob", "BlobPropertyBag", "Document", "HtmlInputElement", "HtmlLabelElement", "Url", "Window"]}
12+
13+
[lib]
14+
crate-type = ["cdylib", "rlib"]

examples/wasm-audio-worklet/README.md

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# wasm-audio-worklet
2+
3+
[View documentation for this example online][dox] or [View compiled example
4+
online][compiled]
5+
6+
[dox]: https://rustwasm.github.io/docs/wasm-bindgen/examples/wasm-audio-worklet.html
7+
[compiled]: https://rustwasm.github.io/wasm-bindgen/exbuild/wasm-audio-worklet/
8+
9+
You can build the example locally with:
10+
11+
```
12+
$ ./build.sh
13+
```
14+
15+
(or running the commands on Windows manually)
16+
17+
and then visiting http://localhost:8080 in a browser should run the example!
18+
19+
## dependent_module
20+
21+
This example shows how libraries can create worklets with minimal extra effort
22+
for application developers. No extra scripts are needed.
23+
Just the build commands need to be changed to enable threads, and the server
24+
needs to send extra headers to enable site isolation.
25+
26+
dependent_module relies on ES6 `import`, which is
27+
[currently unavailable](https://bugzilla.mozilla.org/show_bug.cgi?id=1572644)
28+
for worklets in Firefox. The example works in Chrome.

examples/wasm-audio-worklet/build.sh

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/bin/sh
2+
3+
set -ex
4+
5+
# A couple of steps are necessary to get this build working which makes it slightly
6+
# nonstandard compared to most other builds.
7+
#
8+
# * First, the Rust standard library needs to be recompiled with atomics
9+
# enabled. to do that we use Cargo's unstable `-Zbuild-std` feature.
10+
#
11+
# * Next we need to compile everything with the `atomics` and `bulk-memory`
12+
# features enabled, ensuring that LLVM will generate atomic instructions,
13+
# shared memory, passive segments, etc.
14+
15+
RUSTFLAGS='-C target-feature=+atomics,+bulk-memory,+mutable-globals' \
16+
cargo build --target wasm32-unknown-unknown --release -Z build-std=std,panic_abort
17+
18+
cargo run -p wasm-bindgen-cli -- \
19+
../../target/wasm32-unknown-unknown/release/wasm_audio_worklet.wasm \
20+
--out-dir . \
21+
--target web
22+
23+
python3 server.py
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>WASM audio worklet</title>
5+
</head>
6+
<body>
7+
<script type="module">
8+
import init, {web_main} from "./wasm_audio_worklet.js";
9+
async function run() {
10+
await init();
11+
web_main();
12+
}
13+
run();
14+
</script>
15+
</body>
16+
</html>

examples/wasm-audio-worklet/server.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#!/usr/bin/env python3
2+
from http.server import HTTPServer, SimpleHTTPRequestHandler, test
3+
import sys
4+
5+
class RequestHandler(SimpleHTTPRequestHandler):
6+
def end_headers(self):
7+
self.send_header('Cross-Origin-Opener-Policy', 'same-origin')
8+
self.send_header('Cross-Origin-Embedder-Policy', 'require-corp')
9+
SimpleHTTPRequestHandler.end_headers(self)
10+
11+
if __name__ == '__main__':
12+
test(RequestHandler, HTTPServer, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
use js_sys::{Array, JsString};
2+
use wasm_bindgen::prelude::*;
3+
use web_sys::{Blob, BlobPropertyBag, Url};
4+
5+
// This is a not-so-clean approach to get the current bindgen JS module URL
6+
// in Rust.
7+
#[wasm_bindgen]
8+
extern "C" {
9+
#[wasm_bindgen]
10+
type ImportMeta;
11+
12+
#[wasm_bindgen(method, getter)]
13+
fn url(this: &ImportMeta) -> JsString;
14+
15+
#[wasm_bindgen(js_namespace = import, js_name = meta)]
16+
static IMPORT_META: ImportMeta;
17+
}
18+
19+
pub fn on_the_fly(code: &str) -> Result<String, JsValue> {
20+
let header = format!(
21+
"import init, * as bindgen from '{}';\n\n",
22+
IMPORT_META.url(),
23+
);
24+
Url::create_object_url_with_blob(&Blob::new_with_str_sequence_and_options(
25+
&Array::of2(&JsValue::from(header.as_str()), &JsValue::from(code)),
26+
&BlobPropertyBag::new().type_("text/javascript"),
27+
)?)
28+
}
29+
30+
// dependent_module! takes a local file name to a JS module as input and
31+
// returns a URL to a slightly modified module in run time. This modified module
32+
// has an additional import statement in the header that imports the current
33+
// bindgen JS module under the `bindgen` alias.
34+
// How this URL is produced does not matter for the macro user. on_the_fly
35+
// creates a blob URL in run time. A better, more sophisticated solution
36+
// would add wasm_bindgen support to put such a module in pkg/ during build time
37+
// and return a relative URL to this file instead.
38+
#[macro_export]
39+
macro_rules! dependent_module {
40+
($file_name:expr) => {
41+
crate::dependent_module::on_the_fly(include_str!($file_name))
42+
};
43+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export function get_bindgen_transferable(o) {
2+
return {
3+
type: Object.getPrototypeOf(o).constructor.name,
4+
ptr: o.ptr,
5+
};
6+
}
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
use crate::oscillator::Params;
2+
use wasm_bindgen::{closure::Closure, JsCast, JsValue};
3+
use web_sys::{AudioContext, HtmlInputElement, HtmlLabelElement};
4+
5+
pub fn create_gui(params: &'static Params, ctx: AudioContext) {
6+
let window = web_sys::window().unwrap();
7+
let document = window.document().unwrap();
8+
let body = document.body().unwrap();
9+
10+
let volume = add_slider(&document, &body, "Volume:").unwrap();
11+
let frequency = add_slider(&document, &body, "Frequency:").unwrap();
12+
volume.set_value("0");
13+
frequency.set_min("20");
14+
frequency.set_value("60");
15+
16+
let listener = Closure::<dyn FnMut(_)>::new(move |_: web_sys::Event| {
17+
params.set_frequency(frequency.value().parse().unwrap());
18+
params.set_volume(volume.value().parse().unwrap());
19+
ctx.resume().unwrap();
20+
})
21+
.into_js_value();
22+
23+
body.add_event_listener_with_callback("input", listener.as_ref().unchecked_ref())
24+
.unwrap();
25+
}
26+
27+
fn add_slider(
28+
document: &web_sys::Document,
29+
body: &web_sys::HtmlElement,
30+
name: &str,
31+
) -> Result<HtmlInputElement, JsValue> {
32+
let input: HtmlInputElement = document.create_element("input")?.unchecked_into();
33+
let label: HtmlLabelElement = document.create_element("label")?.unchecked_into();
34+
input.set_type("range");
35+
label.set_text_content(Some(name));
36+
label.append_child(&input)?;
37+
body.append_child(&label)?;
38+
Ok(input)
39+
}
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
mod dependent_module;
2+
mod gui;
3+
mod oscillator;
4+
mod wasm_audio;
5+
6+
use gui::create_gui;
7+
use oscillator::{Oscillator, Params};
8+
use wasm_audio::wasm_audio;
9+
use wasm_bindgen::prelude::*;
10+
11+
#[wasm_bindgen]
12+
pub async fn web_main() {
13+
// On the application level, audio worklet internals are abstracted by wasm_audio:
14+
let params: &'static Params = Box::leak(Box::new(Params::default()));
15+
let mut osc = Oscillator::new(&params);
16+
let ctx = wasm_audio(Box::new(move |buf| osc.process(buf)))
17+
.await
18+
.unwrap();
19+
create_gui(params, ctx);
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// WASM audio processors can be implemented in Rust without knowing
2+
// about audio worklets.
3+
4+
use std::sync::atomic::{AtomicU8, Ordering};
5+
6+
// Let's implement a simple sine oscillator with variable frequency and volume.
7+
pub struct Oscillator {
8+
params: &'static Params,
9+
accumulator: u32,
10+
}
11+
12+
impl Oscillator {
13+
pub fn new(params: &'static Params) -> Self {
14+
Self {
15+
params,
16+
accumulator: 0,
17+
}
18+
}
19+
}
20+
21+
impl Oscillator {
22+
pub fn process(&mut self, output: &mut [f32]) -> bool {
23+
// This method is called in the audio process thread.
24+
// All imports are set, so host functionality available in worklets
25+
// (for example, logging) can be used:
26+
// `web_sys::console::log_1(&JsValue::from(output.len()));`
27+
// Note that currently TextEncoder and TextDecoder are stubs, so passing
28+
// strings may not work in this thread.
29+
for a in output {
30+
let frequency = self.params.frequency.load(Ordering::Relaxed);
31+
let volume = self.params.volume.load(Ordering::Relaxed);
32+
self.accumulator += u32::from(frequency);
33+
*a = (self.accumulator as f32 / 512.).sin() * (volume as f32 / 100.);
34+
}
35+
true
36+
}
37+
}
38+
39+
#[derive(Default)]
40+
pub struct Params {
41+
// Use atomics for parameters so they can be set in the main thread and
42+
// fetched by the audio process thread without further synchronization.
43+
frequency: AtomicU8,
44+
volume: AtomicU8,
45+
}
46+
47+
impl Params {
48+
pub fn set_frequency(&self, frequency: u8) {
49+
self.frequency.store(frequency, Ordering::Relaxed);
50+
}
51+
pub fn set_volume(&self, volume: u8) {
52+
self.volume.store(volume, Ordering::Relaxed);
53+
}
54+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
if (!globalThis.TextDecoder) {
2+
globalThis.TextDecoder = class TextDecoder {
3+
decode() {
4+
return "";
5+
}
6+
};
7+
}
8+
9+
if (!globalThis.TextEncoder) {
10+
globalThis.TextEncoder = class TextEncoder {
11+
encode() {
12+
return new Uint8Array(0);
13+
}
14+
};
15+
}
16+
17+
export function nop() {
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
use crate::dependent_module;
2+
use wasm_bindgen::prelude::*;
3+
use wasm_bindgen::JsValue;
4+
use wasm_bindgen_futures::JsFuture;
5+
use web_sys::{AudioContext, AudioWorkletNode, AudioWorkletNodeOptions};
6+
7+
#[wasm_bindgen]
8+
struct WasmAudioProcessor(Box<dyn FnMut(&mut [f32]) -> bool>);
9+
10+
#[wasm_bindgen]
11+
impl WasmAudioProcessor {
12+
pub fn process(&mut self, buf: &mut [f32]) -> bool {
13+
self.0(buf)
14+
}
15+
}
16+
17+
// Use wasm_audio if you have a single wasm audio processor in your application
18+
// whose samples should be played directly.
19+
pub async fn wasm_audio(
20+
process: Box<dyn FnMut(&mut [f32]) -> bool>,
21+
) -> Result<AudioContext, JsValue> {
22+
let ctx = AudioContext::new()?;
23+
prepare_wasm_audio(&ctx).await?;
24+
let node = wasm_audio_node(&ctx, process)?;
25+
node.connect_with_audio_node(&ctx.destination())?;
26+
Ok(ctx)
27+
}
28+
29+
// wasm_audio_node creates an AudioWorkletNode running a wasm audio processor.
30+
// Remember to call prepare_wasm_audio once on your context before calling
31+
// this function.
32+
pub fn wasm_audio_node(
33+
ctx: &AudioContext,
34+
process: Box<dyn FnMut(&mut [f32]) -> bool>,
35+
) -> Result<AudioWorkletNode, JsValue> {
36+
AudioWorkletNode::new_with_options(
37+
&ctx,
38+
"WasmProcessor",
39+
&AudioWorkletNodeOptions::new().processor_options(Some(&js_sys::Array::of3(
40+
&wasm_bindgen::module(),
41+
&wasm_bindgen::memory(),
42+
&JsValue::from(WasmAudioProcessor(process)),
43+
))),
44+
)
45+
}
46+
47+
pub async fn prepare_wasm_audio(ctx: &AudioContext) -> Result<(), JsValue> {
48+
nop();
49+
let mod_url = dependent_module!("worklet_async.js")?;
50+
JsFuture::from(ctx.audio_worklet()?.add_module(&mod_url)?).await?;
51+
Ok(())
52+
}
53+
54+
// TextEncoder and TextDecoder are not available in Audio Worklets, but there
55+
// is a dirty workaround: Import polyfill.js to install stub implementations
56+
// of these classes in globalThis.
57+
#[wasm_bindgen(module = "/src/polyfill.js")]
58+
extern "C" {
59+
fn nop();
60+
}

0 commit comments

Comments
 (0)