Skip to content

Commit

Permalink
Merge pull request #8 from Smona/multi-audio-contexts
Browse files Browse the repository at this point in the history
Support multiple (possibly offline) audio contexts
  • Loading branch information
Smona authored Sep 8, 2022
2 parents 1877d17 + 220d822 commit 9fd67bb
Show file tree
Hide file tree
Showing 13 changed files with 472 additions and 299 deletions.
3 changes: 3 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
test
.log
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
"types": "dist/faustLoader.d.ts",
"scripts": {
"prepare": "install-peers",
"build": "tsc",
"build": "tsc --project tsconfig.build.json",
"serve": "webpack serve -c test/webpack.config.js",
"test": "webpack build -c test/webpack.config.js"
"test": "webpack build -c test/webpack.config.js",
"prepublishOnly": "yarn build && yarn test"
},
"keywords": ["webpack", "loader", "faust", "audio", "dsp"],
"author": "Mason Bourgeois",
Expand All @@ -23,8 +24,9 @@
"@types/fs-extra": "^9.0.11",
"@types/loader-utils": "^2.0.2",
"install-peers-cli": "^2.2.0",
"ts-loader": "^9.3.1",
"typescript": "^4.3.2",
"webpack": "^5.39.0",
"webpack": "^5.40.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
Expand Down
13 changes: 4 additions & 9 deletions src/loadProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ function heap2Str(buf: Uint8Array) {
return str;
}

const processorModules: Record<string, Promise<void>> = {};
async function loadProcessorModule(context: IAudioContext, url: string) {
if (!context.audioWorklet) {
console.error(
Expand All @@ -19,14 +18,10 @@ async function loadProcessorModule(context: IAudioContext, url: string) {
return null;
}

const existing = processorModules[url];

if (existing) {
return existing;
}

processorModules[url] = context.audioWorklet.addModule(url);
return processorModules[url];
// The audio worklet handles caching of modules by URL in the same context.
// Adding an already-loaded module to a different context will trigger another
// network request, but the browser cache should catch it.
return context.audioWorklet.addModule(url);
}

const wasmModules: Record<string, Promise<WebAssembly.Module>> = {};
Expand Down
8 changes: 0 additions & 8 deletions test/Compressor.dsp

This file was deleted.

10 changes: 10 additions & 0 deletions test/TestSynth.dsp
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
declare name "TestSynth";
declare version "1.0";
declare author "Smona";
declare license "BSD";

import("stdfaust.lib");

// TODO: test all input & output types

process = no.noise * 0.1;
4 changes: 4 additions & 0 deletions test/faust-modules.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module "*.dsp" {
const loader: import("../src/faustLoader").ProcessorLoader;
export = loader;
}
7 changes: 7 additions & 0 deletions test/index.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
<html>
<head> </head>
<body>
<h3>Test live context</h3>
<button id="start">Start</button>
<button id="stop">Stop</button>

<h3>Test offline context</h3>
<button id="playback">Play back result</button>

<script src="/build/my-first-webpack.bundle.js"></script>
</body>
</html>
11 changes: 0 additions & 11 deletions test/index.js

This file was deleted.

61 changes: 61 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { AudioContext, OfflineAudioContext } from "standardized-audio-context";
import createCompressor from "./TestSynth.dsp";

const ctx = new AudioContext();
const ctx2 = new AudioContext();
const offline = new OfflineAudioContext({
length: 4 * 44_100,
numberOfChannels: 2,
sampleRate: 44_100,
});

Promise.all([
createCompressor(ctx),
createCompressor(ctx),
createCompressor(ctx),
]).then(async (nodes) => {
console.log(nodes);
const [test] = nodes;
if (!test) throw new Error("Node instantiation failed.");

assert(test.getNumInputs() === 0);
assert(test.getNumOutputs() === 1);

// Second AudioContext tests
const test2 = await createCompressor(ctx2);
if (!test2) throw new Error("Node instantiation failed.");
console.log(test2);
test2.connect(ctx2.destination);

// OfflineAudioContext tests
const testOffline = await createCompressor(offline);
if (!testOffline) throw new Error("Node instantiation failed.");
console.log(testOffline);
testOffline.connect(offline.destination);
const buffer = await offline.startRendering();

console.log("🎉 All tests passed");

// Wire up audio QA controls

document.getElementById("start")?.addEventListener("click", () => {
ctx2.resume();
test2.connect(ctx2.destination);
});
document.getElementById("stop")?.addEventListener("click", () => {
test2.disconnect();
});
document.getElementById("playback")?.addEventListener("click", () => {
ctx2.resume();
const bufferNode = ctx2.createBufferSource();
bufferNode.buffer = buffer;
bufferNode.connect(ctx2.destination);
bufferNode.start();

test2.disconnect();
});
});

function assert(condition: boolean, message = "Test failed!") {
if (!condition) throw new Error(message);
}
13 changes: 12 additions & 1 deletion test/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const path = require("path");

module.exports = {
mode: "development",
entry: path.resolve(__dirname, "index.js"),
entry: path.resolve(__dirname, "index.ts"),
output: {
path: path.resolve(__dirname, "build"),
filename: "my-first-webpack.bundle.js",
Expand All @@ -17,6 +17,17 @@ module.exports = {
},
module: {
rules: [
{
exclude: /node_modules/,
test: /\.ts$/,
use: {
loader: "ts-loader",
options: {
// TODO: re-enable type checking once loader types are fixed
transpileOnly: true,
},
},
},
{
test: /\.dsp$/,
use: [
Expand Down
4 changes: 4 additions & 0 deletions tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["test", "dist"]
}
73 changes: 15 additions & 58 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,70 +1,27 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
"target": "es2016" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"lib": [
"DOM"
] /* Specify library files to be included in the compilation. */,
"declaration": true /* Generates corresponding '.d.ts' file. */,
"outDir": "./dist" /* Redirect output structure to the directory. */,
// "rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,

/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es2016", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": ["DOM"], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
"strict": true /* Enable all strict type-checking options. */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": ["src", "test"],
"exclude": ["dist"]
}
Loading

0 comments on commit 9fd67bb

Please sign in to comment.