Skip to content

scrapjs/gain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Apr 11, 2022
08c0e74 Â· Apr 11, 2022

History

70 Commits
Sep 3, 2016
Oct 17, 2015
Feb 23, 2022
Apr 11, 2022
Feb 23, 2022
Sep 3, 2016
Apr 11, 2022
Feb 23, 2022

Repository files navigation

@audio/gain test npm version

Audio gain DSP module

Amplify input values.

Usage

npm install @audio/gain

./gain.js

import gain from '@audio/gain';

// mono, k-param gain
[output] = gain([[0.1,0.2,...inputValues]], .75);

// stereo, a-param gain
[outputLeft, outputRight] = gain([[0.1,...leftInput], [-0.1,...rightInput]], [.5,.6,...gainValues]);

// multichannel, a-param gain
outputChannels = gain([...inputChannels], gainValues);

./gain.wasm

Raw WASM function requires a bit of memory management.

const memory = new WebAssembly.Memory({initial:1, maximum: 8}) // can be shared

WebAssembly.instantiateStreaming(fetch('./gain.wasm'), { init: { memory } })
.then(({ instance }) => {
	const { gain, block, blockSize } = instance.exports

	const data = new Float64Array(memory.buffer) // memory view
	const inPtr = block(2), gainPtr = block(1) // allocate batch slots for audio buffers

	// sample processing loop
	const processGain = (input, output, param) => {
		// adjust processing block size
		blockSize.value = input[0].length, outPtr

		// write input to memory
		data.set(input[0], inPtr), data.set(input[1], inPtr+blockSize)

		// process a-rate (accurate) gain values
		if (param.gain.length > 1) {
			data.set(param.gain, gainPtr)
			outPtr = gain(inPtr, gainPtr)
		}
		// process k-rate (controlling) gain values
		else {
			outPtr = gain(inPtr, param.gain[0])
		}

		// write output from memory
		output[0].set(data.subarray(outPtr, blockSize))
		output[1].set(data.subarray(outPtr+blockSize, blockSize))
	}
});

This is illustrative flow, can be enhanced to use multiple channels, shared memory etc.

./gain.son

Can be used in sonr as:

# './gain.son': gain;

gain(mySource, 0.45);	// direct fn
mySource | gain(0.45); // pipe style

🕉