<?phpnamespace App\Alis;// Port of alis/src/video/video.c (MIT, Olivier Huguenot, Vadim Kindl).// Film players: FLI/FLC (fli.php), FLS (fls.php), 3DO cinepak (film3do.php, cinepak.php).//// PORT (blocking): runfilm() loops in the C until the film (or the batch of frames) ends, while the SDL// thread shows image.physic. Here it is resumable: after each film frame it renders the screen (sys_render)// and restarts the crunfilm opcode at the next VM frame (vm_yield_retry); the pacing waits (timeclock or// the queued speech duration) become "yield until the time has come". FilmVars::$run_* keep the loop state.// ---------------------------------------------------------------------------------------------// Port helpers: film data reads (FilmVars::$data), boot check, host block// ---------------------------------------------------------------------------------------------function film_rd16le(int $o): int{ $d = FilmVars::$data; return ord($d[$o]) | (ord($d[$o + 1]) << 8);}function film_rd32le(int $o): int{ $d = FilmVars::$data; return s32(ord($d[$o]) | (ord($d[$o + 1]) << 8) | (ord($d[$o + 2]) << 16) | (ord($d[$o + 3]) << 24));}function film_rd16be(int $o): int{ $d = FilmVars::$data; return (ord($d[$o]) << 8) | ord($d[$o + 1]);}function film_rd32be(int $o): int{ $d = FilmVars::$data; return s32((ord($d[$o]) << 24) | (ord($d[$o + 1]) << 16) | (ord($d[$o + 2]) << 8) | ord($d[$o + 3]));}/** C read16(ptr) on film bytes: game byte order, u16. */function film_rd16(int $o): int{ return Alis::$xle ? film_rd16le($o) : film_rd16be($o);}/** C read32(ptr) on film bytes: game byte order, s32 bits. */function film_rd32(int $o): int{ return Alis::$xle ? film_rd32le($o) : film_rd32be($o);}/** Sets the film bytes (adds the zero padding). */function film_set_data(string $bytes): void{ FilmVars::$data = $bytes . str_repeat("\0", FilmConst::kFilmPad);}/** Length of the film bytes without the padding. */function film_data_len(): int{ return \max(0, strlen(FilmVars::$data) - FilmConst::kFilmPad);}/** * PORT: bfilm and the host blocks of FilmVars belong to one boot of the VM. Machine::boot() makes a new * SysVars::$mouse (SysVars::init); a state load does not: a new mouse object means another game was started. */function film_check_boot(): void{ static $owner = null; if (!isset(SysVars::$mouse)) { return; } if ($owner !== SysVars::$mouse) { $owner = SysVars::$mouse; if (FilmVars::$bfilm->sfp !== null) { @fclose(FilmVars::$bfilm->sfp); } FilmVars::init(); FilmVars::$endframe = null; FilmVars::$pvgalogic = null; FilmVars::$vgalogic = FilmVars::$vgalogic_df = null; FilmVars::$vgalogic_sz = 0; FilmVars::$g_s512_ending = 0; FilmVars::$fls_drawing = FilmVars::$fls_pallines = FilmVars::$fls_state = 0; FilmVars::$fli_audio_q_head = FilmVars::$fli_audio_q_tail = 0; FilmVars::$fli_audio_copybuf = 0; FilmVars::$scratch = FilmVars::$scratch_sz = 0; FilmVars::$data = ''; FilmVars::$src = null; FilmVars::$rows = []; FilmVars::$run_active = false; FilmVars::$f3 = null; FilmVars::$f3_bmp = null; }}/** * audio.channels[3] (the FLI speech channel). * PORT: alis_init() skips Aud::init() when Aud::$working is set (it always is: default 0), so Aud::$channels may * be empty: the missing channel is created here. */function film_channel3(): sChannel{ if (!isset(Aud::$channels[3])) { Aud::$channels[3] = new sChannel(); } return Aud::$channels[3];}/** memset(&bfilm, 0, sizeof(bfilm)) */function film_reset(): void{ FilmVars::$bfilm = new sFLICData(); FilmVars::$run_active = false; FilmVars::$run_pending = false;}/** * Copies $n bytes of a PHP string into Alis::$mem at $dst in place (byte loop: substr_replace would copy the * whole VM memory; used for the small FLI speech / palette chunks). */function film_mem_poke(int $dst, string $bytes, int $n): void{ if ($n >= 0x4000) { mem_write($dst, substr($bytes, 0, $n)); return; } for ($i = 0; $i < $n; $i++) { Alis::$mem[$dst + $i] = $bytes[$i]; }}/** A host block of Alis::$mem for the film chunks that C code reads from memory (dos_film_palette). */function film_scratch(int $size): int{ if (FilmVars::$scratch == 0 || FilmVars::$scratch_sz < $size) { FilmVars::$scratch_sz = \max($size, 0x1000); FilmVars::$scratch = host_alloc(FilmVars::$scratch_sz); } return FilmVars::$scratch;}/** * PORT: cfilm plays a film resource of the VM memory: its bytes are copied into FilmVars::$data (from a 16-byte * aligned address so that the parity tests of flstofen stay the same). Returns the offset of $addr in $data. */function film_use_mem(int $addr): int{ $memlen = strlen(Alis::$mem); if ($addr < 0 || $addr >= $memlen) { film_set_data(''); FilmVars::$src = null; return 0; } $kind = Alis::$platform->kind; $len = ($kind == C::EPlatformAtari || $kind == C::EPlatformAmiga) ? read32($addr) : read32le($addr); if ($len <= 0 || $addr + $len > $memlen) { $end = \min(Alis::$platform->ram_sz, $memlen); $len = ($end > $addr ? $end : $memlen) - $addr; } $base = $addr & ~15; $n = $addr - $base + $len; film_set_data(substr(Alis::$mem, $base, $n)); FilmVars::$src = ['mem', $base, $n]; return $addr - $base;}// ---------------------------------------------------------------------------------------------// video.c// ---------------------------------------------------------------------------------------------function vgalogic_alloc(): int{ if (FilmVars::$pvgalogic === null) { FilmVars::$pvgalogic = str_repeat("\0", FilmConst::kVgaLogicSize); } if (FilmVars::$vgalogic_sz < FilmConst::kVgaLogicSize) { FilmVars::$vgalogic_sz = FilmConst::kVgaLogicSize; } FilmVars::$vgalogic = 0x40; FilmVars::$vgalogic_df = 0xdf00 + 319; return 1;}function vgalogic_fit(int $need): int{ if (FilmVars::$pvgalogic === null || $need <= FilmVars::$vgalogic_sz) { return FilmVars::$pvgalogic !== null ? 1 : 0; } if (FilmVars::$vgalogic_borrowed) { return 0; } // calloc + memcpy of the old contents (the offsets stay the same) FilmVars::$pvgalogic = substr(FilmVars::$pvgalogic, 0, FilmVars::$vgalogic_sz) . str_repeat("\0", $need - FilmVars::$vgalogic_sz); FilmVars::$vgalogic_sz = $need; return 1;}function vgalogic_free(): void{ FilmVars::$vgalogic_borrowed = 0; FilmVars::$pvgalogic = null; FilmVars::$vgalogic = FilmVars::$vgalogic_df = null; FilmVars::$vgalogic_sz = 0;}function endfilm(): void{ if (Trace::on()) { Trace::event('endfilm'); } flstofen(-1); FilmVars::$bfilm->type = FilmConst::eAlisVideoNone; ImageVars::$v6xdirty = 1;}function inifilm(): void{ // PORT: the film's picture box, and the game's palette for the entries the film does not use (fn/fli.php fli_next()) FilmVars::$palUsed = []; FilmVars::$gamePal = Img::$mpalet; FilmVars::$gameDpal = dos_pal_family() == ImageConst::DPAL_B32 ? ImageVars::$dpal_mpal : []; FilmVars::$box = null; if (Trace::on()) { Trace::event('inifilm'); } $bf = FilmVars::$bfilm; $bf->playing = 0; if (!vgalogic_alloc()) { $bf->type = FilmConst::eAlisVideoNone; return; } // Free channel 3 (a game sound may hold it; the queue only primes when idle) and // reset the queue. type = None first so the mixer skips it meanwhile. $ch = film_channel3(); $ch->type = C::eChannelTypeNone; $ch->curson = s8(0x80); FilmVars::$fli_audio_q_head = 0; FilmVars::$fli_audio_q_tail = 0; FilmVars::$g_s512_ending = 0; // fresh film: cancel any pending end-flush from a previous one switch (Alis::$platform->kind) { case C::EPlatformAtari: $bf->type = FilmConst::eAlisVideoS512; break; case C::EPlatformAmiga: $bf->type = FilmConst::eAlisVideoHAM6; break; default: $bf->type = FilmConst::eAlisVideoFLIC; break; } if (Alis::$platform->kind == C::EPlatformAtari || Alis::$platform->kind == C::EPlatformAmiga) { flstofen(0); } else { flitofen(); // reads the FLC header (0xAF11) -> bfilm.width/height set }}/** PORT: is crunfilm resuming the film loop it started (same script, same opcode)? Drops a stale loop. */function film_run_resuming(): bool{ if (FilmVars::$run_active && FilmVars::$run_script === Alis::$script && FilmVars::$run_pc == Alis::$opcode_pc) { return true; } FilmVars::$run_active = false; return false;}/** PORT: shows the film frame now (the C SDL thread shows image.physic / the film buffer by itself). */function film_show(): void{ sys_render(Host::$pixelbuf);}/** * PORT: ends the VM frame here; crunfilm restarts at the next one and resumes the loop. The frame decoded last * is rendered first (when crunfilm returns without yielding, the end of the VM cycle renders it). */function film_yield(): void{ if (!FilmVars::$run_yielded) { FilmVars::$run_yielded = true; film_show(); } FilmVars::$run_script = Alis::$script; FilmVars::$run_pc = Alis::$opcode_pc; vm_yield_retry();}/** PORT: is the time of the film frame decoded last still to come (the wait of runfilm)? */function film_run_waiting(): bool{ if (FilmVars::$run_wait == 1) { return ult(s32(sys_ticks() - FilmVars::$fli_pace_anchor), FilmVars::$fli_pace_total_ms); } if (FilmVars::$run_wait == 2) { return ult(Alis::$timeclock, s32(FilmVars::$run_index + FilmVars::$run_prevclock)); } return false;}/** * PORT: the C waits after each frame, before crunfilm returns. Here, when crunfilm returns after its batch of * frames (the scripts play films one frame per VM cycle), that wait is done at the start of the next runfilm * call instead (FilmVars::$run_pending): the VM cycle ends at once and the frame interval is not rounded up to * two VM frames. Between the frames of one call and after the last frame of the film the wait stays where the * C does it. */function runfilm(): void{ $bf = FilmVars::$bfilm; $kind = Alis::$platform->kind; $fls = $kind == C::EPlatformAtari || $kind == C::EPlatformAmiga; if (!FilmVars::$run_active) { FilmVars::$run_active = true; FilmVars::$run_setup = false; FilmVars::$run_phase = FilmVars::$run_pending ? 3 : 0; FilmVars::$run_yielded = true; // the frame on screen is already shown } if (FilmVars::$run_phase == 3) { // the wait of the previous call's last frame if (film_run_waiting()) { film_yield(); } FilmVars::$run_pending = false; FilmVars::$run_phase = 0; } if (!FilmVars::$run_setup) { FilmVars::$run_setup = true; $basemain = $bf->basemain; Img::$fenx1 = s16(read16le($basemain + 0xe)); Img::$fenx2 = s16(read16le($basemain + 0x12) + Img::$fenx1); Img::$clipl = s16(read16le($basemain + 0x12) + 1); Img::$feny1 = s16(read16le($basemain + 0x10)); Img::$feny2 = s16(read16le($basemain + 0x14) + Img::$feny1); Img::$cliph = s16(read16le($basemain + 0x14) + 1); Img::$wloglarg = Img::$loglarg; Img::$wlogx1 = 0; Img::$wlogy1 = 0; Img::$clipx1 = Img::$fenx1; Img::$clipy1 = Img::$feny1; Img::$clipx2 = Img::$fenx2; Img::$clipy2 = Img::$feny2; // Reset wall-clock pacing state so this cutscene anchors fresh // (lazy: actual anchor sets on first audio chunk). FilmVars::$fli_pace_anchor = 0; FilmVars::$fli_pace_total_ms = 0; $bf->playing = 1; } $qmask = C::FLI_AUDIO_QUEUE_SIZE - 1; while (true) { if (FilmVars::$run_phase == 0) { $prevclock = Alis::$timeclock; $q_head_before = FilmVars::$fli_audio_q_head; $result = $fls ? flstofen(0) : flitofen(); if (Trace::on()) { Trace::event('film frame ' . $result); } // Did flstofen/flitofen enqueue audio chunk(s) for this frame? $chunks_enqueued = (FilmVars::$fli_audio_q_head - $q_head_before) & $qmask; FilmVars::$run_wait = 0; if (0 < $bf->waitclock) { // Audio frames: pace by chunk duration (wall clock). Silent frames: timeclock. if ($chunks_enqueued) { // Anchor on the first chunk; accumulate each chunk's duration. if (FilmVars::$fli_pace_anchor == 0) { FilmVars::$fli_pace_anchor = sys_ticks(); FilmVars::$fli_pace_total_ms = 0; } for ($k = 0; $k < $chunks_enqueued; $k++) { $idx = ($q_head_before + $k) & $qmask; $cf = FilmVars::$fli_audio_queue[$idx]['freq']; $cl = FilmVars::$fli_audio_queue[$idx]['length']; if ($cf > 0) { FilmVars::$fli_pace_total_ms = s32(FilmVars::$fli_pace_total_ms + intdiv($cl * 1000, $cf)); } } FilmVars::$run_wait = 1; } else { // Interval = waitclock / file-format tick rate (FLI 60 Hz, FLS 50 Hz). $thz = SysVars::$sys_timeclock_hz ?: 50; $src = $fls ? 50 : 60; $index = s16(intdiv(($bf->waitclock & 0xffff) * $thz, $src)); if ($index == 0) { $index = 1; } FilmVars::$run_index = $index; FilmVars::$run_wait = 2; } } FilmVars::$run_prevclock = $prevclock; FilmVars::$run_result = $result; FilmVars::$run_phase = 1; FilmVars::$run_yielded = false; if ($result != 0) { $bf->batchframes = s16($bf->batchframes - 1); if ($bf->batchframes == 0) { // the wait is done by the next call (see above) $bf->result = 0; FilmVars::$run_pending = FilmVars::$run_wait != 0; FilmVars::$run_active = false; return; } if ($bf->batchframes < 0) { $bf->batchframes = s16($bf->batchframes + 1); } } } // Pacing (the C sleeps here), and one film frame per VM frame at most. if (film_run_waiting() || (!FilmVars::$run_yielded && FilmVars::$run_result != 0)) { film_yield(); } FilmVars::$run_phase = 0; if (FilmVars::$run_result == 0) { // S512 data exhausted: sys_render still has to draw the last frame, then ends the film. if ($bf->type == FilmConst::eAlisVideoS512 || $bf->type == FilmConst::eAlisVideoHAM6) { FilmVars::$g_s512_ending = 1; } break; } } FilmVars::$run_active = false; FilmVars::$run_pending = false; if ($bf->sfp !== null) { fli_stream_rewind(); // window mode: addr2 may be stale after compaction } else { $bf->addr1 = $bf->addr2; } $bf->result = -0x7ffc;}// ---------------------------------------------------------------------------------------------// sys_render() part of sys_sdl2.c: HAM6 / Spectrum 512 film frames (and the 3DO film frame)// ---------------------------------------------------------------------------------------------/** * C sys_render(): when a film of the Amiga (HAM6) or Atari ST (Spectrum 512) versions is up, the screen is the * film buffer converted to RGB, not the 8-bit frame. Returns that frame as a 24-bit BMP, null otherwise. * PORT: also returns the last 3DO film frame while film3do_run() plays (the C shows it through image.rgbphysic). */function film_render_rgb(): ?string{ film_check_boot(); if (FilmVars::$f3_bmp !== null) { return FilmVars::$f3_bmp; } $type = FilmVars::$bfilm->type; if ($type != FilmConst::eAlisVideoHAM6 && $type != FilmConst::eAlisVideoS512) { return null; } if (Host::$pixelbuf->rgb || FilmVars::$pvgalogic === null || FilmVars::$vgalogic_df === null) { return null; } $w = Host::$pixelbuf->w; $h = Host::$pixelbuf->h; if ($w <= 0 || $h <= 0) { return null; } $data = $type == FilmConst::eAlisVideoHAM6 ? film_render_ham6($w, $h) : film_render_s512($w, $h); return sys_bmp_header($w, $h, 24, strlen($data)) . $data;}/** Amiga HAM bitplanes (6 planes of w*h/8 bytes at vgalogic_df + 0xa0): BGR rows padded to 4 bytes. */function film_render_ham6(int $w, int $h): string{ $buf = FilmVars::$pvgalogic; $bitmap = FilmVars::$vgalogic_df + 0xa0; $ham_pal = FilmVars::$bfilm->ham_pal; $planesize = ($w * $h) >> 3; $need = $bitmap + 6 * $planesize; if (strlen($buf) < $need) { $buf .= str_repeat("\0", $need - strlen($buf)); } $pad = str_repeat("\0", (4 - ($w * 3) % 4) % 4); $r = 0; $g = 0; $b = 0; $c = $bitmap; $out = []; $bpr = $w >> 3; for ($y = 0; $y < $h; $y++) { $line = ''; for ($x = 0; $x < $bpr; $x++, $c++) { $p0 = ord($buf[$c]); $p1 = ord($buf[$c + $planesize]); $p2 = ord($buf[$c + 2 * $planesize]); $p3 = ord($buf[$c + 3 * $planesize]); $p4 = ord($buf[$c + 4 * $planesize]); $p5 = ord($buf[$c + 5 * $planesize]); for ($bit = 7; $bit >= 0; $bit--) { $index = ((($p0 >> $bit) & 1) | ((($p1 >> $bit) & 1) << 1) | ((($p2 >> $bit) & 1) << 2) | ((($p3 >> $bit) & 1) << 3)) << 2; $control = (($p4 >> $bit) & 1) | ((($p5 >> $bit) & 1) << 1); switch ($control) { case 0: $e = $ham_pal[$index >> 2]; $r = $e[0]; $g = $e[1]; $b = $e[2]; break; case 1: $b = ($index << 2) & 0xff; break; case 2: $r = ($index << 2) & 0xff; break; case 3: $g = ($index << 2) & 0xff; break; } $line .= chr($b) . chr($g) . chr($r); } } $out[] = $line . $pad; } return implode('', $out);}/** Atari ST Spectrum 512 bitplanes (interleaved, 160 bytes per line) + 48 colours per line. */function film_render_s512(int $w, int $h): string{ $buf = FilmVars::$pvgalogic; $df = FilmVars::$vgalogic_df; $bitmap = $df + 0xa0; $need = $df + 32000 + 32 + $h * 96 + 32; if (strlen($buf) < $need) { $buf .= str_repeat("\0", $need - strlen($buf)); } $pad = str_repeat("\0", (4 - ($w * 3) % 4) % 4); // the 16-bit colours are kept as their two memory bytes (rawcolor[0], rawcolor[1] of the C) $curpal = []; for ($k = 0; $k < 16; $k++) { $curpal[$k] = [ord($buf[$df + 32000 + 2 * $k]), ord($buf[$df + 32000 + 2 * $k + 1])]; } $palette = $df + 32000 + 32; $out = []; $at = 0; for ($y = 0; $y < $h; $y++, $palette += 32) { $line = ''; foreach ([[408, 0, 10], [510, 1, 20]] as [$palcntr, $half, $xend]) { if ($half) { $palette += 32; } for ($x = $half ? 10 : 0; $x < $xend; $x++, $at += 8) { for ($i = $at; $i < $at + 2; $i++) { $b0 = ord($buf[$bitmap + $i]); $b1 = ord($buf[$bitmap + $i + 2]); $b2 = ord($buf[$bitmap + $i + 4]); $b3 = ord($buf[$bitmap + $i + 6]); for ($rot = 7; $rot >= 0; $rot--, $palcntr += 102) { $palidx = $palcntr >> 10; $po = $palette + 2 * $palidx; $curpal[$palidx] = [ord($buf[$po]), ord($buf[$po + 1])]; $raw = $curpal[(($b0 >> $rot) & 1) | ((($b1 >> $rot) & 1) << 1) | ((($b2 >> $rot) & 1) << 2) | ((($b3 >> $rot) & 1) << 3)]; $c = ((($raw[0] & 7) << 5) << 16) + ((($raw[1] >> 4) << 5) << 8) + (($raw[1] & 7) << 5); $line .= chr($c & 0xff) . chr(($c >> 8) & 0xff) . chr(($c >> 16) & 0xff); } } } } $palette += 32; for ($k = 0; $k < 16; $k++) { $curpal[$k] = [ord($buf[$palette + 2 * $k]), ord($buf[$palette + 2 * $k + 1])]; } $out[] = $line . $pad; } return implode('', $out);}// ---------------------------------------------------------------------------------------------// Save state (the FLI/FLC video part of alis_save_state / alis_load_state of alis.c)// ---------------------------------------------------------------------------------------------/** The film state for alis_save_state(). PORT: the film bytes are not saved, film_load_state() reloads them. */function film_save_state(): array{ $bf = clone FilmVars::$bfilm; $stream_off = null; if ($bf->sfp !== null) { // file offset of addr1: what is read minus what is left in the window after addr1 $stream_off = $bf->sfile_size - $bf->sremain - (($bf->sfill ?? 0) - ($bf->addr1 ?? 0)); } $bf->sfp = null; return [ 'bfilm' => $bf, 'src' => FilmVars::$src, 'stream_off' => $stream_off, 'fls_drawing' => FilmVars::$fls_drawing, 'fls_pallines' => FilmVars::$fls_pallines, 'fls_state' => FilmVars::$fls_state, 'pvgalogic' => FilmVars::$pvgalogic, 'vgalogic' => FilmVars::$vgalogic, 'vgalogic_df' => FilmVars::$vgalogic_df, 'vgalogic_sz' => FilmVars::$vgalogic_sz, 'endframe' => FilmVars::$endframe, ];}function film_load_state(?array $st): void{ film_check_boot(); if (FilmVars::$bfilm->sfp !== null) { fclose(FilmVars::$bfilm->sfp); } FilmVars::$run_active = false; FilmVars::$f3 = null; FilmVars::$f3_bmp = null; if ($st === null || !($st['bfilm'] ?? null) instanceof sFLICData) { film_reset(); FilmVars::$data = ''; FilmVars::$src = null; vgalogic_free(); return; } $bf = $st['bfilm']; FilmVars::$bfilm = $bf; FilmVars::$src = $st['src']; FilmVars::$data = ''; // Streaming-film state (file handle, window buffer): the C clears it; the port reopens the file at addr1. $bf->sfp = null; $streamed = $bf->sbuf !== null; $bf->sbuf = $bf->sfill = null; $bf->sbuf_size = $bf->sremain = $bf->sfile_size = 0; $src = FilmVars::$src; if ($src !== null && $src[0] === 'mem') { film_set_data(substr(Alis::$mem, $src[1], $src[2])); } elseif ($src !== null && $src[0] === 'file') { $fp = sys_fopen($src[1], 'rb'); if ($fp !== null) { $size = (int) (fstat($fp)['size'] ?? 0); if ($streamed && $st['stream_off'] !== null && fli_stream_open($fp, $size)) { $off = \min(\max(0, (int) $st['stream_off']), $size); fseek($fp, $off); $bf->sremain = $size - $off; $bf->addr1 = $bf->addr2 = $bf->endptr = $bf->delptr = 0; } else { film_set_data((string) stream_get_contents($fp)); fclose($fp); } } } FilmVars::$fls_drawing = $st['fls_drawing']; FilmVars::$fls_pallines = $st['fls_pallines']; FilmVars::$fls_state = $st['fls_state']; if ($st['pvgalogic'] !== null) { FilmVars::$pvgalogic = $st['pvgalogic']; FilmVars::$vgalogic_sz = $st['vgalogic_sz']; FilmVars::$vgalogic = $st['vgalogic']; FilmVars::$vgalogic_df = $st['vgalogic_df']; } else { vgalogic_free(); } FilmVars::$endframe = $st['endframe'];}