Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WorkletScriptNode Prototype #254

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/_data/build_info.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"version":"3.0.2","revision":"a484ed9","lastUpdated":"2022-08-10","copyrightYear":2022}
{"version":"3.0.2","revision":"233cb66","lastUpdated":"2022-08-15","copyrightYear":2022}
126 changes: 126 additions & 0 deletions src/audio-worklet/migration/worklet-script-node/worklet-script-node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import getCustomProcessorUrl from "./worklet-script-processor.js";

class WorkletScriptNode extends AudioWorkletNode {
/**
* @constructor
* @param {BaseAudioContext} context The associated BaseAudioContext.
* @param
*/
constructor(context, options) {
super(context, "worklet-script-processor", {
processorOptions: options
});

this.port.onmessage = onProcessorMessage.bind(this);
}

// Events
onProcessorMessage(event) {
this.previousMessageKind = this.currentMessage.kind;
this.currentMessage = event;
}

postMessage(event) {
this.port.postMessage(event)
}

waitForMessage(eventKind) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (this.currentMessage.kind === event.kind)
resolve(this.currentMessage);
else
console.log(`[WorkletScriptNode] Expected ${eventKind} but got ${this.currentMessage.kind}`);
reject();
}, 1000)
})
}

// Get buffer

getBuffer(bufferName) {
this.postMessage({
kind: "GET_BUFFER",
bufferName
})

await return this.waitForMessage("SHARE_BUFFER")
.then(event => return this.buffer.)
}
}

class WorkletScriptNodeBuilder {

constructor(context, bufferSize = 128, numInputs = 1, numOutputs = 1) {
this.context = context;
this.bufferSize = bufferSize;
this.numInputs = numInputs;
this.numOutputs = numOutputs;

this.processorFunction = () => {};
this.initialState = {};
this.updateRate = 0;

this.useSharedBuffer = true;
this.useRingBuffer = false;

this.bufferSize = bufferSize;
if (bufferSize > 128) {
this.useRingBuffer = true;
}

return this;
}

// Buffers
setProcessor(processFunction) {
this.processorFunction = this.processorFunction

return this;
}

setState(initialState, updateRate) {
this.initialState = initialState;
this.updateRate = updateRate;

return this;
}

useSharedBuffer() {
this.useSharedBuffer = true;
return this;
}

useRingBuffer() {
this.useRingBuffer = true;
return this;
}

addBuffer(bufferOptions) {
this.buffers.push(bufferOptions);
return this;
}

async build() {
const processorName = "worklet-script-processor";

// Prepare processor string
const processorURL = getCustomProcessorUrl(this.processFunction);
await context.audioWorklet.addModule(processorURL);

return new WorkletScriptNode(this.context, {
sampleRate: context.sampleRate,
numInput: this.numInput,
numOutput: this.numOutput,

bufferSize: this.bufferSize,
useRingBuffer: this.useRingBuffer,
useSharedBuffer: this.useSharedBuffer,

initialState: this.initialState,
stateUpdateRate: this.stateUpdateRate,
});
}
}

export default WorkletScriptNodeBuilder
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@

class DummyWorkletProcessor {
constructor(options) {
return;
}
}

class WorkletScriptProcessor extends DummyWorkletProcessor {
constructor(options) {

if (options) {

console.log(options);

this.sampleRate = options.sampleRate;ß

// Buffer Stuff
if (options.bufferSize) {
this.bufferSize = options.bufferSize
}

if (options.useSharedBuffer) {
this.liveBuffer = new Float32Array(new SharedArrayBuffer(this.bufferSize * 4));
} else {
this.liveBuffer = new Float32Array(this.bufferSize);
}

if (options.useRingBuffer) {
this.useRingBuffer = true;
this.ringBufferSegments = this.bufferSize / 128;
this.currentRingSegment = 0;
}

if (this.buffers)

// State stuff
if (options.initialState === true) {
this.state = options.initialState
}
if (options.stateUpdateRate > 0) {
this.stateUpdateRate = options.stateUpdateRate
}

// Inputs and Outputs
if (options.buffers) {
options.buffers.forEach({bufferName, frames, channels, shared}) {
this.buffers[bufferName] = new Array(frames).fill(new Float32Array(frames));
}
}
}

this.port.onmessage = onNodeMessage;

super(options);
}

onNodeMessage(event) {
switch (event.kind) {
case "GET_BUFFER":
if (this.buffers[event.bufferName])
this.port.postMessage({
kind: "SHARE_BUFFER",
buffer: this.buffers[event.bufferName]
})
else
this.port.postMessage({
kind: "ERROR_SHARE_BUFFER_DOESNT_EXIST"
})
break;
}
}
process(inputs, outputs, params) {
this.audioprocess({
playbackTime: 0,
inputBuffer: inputs[0],
outputBuffer: outputs[0],
});
}

audioprocess(event, state) {
console.log("AudioProcess not yet defined.");
}
}

function getCustomProcessorUrl(processFunction) {
let processorString = WorkletScriptProcessor.toString();

// We cannot instantiate AudioWorkletProcessor outside of WorkletNode creation
processorString = processorString.replace("DummyWorkletProcessor", "AudioWorkletProcessor");

console.log(processFunction.toString())

let functionContents = processFunction.toString();

// Strip outermost brackets and everything outside of it
functionContents = functionContents.replace(/^[^{]+\{/g, '');
functionContents = functionContents.replace(/\}$/g, '');

const processorRegex = /audioprocess+\(event\) \{([^}]*)\}/g
const processorContents = processorRegex.exec(processorString)[1].trim();

// Replace the body
processorString = processorString.replace(processorContents, functionContents);

// prepare for instantiate
processorString = processorString.concat("\nregisterProcessor('worklet-script-processor', WorkletScriptProcessor)");

console.log(processorString);

return window.URL.createObjectURL(new Blob([processorString], {
type: "application/javascript; charset=utf-8"
}));
}

export default getCustomProcessorUrl;