Skip to content

Commit 5a3a7dd

Browse files
committed
Allow for growing heap from the audio thread
1 parent 03bb4a6 commit 5a3a7dd

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

test/webaudio/audioworklet_grow_heap.c

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,19 +53,29 @@ bool process(int numInputs, const AudioSampleFrame* inputs, int numOutputs, Audi
5353
return true;
5454
}
5555

56+
void doGrow() {
57+
size_t max = emscripten_get_heap_max();
58+
size_t preGrow = emscripten_get_heap_size();
59+
// Note we're leaking this on purpose
60+
if (!malloc((preGrow / 3) * 2)) {
61+
emscripten_out("Failed to malloc()");
62+
}
63+
emscripten_outf("Heap was %zu, now %zu (of %zu)", preGrow, emscripten_get_heap_size(), max);
64+
}
65+
5666
// Registered keypress event to grow the heap by 2/3
5767
bool onPress(int type, const EmscriptenKeyboardEvent* e, void* data) {
5868
if (!e->repeat) {
59-
size_t max = emscripten_get_heap_max();
6069
size_t size = emscripten_get_heap_size();
61-
if (max == size) {
70+
if (emscripten_get_heap_max() == size) {
6271
emscripten_outf("Cannot grow heap, rebuild with ALLOW_MEMORY_GROWTH? Heap is already %zu", size);
6372
} else {
64-
// Note we're leaking this on purpose
65-
if (!malloc((size / 3) * 2)) {
66-
emscripten_out("Failed to malloc()");
73+
if (e->charCode == 32) {
74+
emscripten_out("Growing from audio worklet (see Console)");
75+
emscripten_audio_worklet_post_function_v(VOIDP_2_WA(data), &doGrow);
76+
} else {
77+
doGrow();
6778
}
68-
emscripten_outf("Heap was %zu, now %zu (of %zu)", size, emscripten_get_heap_size(), max);
6979
}
7080
}
7181
return false;
@@ -76,7 +86,7 @@ void processorCreated(EMSCRIPTEN_WEBAUDIO_T context, bool success, void* data) {
7686
assert(success && "Audio worklet failed in processorCreated()");
7787
emscripten_out("Audio worklet processor created");
7888
emscripten_out("Click to toggle audio playback");
79-
emscripten_out("Keypress to grow the heap");
89+
emscripten_out("Keypress to grow the heap, [space] to grow from the audio worklet's thread");
8090

8191
// Stereo output, two inputs
8292
int outputChannelCounts[1] = { 2 };
@@ -102,7 +112,7 @@ void processorCreated(EMSCRIPTEN_WEBAUDIO_T context, bool success, void* data) {
102112
// Register a click to start playback
103113
emscripten_set_click_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, WA_2_VOIDP(context), false, &onClick);
104114
// And a keypress to alloc (and leak) to grow the heap
105-
emscripten_set_keypress_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, NULL, false, &onPress);
115+
emscripten_set_keypress_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, WA_2_VOIDP(context), false, &onPress);
106116

107117
#ifdef TEST_AND_EXIT
108118
// Register the counter that exits the test after one second of mixing

0 commit comments

Comments
 (0)