PL
games/alis / src / Alis / fn / audio.php · commit 9c722cf
<?phpnamespace App\Alis;// Port of alis/src/audio/audio.c (MIT, Olivier Huguenot, Vadim Kindl).// The FLI speech queue of audio.c (fli_audio_queue...) lives in FilmVars (the film player owns it)./** C static inline set_mutaloop() (audio.h). PORT: also grows the music buffers (C: fixed s16[kMuBufLen]). */function set_mutaloop(int $n): void{    Aud::$mutaloop = ult($n, C::kMuBufLen) ? $n : C::kMuBufLen;    if (count(Aud::$muadresse) < Aud::$mutaloop) {        Aud::$muadresse = array_pad(Aud::$muadresse, Aud::$mutaloop, 0);    }    if (count(AudioVars::$muright) < Aud::$mutaloop) {        AudioVars::$muright = array_pad(AudioVars::$muright, Aud::$mutaloop, 0);    }}/** PORT: true while a film plays (C bfilm.playing). */function audio_film_playing(): bool{    return class_exists(FilmVars::class) && isset(FilmVars::$bfilm) && FilmVars::$bfilm->playing;}// v6 (Deus DOS) voice manager// v6 init ALL channels (SFX + music)function v6snd_init(): void{    for ($i = 0; $i < C::V6SND_CHANNELS; $i++) {        $v = AudioVars::$v6voices[$i];        $v->prio = -0x80;        $v->unk06 = 0xffff;        $v->state = 0;    }}function v6snd_alloc(int $slot): int{    $minprio = AudioVars::$v6voices[0]->prio;    $minidx = 0;    for ($i = 0; ;) {        if (AudioVars::$v6voices[$i]->state == 0) {            $idx = $i;            break;        }        if (++$i >= C::V6SND_SFXCHANNELS) {            if ($minprio >= s8(xread8($slot + 0x45))) {                return -1;            }            $idx = $minidx;            break;        }        if ($minprio >= AudioVars::$v6voices[$i]->prio) {            $minprio = AudioVars::$v6voices[$i]->prio;            $minidx = $i;        }    }    $ch = AudioVars::$v6voices[$idx];    $ch->state = 0;    $ch->prio = s8(xread8($slot + 0x45));    $ch->voiceid = xread32($slot + 0x54);    $ch->unk06 = xread16($slot + 0x2a) & 0xffff;    return $idx;}function v6snd_check(int $slot, sV6Voice $ch): void{    xwrite8($slot + 0x23, xread8($slot + 0x23) | 1);    if (xread8($slot + 0x23) & 0x80) {        return;    }    if ($ch->state != 0 && xread32($slot + 0x54) == $ch->voiceid) {        return;    }    xwrite8($slot + 0x23, 2);}function v6snd_trigger(int $slot, sV6Voice $ch): void{    $vol = xread8($slot + 0x47);    $pan = s8(xread8($slot + 0x51));    $ch->lvol = (($vol * (0x80 - $pan)) >> 9) & 0xff;    $ch->rvol = (($vol * (0x80 + $pan)) >> 9) & 0xff;    if (Alis::$platform->uid == C::EGameRobinsonsRequiem3DO) {        $ch->lvol = $ch->rvol = (($vol > 0x7f ? 0x7f : $vol) * 2) & 0xff;  // 3DO: amplitude 0x7fff * vol / 127    }    $freq = xread16($slot + 0x4a) & 0xffff;    $ch->freq = $freq;    $step = (int) floor($freq * 65536.0 / 22050); // (u32)freq << 16: float for 32-bit PHP    $ch->stepfrac = $step & 0xffff; // PORT: C (step & 0xffff) << 16, stored as its high half    $ch->stepint = $step >> 16;    $ch->unk30 = xread16($slot + 0x42) & 0xffff;    $ch->fade36 = 0;    $ch->unk34 = 0;}function v6snd_start(int $slot, sV6Voice $ch): void{    $ch->state = 0;    $p = xread32($slot + 0x3c);    $desc = s32($p + xread32($p));    $data = s32($desc + 0x20);    $ch->sample0 = $data;    $ch->loopstart = $data;    $ch->pos = $data;    $ch->frac = 0;    $end = s32($data + xread32($desc + 0x10));    $ch->end = $end;    $ch->loopend = $end;    $loop = xread16($slot + 0x4c);    $ch->loopcnt = $loop;    if ($loop != -1) {        xwrite16($slot + 0x4c, 0);    }    $ch->type = 1;    $ch->state = 1;}function v6snd_stopslot(int $slot): void{    $chidx = s8(xread8($slot + 0x50));    if ($chidx != -1) {        $ch = AudioVars::$v6voices[$chidx & 0xff] ?? null;        if ($ch !== null && xread32($slot + 0x54) == $ch->voiceid) {            $ch->state = 0;        }    }    xwrite8($slot + 0x50, 0xff);    if (xread16($slot + 0x4c) != -1) {        xwrite16($slot + 0x40, 0);    }}function v6snd_step(int $slot): void{    if (xread8($slot + 0x47) != 0) {        $chidx = s8(xread8($slot + 0x50));        $ch = null;        $needAlloc = true;        if ($chidx != -1) {            $ch = AudioVars::$v6voices[$chidx & 0xff] ?? null;            if ($ch !== null && xread32($slot + 0x54) == $ch->voiceid) {                $needAlloc = false;            }        }        if ($needAlloc) {            if (xread16($slot + 0x4c) == 0) {                v6snd_stopslot($slot);                xwrite8($slot + 0x23, xread8($slot + 0x23) & 0xfd);                return;            }            $a = v6snd_alloc($slot);            if ($a == -1) {                v6snd_stopslot($slot);                xwrite8($slot + 0x23, xread8($slot + 0x23) & 0xfd);                return;            }            xwrite8($slot + 0x50, $a & 0xff);            xwrite8($slot + 0x23, xread8($slot + 0x23) | 0x80);            $ch = AudioVars::$v6voices[$a];        }        v6snd_check($slot, $ch);        if (xread8($slot + 0x23) & 0x81) {            v6snd_trigger($slot, $ch);            xwrite8($slot + 0x23, xread8($slot + 0x23) & 0xfe);        }        if (xread8($slot + 0x23) & 0x80) {            v6snd_start($slot, $ch);            xwrite8($slot + 0x23, xread8($slot + 0x23) & 0x7f);        }        if ((xread8($slot + 0x23) & 0x02) == 0) {            return;        }    }    v6snd_stopslot($slot);    xwrite8($slot + 0x23, xread8($slot + 0x23) & 0xfd);}function v6snd_delsound(int $slot, int $arg): void{    $arg &= 0xffff;    $chidx = s8(xread8($slot + 0x50));    if ($chidx != -1) {        if ($arg == 0) {            v6snd_stopslot($slot);            xwrite8($slot + 0x50, 0xff);        } else {            AudioVars::$v6voices[$chidx & 0xff]->fade36 = $arg;        }    }}function v6snd_stopchan(int $idx): void{    $idx = s16($idx);    if ($idx < 0) {        for ($i = 0; $i < C::V6SND_SFXCHANNELS; $i++) {            AudioVars::$v6voices[$i]->state = 0;        }    } elseif ($idx < C::V6SND_SFXCHANNELS) {        AudioVars::$v6voices[$idx]->state = 0;    }}// 3DO cplaycd: the audio thread (launchme 0xb120) plays a TRACKn AIFF at full volume,// loops times (0 = once, negative = forever) unless stopped.function be32(string $b, int $o): int{    return s32((ord($b[$o]) << 24) | (ord($b[$o + 1]) << 16) | (ord($b[$o + 2]) << 8) | ord($b[$o + 3]));}function cd_load(string $path): int{    if (AudioVars::$cdtrk_pcm !== '' && AudioVars::$cdtrk_name === $path) {        return 1;    }    $f = sys_fopen($path, 'rb');    if (!$f) {        return 0;    }    $b = stream_get_contents($f);    fclose($f);    $n = strlen((string) $b);    if ($b === false || $n < 12 || substr($b, 0, 4) !== 'FORM' || substr($b, 8, 4) !== 'AIFF') {        return 0;    }    $rate = 0;    $frames = 0;    $ok = 0;    $pcm = -1;    for ($o = 12; $o + 8 <= $n;) {        $sz = be32($b, $o + 4);        $c = $o + 8;        $id = substr($b, $o, 4);        if ($id === 'COMM' && $sz >= 18) {            $frames = be32($b, $c + 2);            $ok = ord($b[$c]) == 0 && ord($b[$c + 1]) == 1 && ord($b[$c + 6]) == 0 && ord($b[$c + 7]) == 16;   // mono, 16-bit            $e = ((ord($b[$c + 8]) << 8) | ord($b[$c + 9])) - 16383 - 31;                                       // 80-bit float rate            $rate = $e < 0 ? shr32(be32($b, $c + 10), -$e) : be32($b, $c + 10);        } elseif ($id === 'SSND' && $sz >= 8) {            $pcm = $c + 8 + be32($b, $c);        }        if ($sz < 0) {            break; // PORT: a chunk size >= 2 GB (corrupt file) would loop forever here        }        $o += 8 + (($sz + 1) & ~1);    }    if (!$ok || $pcm < 0 || !$rate || $frames < 0 || $pcm + $frames * 2 > $n) {        return 0;    }    AudioVars::$cdon = 0;    AudioVars::$cdtrk_pcm = substr($b, $pcm, $frames * 2);    AudioVars::$cdtrk_len = $frames;    AudioVars::$cdtrk_rate = $rate;    AudioVars::$cdtrk_name = substr($path, 0, C::kPathMaxLen - 1);    return 1;}function cdtrack_play(string $path, int $loops): void{    $loops = s8($loops);    if (AudioVars::$cdon || !cd_load($path)) {        return;    }    AudioVars::$cdpos = AudioVars::$cdfrac = 0;    AudioVars::$cdloops = $loops ? $loops : 1;    AudioVars::$cdon = 1;}function cdtrack_stop(): void{    AudioVars::$cdon = 0;}// Savestate tail: on flag, repeats left, file name (playback restarts from the top)function cdtrack_save($fp): void{    $name = AudioVars::$cdtrk_name;    $p = strrpos($name, '/');    $nm = substr($p !== false ? substr($name, $p + 1) : $name, 0, 31);    fwrite($fp, chr(AudioVars::$cdon & 0xff));    fwrite($fp, pack('V', AudioVars::$cdloops & 0xffffffff));    fwrite($fp, str_pad($nm, 32, "\0"));}function cdtrack_load($fp): void{    AudioVars::$cdon = 0;    $on = fread($fp, 1);    $l = fread($fp, 4);    $nm = fread($fp, 32);    if ($on === false || strlen($on) != 1 || $l === false || strlen($l) != 4 || $nm === false || strlen($nm) != 32 || !ord($on)) {        return;    }    $l = s32(unpack('V', $l)[1]);    $nm = substr($nm, 0, 31);    $z = strpos($nm, "\0");    if ($z !== false) {        $nm = substr($nm, 0, $z);    }    $path = Alis::$platform->path . $nm;    cdtrack_play($path, $l < 0 ? -1 : s8($l));}/** $buf: interleaved s16 frames (normalised), modified in place. */function cd_render(array &$buf, int $frames, int $channels, int $outrate): void{    $step = s32((int) floor(AudioVars::$cdtrk_rate * 65536.0 / $outrate)); // u64 in the C    $pcm = AudioVars::$cdtrk_pcm;    $len = AudioVars::$cdtrk_len;    $pos = AudioVars::$cdpos;    $frac = AudioVars::$cdfrac;    for ($f = 0; $f < $frames && AudioVars::$cdon; $f++) {        $o = $pos * 2;        $smp = (ord($pcm[$o]) << 8) | ord($pcm[$o + 1]);        if ($smp >= 0x8000) {            $smp -= 0x10000;        }        for ($c = 0; $c < $channels; $c++) {            $v = $buf[$f * $channels + $c] + $smp;            $buf[$f * $channels + $c] = $v < -32768 ? -32768 : ($v > 32767 ? 32767 : $v);        }        $frac += $step;        $pos += $frac >> 16;        $frac &= 0xffff;        if ($pos >= $len) {            $pos = 0;            if (AudioVars::$cdloops > 0 && --AudioVars::$cdloops == 0) {                AudioVars::$cdon = 0;            }        }    }    AudioVars::$cdpos = $pos;    AudioVars::$cdfrac = $frac;}/** $buf: interleaved s16 frames (normalised), modified in place. */function v6snd_render(array &$buf, int $frames, int $channels, int $outrate): void{    if (AudioVars::$cdon) {        cd_render($buf, $frames, $channels, $outrate);    }    if (!Aud::$fsound) {        return;    }    $mem = Alis::$mem;    for ($i = 0; $i < C::V6SND_SFXCHANNELS; $i++) {        $ch = AudioVars::$v6voices[$i];        if ($ch->state == 0 || $ch->type != 1) {            continue;        }        $ch->state = 2;        $step = (int) floor(($ch->freq & 0xffff) * 65536.0 / $outrate); // u32 in the C: float for 32-bit PHP        $stepfrac = $step & 0xffff; // high half of the C u32 stepfrac        $stepint = $step >> 16;        $lvol = $ch->lvol;        $rvol = $ch->rvol;        for ($f = 0; $f < $frames; $f++) {            $smp = ord($mem[$ch->pos] ?? "\x80") - 0x80;            $l = $buf[$f * $channels] + $smp * $lvol;            $buf[$f * $channels] = $l < -32768 ? -32768 : ($l > 32767 ? 32767 : $l);            if ($channels > 1) {                $r = $buf[$f * $channels + 1] + $smp * $rvol;                $buf[$f * $channels + 1] = $r < -32768 ? -32768 : ($r > 32767 ? 32767 : $r);            }            $ch->frac += $stepfrac;            $ch->pos = s32($ch->pos + $stepint + ($ch->frac >> 16));            $ch->frac &= 0xffff;            if (!ult($ch->pos, $ch->end)) {                $ch->loopcnt = s16($ch->loopcnt - 1);                if ($ch->loopcnt == 0) {                    $ch->state = 0;                    break;                }                if ($ch->loopcnt < 0) {                    $ch->loopcnt++;                }                $ch->end = $ch->loopend;                $ch->pos = $ch->loopstart;                $ch->frac = 0;            }        }    }}/** C playsample(type, address, s8 freq, u8 volume, u32 length, u16 loop, s8 priorson). */function playsample(int $type, int $address, int $freq, int $volume, int $length, int $loop, int $priorson, ?int $owner = null): void{    $freq = s8($freq);    $priorson = s8($priorson);    $cson = 127; // CHAR_MAX    $canal = null;    // While a film plays, channel 3 is reserved for FLI speech (SFX would chop it).    $max_chan = audio_film_playing() ? 3 : 4;    for ($i = 0; $i < $max_chan; $i++) {        $ch = Aud::$channels[$i];        // DOS v3 (0x9197): a negative priority reuses the voice with the same priority; a positive one        // only an active voice with the same owner script AND the same priority.        $match = $owner === null || $priorson < 0            ? $priorson == $ch->curson            : ($ch->type != C::eChannelTypeNone && $ch->pere == $owner && $priorson == $ch->curson);        if ($match) {            $canal = $ch;            $cson = $priorson;            break;        }    }    if ($canal === null) {        for ($i = 0; $i < $max_chan; $i++) {            if (Aud::$channels[$i]->curson < $cson) {                $canal = Aud::$channels[$i];                $cson = Aud::$channels[$i]->curson;            }        }    }    if (($priorson >= 0 && $cson < 0 && $cson != -0x80) || $priorson < $cson) {        return;    }    if ($canal === null) {        return; // C: unreachable (cson stays CHAR_MAX: returned above)    }    if ($freq < 0x1 || 0x14 < $freq) {        $freq = 10;    }    $canal->address = $address;    $canal->volume = s16($volume & 0xff);    $canal->length = s32($length);    $canal->freq = s16($freq * 1000);    if ($owner !== null) {        // original: 16-bit counter, decremented at each end; <= 0 never reaches 0 (plays forever)        $l = s16($loop);        $canal->forever = $l <= 0;        $canal->loop = $l <= 0 ? 1 : $l;        $canal->pere = $owner;    } else {        $canal->forever = false;        $canal->loop = $loop & 0xff;    }    $canal->played = 0;    $canal->type = $type;    $canal->curson = $priorson;}/** C runson(type, s8 pereson, s8 priorson, s16 volson, u16 freqson, u16 longson, s16 dvolson, s16 dfreqson). */function runson(int $type, int $pereson, int $priorson, int $volson, int $freqson, int $longson, int $dvolson, int $dfreqson): void{    $pereson = s8($pereson);    $priorson = s8($priorson);    $cson = 127; // CHAR_MAX    $canal = null;    if ($priorson < 0) {        for ($i = 0; $i < 3; $i++) {            if ($priorson == Aud::$channels[$i]->curson) {                $canal = Aud::$channels[$i];                $cson = $priorson;                break;            }        }    } else {        for ($i = 0; $i < 3; $i++) {            if ($pereson == Aud::$channels[$i]->pere && $priorson == Aud::$channels[$i]->curson) {                $canal = Aud::$channels[$i];                $cson = $priorson;                break;            }        }    }    if ($canal === null) {        for ($i = 0; $i < 3; $i++) {            if (Aud::$channels[$i]->curson < $cson) {                $canal = Aud::$channels[$i];                $cson = Aud::$channels[$i]->curson;            }        }    }    if (($priorson >= 0 && $cson < 0 && $cson != -0x80) || $priorson < $cson) {        return;    }    if ($canal === null) {        return;    }    $canal->state = -0x80;    $canal->curson = $priorson;    $canal->type = $type;    $canal->freq = s16($freqson);    $canal->delta_freq = s16($dfreqson);    $canal->volume = s16($volson);    $canal->delta_volume = s16($dvolson);    $canal->length = $longson & 0xffff;    $canal->pere = $pereson;    $canal->state = 2;}function channel_off(int $i): void{    $ch = Aud::$channels[$i];    $ch->type = C::eChannelTypeNone;    $ch->volume = 0;    $ch->freq = 0;    $ch->curson = s8(0x80);    $ch->pere = 0;    $ch->state = 0;    $ch->played = 0;    if ($i < 3) {        io_canal($ch, $i);    }}function offsound(): void{    for ($i = 0; $i < 4; $i++) {        channel_off($i);    }}// VM address after script data moved: >= hi shifts by delta, [lo, hi) was removed (0), below lo stays.function moved(int $a, int $lo, int $hi, int $delta): int{    return ult($a, $lo) ? $a : (ult($a, $hi) ? 0 : s32($a + $delta));}function move_ptr(int &$a, int $lo, int $hi, int $delta): void{    $a = moved($a, $lo, $hi, $delta);}// The original engine leaves audio pointing at the old location after shrinkprog (garbage// sound); our mixers derive read pointers from sample headers, so stale ones crash.function audio_relocate(int $lo, int $hi, int $delta): void{    for ($i = 0; $i < 128; $i++) {        move_ptr(Aud::$tabinst[$i]->address, $lo, $hi, $delta);    }    if (!ult(Aud::$mupnote, $lo) && ult(Aud::$mupnote, $hi)) {        Aud::$muflag = 0;    }    move_ptr(Aud::$mupnote, $lo, $hi, $delta);    if (Alis::$platform->version == 10) {        mv0_relocate($lo, $hi, $delta);    }    $mv1a = MusicV1Vars::$mv1a;    move_ptr($mv1a->noteptr, $lo, $hi, $delta);    for ($i = 0; $i < C::kNumMV1Channels; $i++) {        $ch = $mv1a->channels[$i];        move_ptr($ch->instr, $lo, $hi, $delta);        move_ptr($ch->endsam, $lo, $hi, $delta);        move_ptr($ch->startsam->address, $lo, $hi, $delta);        if ($ch->startsam->address == 0 && $ch->instr == 0) {            $ch->actflag = 0;        }    }    $mv2a = MusicV2Vars::$mv2a;    for ($i = 0; $i < 4; $i++) {        $v = $mv2a->voices[$i];        $sample = $v->sample;        move_ptr($v->sample, $lo, $hi, $delta);        move_ptr($v->startsam1, $lo, $hi, $delta);        move_ptr($v->startsam2, $lo, $hi, $delta);        if ($sample && !$v->sample) {            foreach (get_object_vars($v) as $k => $_) {                $v->$k = 0;            }        }    }    // v6 voices in the freed block stop, moved ones restart as state 1    for ($i = 0; Alis::$platform->version >= 60 && $i < C::V6SND_CHANNELS; $i++) {        $v = AudioVars::$v6voices[$i];        if ($v->state == 0 || ult($v->sample0, $lo)) {            continue;        }        if (ult($v->sample0, $hi)) {            $v->state = 0;            continue;        }        $v->sample0 = s32($v->sample0 + $delta);        $v->loopstart = s32($v->loopstart + $delta);        $v->loopend = s32($v->loopend + $delta);        $v->end = s32($v->end + $delta);        $v->pos = s32($v->pos + $delta);        $v->state = 1;    }    for ($i = 0; $i < 4; $i++) {        $ch = Aud::$channels[$i];        $a = $ch->address;        if ($a < $lo || $a >= Alis::$finmem) {            continue;        }        $at = moved($a, $lo, $hi, $delta);        if ($at) {            $ch->address = $at;        } else {            channel_off($i);        }    }}/** C save_wave_file(): float WAV writer (debugging), $data = PHP floats. */function save_wave_file(string $name, array $data, int $sample_rate, int $channel_count, int $sample_count): int{    $sample_size = 4;    $data_size = $sample_size * $channel_count * $sample_count;    $pad = $data_size & 1;    $header = 'RIFF' . pack('V', 50 + $data_size + $pad) . 'WAVE' . 'fmt ' . pack('V', 18) . pack('v', 3)        . pack('v', $channel_count) . pack('V', $sample_rate) . pack('V', $sample_rate * $sample_size * $channel_count)        . pack('v', $sample_size * $channel_count) . pack('v', 8 * $sample_size) . pack('v', 0)        . 'fact' . pack('V', 4) . pack('V', $channel_count * $sample_count) . 'data' . pack('V', $data_size);    $body = pack('g*', ...array_slice($data, 0, $channel_count * $sample_count));    return file_put_contents($name, $header . $body . ($pad ? "\0" : '')) === false ? 0 : 1;}