deck.js (8.1 KB)


  1 const BAR_SECONDS = 0.1;
  2 const SPLICE_SECONDS = 0.005;
  3 // Time constant of a held tape's speed chasing the finger.
  4 const FOLLOW_SECONDS = 0.05;
  5 // Extra acceleration for the part of a speed gap beyond 1, so big gaps close fast.
  6 const FAST_DECAY_SECONDS = 0.35;
  7 // A throttle setting slower than this, as a fraction of normal speed, counts as stopped.
  8 const SLOWEST_THROTTLE = 0.05;
  9 // Volume smoothing, against clicks.
 10 const VOLUME_SECONDS = 0.02;
 11 const RENDERS_PER_REPORT = 3;
 12 // A working microphone is never exactly zero for this long.
 13 const SILENT_SECONDS = 0.5;
 14 
 15 const BAR_SAMPLES = Math.round(sampleRate * BAR_SECONDS);
 16 const FAST_DECAY_RATE = 1 / (FAST_DECAY_SECONDS * sampleRate);
 17 const FOLLOW_SAMPLES = FOLLOW_SECONDS * sampleRate;
 18 const VOLUME_RATE = 1 / (VOLUME_SECONDS * sampleRate);
 19 
 20 class Deck extends AudioWorkletProcessor {
 21 	constructor({processorOptions}) {
 22 		super();
 23 		this.spinUpRate = 1 / (processorOptions.spinUpSeconds * sampleRate);
 24 		this.spinDownSamples = processorOptions.spinDownSeconds * sampleRate;
 25 		this.deleteRate = 1 / (processorOptions.deleteSeconds * sampleRate);
 26 		this.tapes = [];
 27 		this.recording = null;
 28 		this.renders = 0;
 29 		// Samples of exact zeros since the microphone opened; null when not checking.
 30 		this.silence = null;
 31 		this.microphoneGain = 1;
 32 		this.playbackGain = 1;
 33 		this.port.onmessage = ({data}) => {
 34 			const tape = this.tapes[data.id];
 35 			if (data.type === 'record') this.record();
 36 			if (data.type === 'stop') this.stop();
 37 			if (data.type === 'playbackGain') this.playbackGain = data.value;
 38 			if (data.type === 'microphone') {
 39 				this.silence = 0;
 40 				this.microphoneGain = data.gain;
 41 				this.playbackGain = data.playbackGain;
 42 			}
 43 			if (data.type === 'load') this.add(data.samples, data.volume);
 44 			if (data.type === 'play') tape.target = data.speed;
 45 			if (data.type === 'press' || data.type === 'brake') {
 46 				// Stop time is fixed at any speed. A brake after a press keeps the press's rate.
 47 				if (!tape.pressed) tape.stopRate = Math.abs(tape.speed) / this.spinDownSamples;
 48 				tape.pressed = data.type === 'press';
 49 				if (data.type === 'brake') tape.target = 0;
 50 			}
 51 			if (data.type === 'volume') tape.volume = data.value;
 52 			if (data.type === 'grab') {
 53 				tape.held = true;
 54 				tape.pressed = false;
 55 				tape.base = tape.speed;
 56 				tape.direction = null;
 57 				tape.target = tape.speed;
 58 			}
 59 			// A deleted tape fades out first, so that a playing one does not click.
 60 			if (data.type === 'delete') tape.fadeRate = this.deleteRate;
 61 			if (data.type === 'throttle') {
 62 				tape.target = tape.base + data.change;
 63 				this.reportDirection(data.id);
 64 			}
 65 			if (data.type === 'drop') tape.pressed = false;
 66 			if (data.type === 'release') {
 67 				tape.held = false;
 68 				if (Math.abs(tape.target) < SLOWEST_THROTTLE) {
 69 					tape.target = 0;
 70 					tape.speed = 0;
 71 				}
 72 				this.reportDirection(data.id);
 73 			}
 74 		};
 75 	}
 76 
 77 	reportDirection(id) {
 78 		const tape = this.tapes[id];
 79 		const direction = Math.abs(tape.target) < SLOWEST_THROTTLE ? 0 : Math.sign(tape.target);
 80 		if (direction === tape.direction) return;
 81 		tape.direction = direction;
 82 		this.port.postMessage({type: 'direction', id, direction});
 83 	}
 84 
 85 	record() {
 86 		this.recording = {
 87 			blocks: [],
 88 			block: new Float32Array(sampleRate),
 89 			fill: 0,
 90 			peak: 0,
 91 			peakFill: 0,
 92 		};
 93 	}
 94 
 95 	capture(input) {
 96 		const rec = this.recording;
 97 		const gain = this.microphoneGain;
 98 		for (let i = 0; i < input.length; i++) {
 99 			const sample = gain === 1 ? input[i] : Math.tanh(input[i] * gain);
100 			rec.block[rec.fill++] = sample;
101 			if (rec.fill === rec.block.length) {
102 				rec.blocks.push(rec.block);
103 				rec.block = new Float32Array(sampleRate);
104 				rec.fill = 0;
105 			}
106 			rec.peak = Math.max(rec.peak, Math.abs(sample));
107 			if (++rec.peakFill === BAR_SAMPLES) {
108 				this.port.postMessage({type: 'peak', value: rec.peak});
109 				rec.peak = 0;
110 				rec.peakFill = 0;
111 			}
112 		}
113 	}
114 
115 	stop() {
116 		const rec = this.recording;
117 		if (!rec) return;
118 		this.recording = null;
119 
120 		const length = rec.blocks.length * sampleRate + rec.fill;
121 		const splice = Math.round(sampleRate * SPLICE_SECONDS);
122 		if (length < splice * 2) {
123 			this.port.postMessage({type: 'discard'});
124 			return;
125 		}
126 		const samples = new Float32Array(length);
127 		rec.blocks.forEach((block, i) => samples.set(block, i * sampleRate));
128 		samples.set(rec.block.subarray(0, rec.fill), rec.blocks.length * sampleRate);
129 
130 		// Fade both ends so the loop point does not click.
131 		for (let i = 0; i < splice; i++) {
132 			samples[i] *= i / splice;
133 			samples[length - 1 - i] *= i / splice;
134 		}
135 
136 		// The last bar is shorter than the others unless the take ends on a bar boundary.
137 		const peaks = new Float32Array(Math.ceil(length / BAR_SAMPLES));
138 		for (let i = 0; i < length; i++) {
139 			const bar = Math.floor(i / BAR_SAMPLES);
140 			peaks[bar] = Math.max(peaks[bar], Math.abs(samples[i]));
141 		}
142 
143 		this.add(samples, 1);
144 		this.port.postMessage({type: 'tape', peaks, length: length / BAR_SAMPLES, samples});
145 	}
146 
147 	add(samples, volume) {
148 		this.tapes.push({
149 			samples,
150 			position: 0,
151 			reported: 0,
152 			// Samples per output sample; negative is backwards.
153 			speed: 0,
154 			// Speed a free tape eases towards.
155 			target: 0,
156 			held: false,
157 			// A resting finger brakes the tape towards zero.
158 			pressed: false,
159 			// Speed lost per sample while stopping.
160 			stopRate: 0,
161 			// Speed when a throttle drag began.
162 			base: 0,
163 			// Last direction reported to the main thread during this throttle drag.
164 			direction: null,
165 			volume,
166 			// Smoothed `volume`.
167 			gain: volume,
168 			// Falls from 1 to 0 at `fadeRate` per sample once the tape is deleted.
169 			fade: 1,
170 			fadeRate: 0,
171 		});
172 	}
173 
174 	process(inputs, outputs) {
175 		const input = inputs[0][0];
176 		const output = outputs[0][0];
177 		if (this.recording && input) this.capture(input);
178 		if (this.silence !== null && input) {
179 			if (input.some(sample => sample !== 0)) {
180 				this.silence = null;
181 			} else if ((this.silence += input.length) >= SILENT_SECONDS * sampleRate) {
182 				this.silence = null;
183 				this.port.postMessage({type: 'silent'});
184 			}
185 		}
186 
187 		for (const [id, tape] of this.tapes.entries()) {
188 			if (!tape) continue;
189 			const goal = tape.pressed ? 0 : tape.target;
190 			// Nulled, not spliced, so the other ids stay valid.
191 			if (tape.fade === 0 || (tape.fadeRate && tape.speed === 0)) {
192 				this.tapes[id] = null;
193 				continue;
194 			}
195 			if (tape.speed === 0 && goal === 0) {
196 				tape.gain = tape.volume;
197 				continue;
198 			}
199 			const {samples} = tape;
200 			const length = samples.length;
201 			for (let i = 0; i < output.length; i++) {
202 				if (tape.held) {
203 					tape.speed += (tape.target - tape.speed) / FOLLOW_SAMPLES;
204 				} else if (tape.speed !== goal) {
205 					const gap = goal - tape.speed;
206 					const distance = Math.abs(gap);
207 					const change = goal
208 						? this.spinUpRate + Math.max(0, distance - 1) * FAST_DECAY_RATE
209 						: tape.stopRate;
210 					tape.speed += Math.sign(gap) * Math.min(distance, change);
211 				}
212 				tape.gain += (tape.volume - tape.gain) * VOLUME_RATE;
213 				tape.fade = Math.max(0, tape.fade - tape.fadeRate);
214 				const index = Math.floor(tape.position);
215 				const fraction = tape.position - index;
216 				const a = samples[index];
217 				const b = samples[index + 1 === length ? 0 : index + 1];
218 				// Level follows speed up to 1, like a real playback head.
219 				output[i] += (a + (b - a) * fraction) * Math.min(1, Math.abs(tape.speed)) * tape.gain * tape.fade;
220 				tape.position += tape.speed;
221 				if (tape.position < 0 || tape.position >= length) {
222 					tape.position = (tape.position % length + length) % length;
223 					// Rounding can land a tiny negative position exactly on `length`.
224 					if (tape.position >= length) tape.position = 0;
225 				}
226 			}
227 			if (tape.held && tape.target === 0 && Math.abs(tape.speed) < 1e-4) tape.speed = 0;
228 		}
229 
230 		// Soft-clip the raised mix, as in capture().
231 		if (this.playbackGain !== 1) {
232 			for (let i = 0; i < output.length; i++) {
233 				output[i] = Math.tanh(output[i] * this.playbackGain);
234 			}
235 		}
236 
237 		const moved = tape => tape && tape.position !== tape.reported;
238 		if (++this.renders % RENDERS_PER_REPORT === 0 && this.tapes.some(moved)) {
239 			this.port.postMessage({
240 				type: 'positions',
241 				positions: this.tapes.map(tape => tape && (tape.reported = tape.position) / BAR_SAMPLES),
242 			});
243 		}
244 		return true;
245 	}
246 }
247 
248 registerProcessor('deck', Deck);