Skip to content
Draft
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 Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ build:
dist: build
mkdir -p $(BUILD)/build
cp -r $(SRC)/*.html $(SRC)/term.js src/examples $(SRC)/build/sw.js $(BUILD)
cp $(SRC)/build/firmware.js $(SRC)/build/firmware.wasm $(SRC)/build/firmware-debug.js $(SRC)/build/firmware-debug.wasm $(SRC)/build/firmware-debug.dwarf.wasm $(SRC)/build/simulator.js $(BUILD)/build/
cp $(SRC)/build/firmware.js $(SRC)/build/firmware.wasm $(SRC)/build/firmware-debug.js $(SRC)/build/firmware-debug.wasm $(SRC)/build/firmware-debug.dwarf.wasm $(SRC)/build/simulator.js $(SRC)/build/audio-worklet.js $(BUILD)/build/

watch: dist
fswatch -o -e src/build src | while read _; do $(MAKE) dist; done
Expand Down
42 changes: 39 additions & 3 deletions e2e/audio.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,18 @@ test("speech.say", async ({ simulator }) => {
expect(stats.rms).toBeGreaterThan(0.3);
});

// Programs rarely set the mode. This one halves the default's 6.7 ms buffers,
// which makes any underrun show up reliably.
test("speech at the highest sample rate has no dropouts", async ({
simulator,
}) => {
const audio = await runToEnd(
simulator,
"import speech\nspeech.say('hello world', mode=3)\n",
);
expect(audio.stats().gaps).toBe(0);
});

test("built-in sound expression", async ({ simulator }) => {
const audio = await runToEnd(
simulator,
Expand Down Expand Up @@ -146,13 +158,37 @@ test("AudioFrame playback", async ({ simulator }) => {
expect(stats.rms).toBeGreaterThan(0.5);
});

// Each ~16 ms chunk is only requested when the previous one ends, so
// underruns leave dozens of short gaps that are heard as buzzing.
test.fail("AudioFrame playback has no dropouts", async ({ simulator }) => {
test("AudioFrame playback has no dropouts", async ({ simulator }) => {
const audio = await runToEnd(simulator, audioFrameProgram);
expect(audio.stats().gaps).toBe(0);
});

// Without a sleep the program never idles, which is where frames are
// otherwise topped up.
test("AudioFrame playback in a busy loop has no dropouts", async ({
simulator,
}) => {
const audio = await runToEnd(
simulator,
audioFrameProgram.replace("audio.play(frames())", "") +
"audio.play(frames(), wait=False)\nwhile audio.is_playing():\n pass\n",
);
const stats = audio.stats();
expectWithin(stats, "soundSeconds", 0.7, 1.5);
expect(stats.gaps).toBe(0);
});

test("AudioFrame sounds played in turn follow on", async ({ simulator }) => {
const audio = await runToEnd(
simulator,
audioFrameProgram + "audio.play(frames())\n",
);
const stats = audio.stats();
// Overlapping would shorten this and clipping the first would leave a gap.
expectWithin(stats, "soundSeconds", 1.55, 2.5);
expect(stats.gaps).toBe(0);
});

test("stopping the program stops the sound", async ({ simulator }) => {
await simulator.run(
"from microbit import *\nimport music\nmusic.pitch(440, wait=False)\nprint('playing')\nwhile True:\n sleep(100)\n",
Expand Down
1 change: 1 addition & 0 deletions src/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ $(BUILD)/micropython.js: $(OBJ) jshal.js simulator-js

simulator-js:
npx esbuild --target=$(ESBUILD_TARGET) '--define:process.env.STAGE="$(STAGE)"' ./simulator.ts --bundle --outfile=$(BUILD)/simulator.js --loader:.svg=text
npx esbuild --target=$(ESBUILD_TARGET) ./board/audio/buffered-audio-worklet.ts --bundle --outfile=$(BUILD)/audio-worklet.js
npx esbuild --target=$(ESBUILD_TARGET) --define:process.env.VERSION="$$(node -e 'process.stdout.write(`"` + require("../package.json").version + `"`)')" ./sw.ts --bundle --outfile=$(BUILD)/sw.js

include $(TOP)/py/mkrules.mk
Expand Down
140 changes: 140 additions & 0 deletions src/board/audio/buffered-audio-worklet.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import { beforeAll, beforeEach, describe, expect, it } from "vitest";
import type {
BufferedAudioRequest,
BufferedAudioResponse,
} from "./buffered-audio-worklet";

interface Processor {
port: { onmessage: (e: { data: BufferedAudioRequest }) => void };
process(inputs: Float32Array[][], outputs: Float32Array[][]): boolean;
}

const contextSampleRate = 40_000;

describe("BufferedAudioProcessor", () => {
let responses: BufferedAudioResponse[];
let registered: any;

beforeAll(async () => {
const scope = globalThis as any;
scope.sampleRate = contextSampleRate;
scope.AudioWorkletProcessor = class {
port = {
postMessage: (response: BufferedAudioResponse) =>
responses.push(response),
};
};
scope.registerProcessor = (_name: string, processor: unknown) => {
registered = processor;
};
await import("./buffered-audio-worklet");
});

beforeEach(() => {
responses = [];
});

const createProcessor = (
startQueuedSeconds = 0,
startDelaySeconds = 0,
): Processor =>
new registered({
processorOptions: { startQueuedSeconds, startDelaySeconds },
});

const send = (processor: Processor, request: BufferedAudioRequest) =>
processor.port.onmessage({ data: request });

const data = (
samples: number[],
sampleRate = contextSampleRate,
generation = 0,
): BufferedAudioRequest => ({
kind: "data",
samples: new Float32Array(samples),
sampleRate,
generation,
});

const render = (processor: Processor, frames: number) => {
const output = new Float32Array(frames);
expect(processor.process([], [[output]])).toBe(true);
return Array.from(output);
};

it("plays buffers in order then silence", () => {
const processor = createProcessor();
send(processor, data([0.25, 0.5]));
send(processor, data([0.75]));
expect(render(processor, 5)).toEqual([0.25, 0.5, 0.75, 0, 0]);
expect(responses).toEqual([{ ended: 2, generation: 0 }]);
});

it("reports buffers as they end", () => {
const processor = createProcessor();
send(processor, data([0.25, 0.5]));
send(processor, data([0.75, 1]));
render(processor, 3);
expect(responses).toEqual([{ ended: 1, generation: 0 }]);
render(processor, 3);
expect(responses).toEqual([
{ ended: 1, generation: 0 },
{ ended: 1, generation: 0 },
]);
});

it("interpolates a lower sample rate across buffers", () => {
const processor = createProcessor();
send(processor, data([0, 0.5], contextSampleRate / 2));
send(processor, data([1, 0], contextSampleRate / 2));
expect(render(processor, 9)).toEqual([0, 0.25, 0.5, 0.75, 1, 0.5, 0, 0, 0]);
});

it("waits for enough to be queued before starting", () => {
const processor = createProcessor(
3 / contextSampleRate,
100 / contextSampleRate,
);
send(processor, data([0.25, 0.5]));
expect(render(processor, 4)).toEqual([0, 0, 0, 0]);
send(processor, data([0.75]));
expect(render(processor, 4)).toEqual([0.25, 0.5, 0.75, 0]);
// Having run out, it waits again.
send(processor, data([1, 1]));
expect(render(processor, 2)).toEqual([0, 0]);
});

it("counts what is queued at the output sample rate", () => {
const processor = createProcessor(
4 / contextSampleRate,
100 / contextSampleRate,
);
send(processor, data([0.5, 1], contextSampleRate / 2));
expect(render(processor, 2)).toEqual([0.5, 0.75]);
});

it("starts after the delay with less queued", () => {
const processor = createProcessor(
3 / contextSampleRate,
2 / contextSampleRate,
);
send(processor, data([0.5]));
expect(render(processor, 4)).toEqual([0, 0, 0.5, 0]);
});

it("discards what is queued on stop", () => {
const processor = createProcessor();
send(processor, data([0.5, 0.5, 0.5]));
render(processor, 1);
send(processor, { kind: "stop" });
send(processor, data([1], contextSampleRate, 1));
expect(render(processor, 3)).toEqual([1, 0, 0]);
expect(responses).toEqual([{ ended: 1, generation: 1 }]);
});

it("finishes when closed", () => {
const processor = createProcessor();
send(processor, { kind: "close" });
expect(processor.process([], [[new Float32Array(1)]])).toBe(false);
});
});
147 changes: 147 additions & 0 deletions src/board/audio/buffered-audio-worklet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/**
* Plays a queue of sample buffers sent from the main thread.
*
* This runs on the audio thread, so the buffers already queued play to the
* sample whatever the main thread is doing. Built as its own script, as that
* is how a worklet is loaded.
*/

