100 %) and of a decay over 96 dB, by OPL rate */ private const ATTACK_MS = [INF, 2826, 1413, 706, 353, 176, 88, 44, 22, 11, 5.5, 2.8, 1.4, 0.7, 0.35, 0.01]; private const DECAY_MS = [INF, 39280, 19640, 9820, 4910, 2455, 1227, 614, 307, 153, 77, 38, 19, 9.6, 4.8, 2.4]; /** @var list> GENMIDI instruments: flags, fixed note, voices */ private array $instruments = []; /** @var list the song: [seconds, status & 0xF0, channel, data1, data2] */ private array $events = []; private float $length = 0; private int $next = 0; private float $time = 0; private bool $loop = true; public string $playing = ''; /** DC blocker state (the half / absolute sine waves are not centred) */ private float $dcIn = 0; private float $dcOut = 0; /** @var array */ private array $channels = []; /** @var list> sounding voices */ private array $voices = []; public function __construct(Wad $wad) { if (self::$waves === []) { for ($w = 0; $w < 4; $w++) { $t = []; for ($i = 0; $i < 1024; $i++) { $s = sin($i / 1024 * 2 * M_PI); $t[$i] = match ($w) { 0 => $s, 1 => max(0.0, $s), 2 => abs($s), default => ($i & 256) ? 0.0 : abs($s), // quarter sine pulses }; } self::$waves[$w] = $t; } } if ($wad->has('GENMIDI')) { $this->loadGenmidi($wad->lump('GENMIDI')); } } private function loadGenmidi(string $data): void { $voice = function (string $v): array { $op = fn (int $o) => [ 'char' => ord($v[$o]), 'ad' => ord($v[$o + 1]), 'sr' => ord($v[$o + 2]), 'wave' => ord($v[$o + 3]) & 3, 'level' => ord($v[$o + 5]) & 63, ]; return [ 'mod' => $op(0), 'fb' => ord($v[6]), 'car' => $op(7), 'offset' => unpack('s', substr($v, 14, 2))[1], ]; }; for ($i = 0; $i < 175; $i++) { $o = 8 + $i * 36; if ($o + 36 > strlen($data)) { break; } $flags = unpack('v', $data, $o)[1]; $this->instruments[$i] = [ 'fixed' => (bool) ($flags & 1), 'double' => (bool) ($flags & 4), 'finetune' => ord($data[$o + 2]), 'note' => ord($data[$o + 3]), 'voices' => [$voice(substr($data, $o + 4, 16)), $voice(substr($data, $o + 20, 16))], ]; } } // ================================================================ the song /** Starts a song (a MIDI or MUS lump); an empty string stops the music. */ public function play(string $name, string $lump, bool $loop = true): void { $this->playing = $name; $this->loop = $loop; $this->events = []; $this->voices = []; $this->next = 0; $this->time = 0; $this->length = 0; $this->resetChannels(); if (str_starts_with($lump, 'MThd')) { $this->parseMidi($lump); } elseif (str_starts_with($lump, "MUS\x1A")) { $this->parseMus($lump); } } /** MUS controller number => MIDI controller (0 is the instrument change: a MIDI program change) */ private const MUS_CONTROLLERS = [1 => 0, 2 => 1, 3 => 7, 4 => 10, 5 => 11, 6 => 91, 7 => 93, 8 => 64, 9 => 67]; /** MUS system event => MIDI controller (all sounds off, all notes off, mono, poly, reset all controllers) */ private const MUS_SYSTEM = [10 => 120, 11 => 123, 12 => 126, 13 => 127, 14 => 121]; /** * MUS, the songs' format of DMX (a compact MIDI: 16 channels, the 16th the percussion, 140 ticks a second), turned * into the same events as a MIDI file. The header: "MUS\x1A", the score's length and start, the channels, the * instruments used; then the events: a byte (last | type << 4 | channel), its data, and a delay after a "last" one. */ private function parseMus(string $d): void { $h = unpack('vlen/vstart', $d, 4); $p = $h['start']; $end = min(strlen($d), $h['start'] + $h['len']); $tick = 0; $velocity = array_fill(0, 16, 127); // a note without a volume plays at the channel's last one $byte = static function () use ($d, &$p): int { return ord($d[$p++] ?? "\0"); }; while ($p < $end) { $event = $byte(); $mus = $event & 15; $ch = $mus === 15 ? 9 : ($mus >= 9 ? $mus + 1 : $mus); // MIDI's percussion channel is the 10th $t = $tick / 140.0; switch (($event >> 4) & 7) { case 0: // release a note $this->events[] = [$t, 0x80, $ch, $byte() & 127, 0]; break; case 1: // play a note, with a new volume when its high bit is set $note = $byte(); if ($note & 0x80) { $velocity[$ch] = $byte() & 127; } $this->events[] = [$t, 0x90, $ch, $note & 127, $velocity[$ch]]; break; case 2: // pitch wheel: 0..255, 128 = centre -> MIDI's 14 bits $bend = $byte() << 6; $this->events[] = [$t, 0xE0, $ch, $bend & 127, $bend >> 7]; break; case 3: // system event $ctrl = self::MUS_SYSTEM[$byte()] ?? null; if ($ctrl !== null) { $this->events[] = [$t, 0xB0, $ch, $ctrl, 0]; } break; case 4: // controller $c = $byte(); $v = min(127, $byte()); if ($c === 0) { $this->events[] = [$t, 0xC0, $ch, $v, 0]; } elseif (isset(self::MUS_CONTROLLERS[$c])) { $this->events[] = [$t, 0xB0, $ch, self::MUS_CONTROLLERS[$c], $v]; } break; case 5: // end of a measure break; case 6: // end of the score break 2; default: // unused type: one data byte $p++; } if ($event & 0x80) { $delay = 0; do { $x = $byte(); $delay = ($delay << 7) | ($x & 127); } while (($x & 0x80) && $p < strlen($d)); $tick += $delay; } } $this->length = $tick / 140.0; } public function stop(): void { $this->play('', ''); } private function resetChannels(): void { for ($c = 0; $c < 16; $c++) { $this->channels[$c] = ['program' => 0, 'volume' => 100 / 127, 'expression' => 1.0, 'bend' => 0.0, 'pan' => 64]; } } private static function vlq(string $d, int &$p): int { $v = 0; do { $b = ord($d[$p++] ?? "\0"); $v = ($v << 7) | ($b & 0x7F); } while (($b & 0x80) && $p < strlen($d)); return $v; } /** A standard MIDI file (format 0 or 1): the events of all tracks in time order, in seconds. */ private function parseMidi(string $d): void { $h = unpack('Nlen/nformat/ntracks/ndivision', $d, 4); $division = $h['division'] & 0x7FFF ?: 96; $pos = 8 + $h['len']; $raw = []; // [tick, order, kind, ...] $order = 0; for ($t = 0; $t < $h['tracks'] && $pos + 8 <= strlen($d); $t++) { $len = unpack('N', $d, $pos + 4)[1]; if (substr($d, $pos, 4) !== 'MTrk') { break; } $p = $pos + 8; $end = min(strlen($d), $p + $len); $pos = $p + $len; $tick = 0; $status = 0; while ($p < $end) { $tick += self::vlq($d, $p); $b = ord($d[$p]); if ($b & 0x80) { $status = $b; $p++; } if ($status === 0xFF) { $type = ord($d[$p++]); $l = self::vlq($d, $p); if ($type === 0x51 && $l === 3) { $us = (ord($d[$p]) << 16) | (ord($d[$p + 1]) << 8) | ord($d[$p + 2]); $raw[] = [$tick, $order++, 'tempo', $us]; } elseif ($type === 0x2F) { $raw[] = [$tick, $order++, 'end', 0]; } $p += $l; $status = 0; continue; } if ($status === 0xF0 || $status === 0xF7) { $p += self::vlq($d, $p); $status = 0; continue; } $kind = $status & 0xF0; $a = ord($d[$p++] ?? "\0"); $bb = ($kind === 0xC0 || $kind === 0xD0) ? 0 : ord($d[$p++] ?? "\0"); $raw[] = [$tick, $order++, 'ch', $kind, $status & 15, $a, $bb]; } } usort($raw, fn ($x, $y) => [$x[0], $x[1]] <=> [$y[0], $y[1]]); // ticks -> seconds with the tempo changes $usPerQuarter = 500000; $lastTick = 0; $seconds = 0.0; foreach ($raw as $e) { $seconds += ($e[0] - $lastTick) * $usPerQuarter / 1e6 / $division; $lastTick = $e[0]; if ($e[2] === 'tempo') { $usPerQuarter = $e[3]; } elseif ($e[2] === 'ch') { $this->events[] = [$seconds, $e[3], $e[4], $e[5], $e[6]]; } } $this->length = $seconds; } private function dispatch(int $kind, int $ch, int $a, int $b): void { $c = &$this->channels[$ch]; switch ($kind) { case 0x90: if ($b > 0) { $this->noteOn($ch, $a, $b); break; } // velocity 0: note off case 0x80: foreach ($this->voices as &$v) { if ($v['ch'] === $ch && $v['key'] === $a && $v['stage'] < 3) { $v['stage'] = 3; } } unset($v); break; case 0xB0: if ($a === 7) { $c['volume'] = $b / 127; } elseif ($a === 11) { $c['expression'] = $b / 127; } elseif ($a === 10) { $c['pan'] = $b; } elseif ($a === 120 || $a === 123) { foreach ($this->voices as &$v) { if ($v['ch'] === $ch) { $v['stage'] = 3; } } unset($v); } elseif ($a === 121) { $c['expression'] = 1.0; $c['bend'] = 0.0; } foreach ($this->voices as &$v) { if ($v['ch'] === $ch) { $v['chanAmp'] = $c['volume'] * $c['expression']; } } unset($v); break; case 0xC0: $c['program'] = $a; break; case 0xE0: $c['bend'] = ((($b << 7) | $a) - 8192) / 8192 * 2; // +-2 semitones foreach ($this->voices as &$v) { if ($v['ch'] === $ch) { $this->tune($v); } } unset($v); break; } } private function noteOn(int $ch, int $key, int $velocity): void { if ($ch === self::PERCUSSION) { if ($key < 35 || $key > 81) { return; } $instr = $this->instruments[128 + $key - 35] ?? null; } else { $instr = $this->instruments[$this->channels[$ch]['program']] ?? null; } if ($instr === null) { return; } $count = $instr['double'] ? 2 : 1; for ($i = 0; $i < $count; $i++) { $data = $instr['voices'][$i]; $note = $instr['fixed'] ? $instr['note'] : $key + $data['offset']; $detune = $i === 1 ? ($instr['finetune'] - 128) / 64 : 0.0; $v = [ 'ch' => $ch, 'key' => $key, 'note' => $note + $detune, 'fixed' => $instr['fixed'], 'data' => $data, 'vel' => ($velocity / 127) ** 1.5, 'chanAmp' => $this->channels[$ch]['volume'] * $this->channels[$ch]['expression'], 'stage' => 0, 'menv' => 0.0, 'cenv' => 0.0, 'mstage' => 0, 'cstage' => 0, 'mp' => 0.0, 'cp' => 0.0, 'fb1' => 0.0, 'fb2' => 0.0, 'age' => 0, ]; $this->tune($v); $this->allocate($v); } } /** The phase steps of both operators from the note and the pitch bend. @param array $v */ private function tune(array &$v): void { $bend = $v['fixed'] ? 0.0 : $this->channels[$v['ch']]['bend']; $freq = 440 * 2 ** (($v['note'] + $bend - 69) / 12); $v['minc'] = $freq * self::MULT[$v['data']['mod']['char'] & 15] * 1024 / self::RATE; $v['cinc'] = $freq * self::MULT[$v['data']['car']['char'] & 15] * 1024 / self::RATE; } /** @param array $v */ private function allocate(array $v): void { if (count($this->voices) >= self::MAX_VOICES) { // steal the oldest released voice, else the oldest one $victim = 0; $best = -1; foreach ($this->voices as $i => $o) { $score = $o['age'] + ($o['stage'] === 3 ? 1000000 : 0); if ($score > $best) { $best = $score; $victim = $i; } } array_splice($this->voices, $victim, 1); } $this->voices[] = $v; } // ================================================================ the synthesizer /** One block of envelope for one operator: the amplitude at the end of the block. */ private static function envelope(float $env, int &$stage, array $op, bool $keyOff, int $samples): float { $ar = $op['ad'] >> 4; $dr = $op['ad'] & 15; $sl = $op['sr'] >> 4; $rr = $op['sr'] & 15; $sustain = 10 ** (-($sl === 15 ? 93 : $sl * 3) / 20); if ($keyOff) { $stage = 3; } $perDecay = fn (int $rate): float => is_infinite(self::DECAY_MS[$rate]) ? 1.0 : 10 ** (-96 / 20 * $samples / (self::DECAY_MS[$rate] / 1000 * self::RATE)); switch ($stage) { case 0: // attack $ms = self::ATTACK_MS[$ar]; $env = is_infinite($ms) ? $env : $env + $samples / max(1, $ms / 1000 * self::RATE); if ($env >= 1) { $env = 1.0; $stage = 1; } break; case 1: // decay to the sustain level $env *= $perDecay($dr); if ($env <= $sustain) { $env = $sustain; $stage = 2; } break; case 2: // sustain (held) or a slow fade (percussive sounds) if (!($op['char'] & 0x20)) { $env *= $perDecay($rr); } break; default: // release $env *= $perDecay($rr); } return $env; } /** Signed 16-bit mono samples for $count samples of the song. */ public function render(int $count): string { $mix = array_fill(0, $count, 0.0); if ($this->playing === '' || $this->events === []) { return str_repeat("\0\0", $count); } $waves = self::$waves; for ($start = 0; $start < $count; $start += self::BLOCK) { $n = min(self::BLOCK, $count - $start); // song events up to the end of this block $this->time += $n / self::RATE; while ($this->next < count($this->events) && $this->events[$this->next][0] <= $this->time) { [, $kind, $ch, $a, $b] = $this->events[$this->next++]; $this->dispatch($kind, $ch, $a, $b); } if ($this->next >= count($this->events) && $this->time >= $this->length) { if (!$this->loop) { $this->playing = ''; break; } $this->next = 0; $this->time = 0; $this->voices = []; $this->resetChannels(); } foreach ($this->voices as $vi => &$v) { $data = $v['data']; $mod = $data['mod']; $car = $data['car']; $keyOff = $v['stage'] === 3; $m0 = $v['menv']; $c0 = $v['cenv']; $ms = $v['mstage']; $cs = $v['cstage']; $m1 = self::envelope($m0, $ms, $mod, $keyOff, $n); $c1 = self::envelope($c0, $cs, $car, $keyOff, $n); $v['mstage'] = $ms; $v['cstage'] = $cs; $v['menv'] = $m1; $v['cenv'] = $c1; $v['age'] += $n; $amp = $v['vel'] * $v['chanAmp'] * 0.16; $mLevel = 10 ** (-$mod['level'] * 0.75 / 20); $cLevel = 10 ** (-$car['level'] * 0.75 / 20) * $amp; $additive = (bool) ($data['fb'] & 1); if ($additive) { $mLevel *= $amp; } $fbShift = ($data['fb'] >> 1) & 7; $fbAmount = $fbShift ? 2 ** ($fbShift - 1) * 1024 / 64 : 0.0; $mw = $waves[$mod['wave']]; $cw = $waves[$car['wave']]; $mp = $v['mp']; $cp = $v['cp']; $minc = $v['minc']; $cinc = $v['cinc']; $fb1 = $v['fb1']; $fb2 = $v['fb2']; $ma = $m0 * $mLevel; $mstep = ($m1 - $m0) * $mLevel / $n; $ca = $c0 * $cLevel; $cstep = ($c1 - $c0) * $cLevel / $n; for ($i = 0; $i < $n; $i++) { $mo = $mw[((int) ($mp + ($fb1 + $fb2) * $fbAmount)) & 1023] * $ma; $fb2 = $fb1; $fb1 = $mo; if ($additive) { $out = $mo + $cw[((int) $cp) & 1023] * $ca; } else { $out = $cw[((int) ($cp + $mo * 2048)) & 1023] * $ca; } $mix[$start + $i] += $out; $mp += $minc; $cp += $cinc; $ma += $mstep; $ca += $cstep; } $v['mp'] = fmod($mp, 1024); $v['cp'] = fmod($cp, 1024); $v['fb1'] = $fb1; $v['fb2'] = $fb2; if (($cs === 3 || ($cs === 2 && !($car['char'] & 0x20))) && $c1 < 0.0005) { unset($this->voices[$vi]); // silent: free the voice } } unset($v); $this->voices = array_values($this->voices); } $out = ''; $x1 = $this->dcIn; $y1 = $this->dcOut; foreach ($mix as $x) { $y1 = $x - $x1 + 0.995 * $y1; $x1 = $x; $y = $y1 * self::GAIN; $a = abs($y); if ($a > self::KNEE) { $y = ($y < 0 ? -1 : 1) * (self::KNEE + (1 - self::KNEE) * tanh(($a - self::KNEE) / (1 - self::KNEE))); } $s = (int) ($y * 32767); $out .= pack('v', ($s > 32767 ? 32767 : ($s < -32768 ? -32768 : $s)) & 0xFFFF); } $this->dcIn = $x1; $this->dcOut = $y1; return $out; } }