"""Render the listening pavilion's two edits with Python 3, using only its standard library.

Run this file in a writable directory. It writes pavilion-15s.wav and pavilion-6s.wav.
"""
from array import array
import math
from pathlib import Path
import sys
import wave

RATE = 32000
BEAT = 60 / 128
TAU = 2 * math.pi
DM, BB, F, A = (50, 57, 65, 69), (46, 53, 62, 65), (53, 57, 60, 64), (45, 55, 61, 64)


def tone(mix, start, length, midi, gain, decay=2.8):
    first = round(start * RATE)
    count = min(round(length * RATE), len(mix) - first)
    frequency = 440 * 2 ** ((midi - 69) / 12)
    for i in range(count):
        t = i / RATE
        envelope = min(1, t / .009, (count - i - 1) / (.025 * RATE)) * math.exp(-decay * t)
        phase = TAU * frequency * t
        mix[first + i] += gain * envelope * (math.sin(phase) + .22 * math.sin(2 * phase))


def render(filename, seconds, chords):
    mix = array("f", [0]) * round(RATE * seconds)
    for bar, chord in enumerate(chords):
        start = 4 * BEAT * bar
        for beat in (0, 2):
            tone(mix, start + beat * BEAT, .40, chord[0] - 12, .21, 4)
        for offbeat in (.5, 1.5, 2.5, 3.5):
            for note in chord[1:]:
                tone(mix, start + offbeat * BEAT, .27, note, .062, 5)
        tone(mix, start, .65, chord[-1] + 12, .12)
    # Both edits land on D. The short edit leaves more room for its final ring.
    landing = (len(chords) * 4 - 1) * BEAT
    tone(mix, landing, seconds - landing, 74, .21, 3)
    pcm = array("h", (round(max(-1, min(1, v)) * 32767) for v in mix))
    if sys.byteorder != "little":
        pcm.byteswap()
    with wave.open(str(filename), "wb") as out:
        out.setparams((1, 2, RATE, 0, "NONE", "not compressed"))
        out.writeframes(pcm.tobytes())


if __name__ == "__main__":
    render(Path("pavilion-15s.wav"), 15, [DM, BB, F, A, DM, BB, A, DM])
    render(Path("pavilion-6s.wav"), 6, [DM, A, DM])