// Only import types from this file. Anything else would bundle the processor
// into the importing script.

export interface BufferedAudioProcessorOptions {
/**
* A buffer that arrives when nothing is queued isn't played until this much
* is queued, so that it doesn't run out before the ones after it arrive.
*/
startQueuedSeconds: number;
/** The longest to wait for that. */
startDelaySeconds: number;
}

export type BufferedAudioRequest =
| {
kind: "data";
samples: Float32Array;
sampleRate: number;
generation: number;
}
/** Discard everything queued. */
| { kind: "stop" }
/** Let the processor be collected. */
| { kind: "close" };

/** Sent when buffers finish playing. */
export interface BufferedAudioResponse {
ended: number;
/** From the data requests, so the response can be matched to a stop. */
generation: number;
}

// The worklet global scope isn't in TypeScript's DOM types.
declare const sampleRate: number;
declare class AudioWorkletProcessor {
readonly port: MessagePort;
}
declare function registerProcessor(name: string, processor: unknown): void;

interface QueuedBuffer {
samples: Float32Array;
/** Input samples per output sample. */
step: number;
generation: number;
}

class BufferedAudioProcessor extends AudioWorkletProcessor {
private queue: QueuedBuffer[] = [];
/** Position in the first queued buffer, fractional when resampling. */
private position = 0;
private startQueuedFrames: number;
private startDelayFrames: number;
/** While waiting to start, how much longer to wait at most. */
private delayFrames = 0;
/** While waiting to start, the output frames queued. */
private queuedFrames = 0;
private closed = false;

constructor(options: { processorOptions: BufferedAudioProcessorOptions }) {
super();
const { startQueuedSeconds, startDelaySeconds } = options.processorOptions;
this.startQueuedFrames = startQueuedSeconds * sampleRate;
this.startDelayFrames = Math.round(startDelaySeconds * sampleRate);
this.port.onmessage = (e: MessageEvent<BufferedAudioRequest>) => {
const request = e.data;
switch (request.kind) {
case "data": {
if (this.queue.length === 0) {
this.position = 0;
this.delayFrames = this.startDelayFrames;
this.queuedFrames = 0;
}
const step = request.sampleRate / sampleRate;
this.queuedFrames += request.samples.length / step;
this.queue.push({
samples: request.samples,
step,
generation: request.generation,
});
break;
}
case "stop": {
this.queue.length = 0;
break;
}
case "close": {
this.closed = true;
break;
}
}
};
}

process(_inputs: Float32Array[][], outputs: Float32Array[][]): boolean {
const output = outputs[0][0];
let ended = 0;
let generation = 0;
for (let i = 0; i < output.length; i++) {
if (this.delayFrames > 0) {
if (this.queuedFrames < this.startQueuedFrames) {
this.delayFrames--;
continue;
}
this.delayFrames = 0;
}
let head = this.queue[0];
while (head && this.position >= head.samples.length) {
this.position -= head.samples.length;
generation = head.generation;
ended++;
this.queue.shift();
head = this.queue[0];
}
if (!head) {
break;
}
// Linear interpolation, into the next buffer at the end of this one so
// there's no seam between buffers.
const index = Math.floor(this.position);
const fraction = this.position - index;
const current = head.samples[index];
const next =
index + 1 < head.samples.length
? head.samples[index + 1]
: this.queue[1]
? this.queue[1].samples[0]
: current;
output[i] = current + (next - current) * fraction;
this.position += head.step;
}
if (ended > 0) {
const response: BufferedAudioResponse = { ended, generation };
this.port.postMessage(response);
}
return !this.closed;
}
}

registerProcessor("buffered-audio", BufferedAudioProcessor);
Loading
Loading