"""A tiny offline copy of the WebAudio synth used by the theme mockup. Two building blocks, `tone` and `noise`, write into a shared `Mix` buffer. They follow the WebAudio rules the mockup relies on: - gain envelopes ramp exponentially from 0.0001 up to `gain` and back down; - frequency glides ramp exponentially; - BiquadFilter coefficients follow the Web Audio spec (lowpass and highpass read Q in decibels, bandpass reads Q as a plain ratio). """ import math import numpy SAMPLE_RATE = 44100 ENVELOPE_FLOOR = 0.0001 TAIL_SECONDS = 0.05 # the mockup stops each source 50 ms after its envelope ends class Mix: """A mono float buffer that grows as sounds are added.""" def __init__(self, seed): self.samples = numpy.zeros(0) self.random = numpy.random.default_rng(seed) def add(self, start_seconds, signal): start_index = int(round(start_seconds * SAMPLE_RATE)) end_index = start_index + len(signal) if end_index > len(self.samples): grown = numpy.zeros(end_index) grown[: len(self.samples)] = self.samples self.samples = grown self.samples[start_index:end_index] += signal def _time_axis(duration): sample_count = int(math.ceil((duration + TAIL_SECONDS) * SAMPLE_RATE)) return numpy.arange(sample_count) / SAMPLE_RATE def exponential_ramp(times, start_value, end_value, ramp_seconds): """Value of an exponential ramp that starts at time 0 and then holds.""" progress = numpy.clip(times / ramp_seconds, 0.0, 1.0) return start_value * (end_value / start_value) ** progress def envelope(times, gain, attack, duration): """Exponential rise to `gain` over `attack`, then fall to the floor at `duration`.""" rising = exponential_ramp(times, ENVELOPE_FLOOR, gain, attack) falling = exponential_ramp(times - attack, gain, ENVELOPE_FLOOR, duration - attack) return numpy.where(times < attack, rising, falling) def _poly_blep(phase, phase_step): """Smooths the jump in a saw or square wave to cut aliasing.""" correction = numpy.zeros_like(phase) just_after = phase < phase_step ratio = phase[just_after] / phase_step[just_after] correction[just_after] = ratio + ratio - ratio * ratio - 1.0 just_before = phase > 1.0 - phase_step ratio = (phase[just_before] - 1.0) / phase_step[just_before] correction[just_before] = ratio * ratio + ratio + ratio + 1.0 return correction def oscillator(wave_type, frequencies): """One sample per entry in `frequencies` (Hz), starting at phase 0.""" phase_step = frequencies / SAMPLE_RATE phase = numpy.concatenate(([0.0], numpy.cumsum(phase_step)[:-1])) % 1.0 if wave_type == "sine": return numpy.sin(2.0 * math.pi * phase) if wave_type == "triangle": return 1.0 - 4.0 * numpy.abs(((phase + 0.25) % 1.0) - 0.5) if wave_type == "sawtooth": return 2.0 * phase - 1.0 - _poly_blep(phase, phase_step) if wave_type == "square": square = numpy.where(phase < 0.5, 1.0, -1.0) square = square + _poly_blep(phase, phase_step) return square - _poly_blep((phase + 0.5) % 1.0, phase_step) raise ValueError("unknown wave type: " + wave_type) def biquad(signal, filter_type, cutoffs, quality): """Run `signal` through a Web Audio style biquad. `cutoffs` is per sample.""" angular = 2.0 * math.pi * numpy.minimum(cutoffs, SAMPLE_RATE * 0.49) / SAMPLE_RATE cosine = numpy.cos(angular) sine = numpy.sin(angular) if filter_type == "bandpass": alpha = sine / (2.0 * quality) feed = [alpha, numpy.zeros_like(alpha), -alpha] else: alpha = sine / 2.0 * 10.0 ** (-quality / 20.0) if filter_type == "lowpass": edge = (1.0 - cosine) / 2.0 feed = [edge, 1.0 - cosine, edge] elif filter_type == "highpass": edge = (1.0 + cosine) / 2.0 feed = [edge, -(1.0 + cosine), edge] else: raise ValueError("unknown filter type: " + filter_type) norm = 1.0 + alpha feed_now, feed_one, feed_two = [(part / norm).tolist() for part in feed] back_one = (-2.0 * cosine / norm).tolist() back_two = ((1.0 - alpha) / norm).tolist() output = [0.0] * len(signal) input_one = input_two = output_one = output_two = 0.0 for i, sample in enumerate(signal.tolist()): result = (feed_now[i] * sample + feed_one[i] * input_one + feed_two[i] * input_two - back_one[i] * output_one - back_two[i] * output_two) input_two, input_one = input_one, sample output_two, output_one = output_one, result output[i] = result return numpy.array(output) def tone(mix, start, freq, duration, wave_type="sine", freq_end=None, glide=None, detune_cents=0.0, lowpass=None, gain=0.12, attack=0.005): """Port of the mockup's `tone(at, f, dur, o)`.""" times = _time_axis(duration) if freq_end: frequencies = exponential_ramp(times, freq, freq_end, glide or duration) else: frequencies = numpy.full_like(times, freq) frequencies = frequencies * 2.0 ** (detune_cents / 1200.0) signal = oscillator(wave_type, frequencies) if lowpass: signal = biquad(signal, "lowpass", numpy.full_like(times, lowpass), 1.0) mix.add(start, signal * envelope(times, gain, attack, duration)) def noise(mix, start, duration, filter_type="bandpass", freq=1000.0, freq_end=None, quality=1.0, gain=0.25, attack=0.003): """Port of the mockup's `noise(at, dur, o)`: filtered white noise.""" times = _time_axis(duration) white = mix.random.uniform(-1.0, 1.0, len(times)) if freq_end: cutoffs = exponential_ramp(times, freq, freq_end, duration) else: cutoffs = numpy.full_like(times, freq) signal = biquad(white, filter_type, cutoffs, quality) mix.add(start, signal * envelope(times, gain, attack, duration)) def arpeggio(mix, start, notes, step, duration, **tone_options): """Port of the mockup's `arp`: one tone per note, `step` seconds apart.""" for i, freq in enumerate(notes): tone(mix, start + i * step, freq, duration, **tone_options)