# SPDX-License-Identifier: GPL-3.0-or-later # First written, by alewman, as megadrive-python's MIT tests/test_blastem_events.py # (to 2026-11-25), moved here on 2026-11-26 with the decoder; it keeps that MIT # permission (../../../notices/MIT-emulator-family.txt). """The decoder, on logs built here so nothing has to be fetched. BlastEm is a detector: these check that the *format* is decoded, not that anything it says is right. Runs under pytest or alone: ``python3 -I tests/test_decoder.py``. """ from __future__ import annotations import importlib.util import itertools import sys import zlib from pathlib import Path _spec = importlib.util.spec_from_file_location( "blastem_events_run", Path(__file__).resolve().parents[1] / "run.py" ) be = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(be) def _log(events: bytes, *, name: bytes = b"TEST", video: int = 0) -> bytes: """A whole log: the magic, the version, the uncompressed start block, then zlib.""" head = b"BLSTEL" + b"\x02\x00" + bytes([1, video, len(name)]) + name return head + zlib.compress(events) def _short(kind: int, delta: int) -> bytes: """The one-byte header: type in the high nibble, delta - 16 in the low.""" assert 16 <= delta < 32 return bytes([kind << 4 | (delta - 16)]) def _events(data: bytes): return list(be.Decoder(data)) def _frame_of(decoder, cycle: int) -> int: return cycle // decoder.frame_cycles def test_the_header_is_read(): decoder = be.Decoder(_log(b"", name=b"EARTHION", video=1)) assert decoder.name == "EARTHION" assert decoder.video_std == 1 assert decoder.frame_cycles == 313 * 3420 # PAL: a cycle is a master clock assert list(decoder) == [] def test_a_short_header_carries_type_and_delta(): body = _short(be.VDP_REG, 20) + bytes([12, 0x81]) ((t, name, fields),) = _events(_log(body)) assert name == "vdp-reg" assert (t, fields["register"], fields["value"]) == (20, 12, 0x81) def test_a_three_byte_header_carries_a_sixteen_bit_delta(): body = bytes([0xE0 | be.VDP_REG]) + (5000).to_bytes(2, "big") + bytes([1, 0x74]) ((t, _, fields),) = _events(_log(body)) assert t == 5000 assert (fields["register"], fields["value"]) == (1, 0x74) def test_a_four_byte_header_carries_a_signed_twenty_four_bit_delta(): body = bytes([0xF0 | be.VDP_REG, 0x01]) + (0x0000).to_bytes(2, "big") + bytes([0, 4]) ((t, _, _),) = _events(_log(body)) assert t == 0x10000 # A negative delta is sign-extended rather than read as a huge positive one. body = bytes([0xF0 | be.VDP_REG, 0xFF]) + (0xFFFF).to_bytes(2, "big") + bytes([0, 4]) decoder = be.Decoder(_log(body)) ((t, _, _),) = list(decoder) assert t == -1 # absolute time follows the delta assert decoder.raw == 0xFFFFFFFF # the counter BlastEm holds wraps def test_a_multi_header_repeats_the_event_with_its_own_payload(): # MULTI says the next event's type and delta repeat; each repetition still # carries its own payload bytes. body = bytes([be.MULTI << 4 | 2]) + _short(be.VDP_REG, 16) body += bytes([15, 0x02]) + bytes([15, 0x03]) + bytes([15, 0x04]) events = _events(_log(body)) assert [f["value"] for _, _, f in events] == [0x02, 0x03, 0x04] assert [t for t, _, _ in events] == [16, 32, 48] # the delta repeats too def test_vram_byte_addresses_are_carried_as_deltas(): body = _short(be.VDP_REG, 16) + bytes([15, 2]) body += _short(be.VRAM_BYTE, 16) + (0x1000).to_bytes(2, "big") + bytes([0xAA]) body += _short(be.VRAM_BYTE_ONE, 16) + bytes([0xBB]) body += _short(be.VRAM_BYTE_AUTO, 16) + bytes([0xCC]) body += _short(be.VRAM_BYTE_DELTA, 16) + bytes([0x10, 0xDD]) events = _events(_log(body))[1:] assert [f["address"] for _, _, f in events] == [0x1000, 0x1001, 0x1003, 0x1013] assert [f["value"] for _, _, f in events] == [0xAA, 0xBB, 0xCC, 0xDD] def test_an_auto_step_follows_register_fifteen(): """BlastEm logs the auto-increment byte event when a write lands register 15's value past the last one, whatever that value is; 2 was once assumed and is not the only one.""" body = _short(be.VDP_REG, 16) + bytes([15, 0x80]) body += _short(be.VRAM_BYTE, 16) + (0x1000).to_bytes(2, "big") + bytes([0xAA]) body += _short(be.VRAM_BYTE_AUTO, 16) + bytes([0xBB]) body += _short(be.VDP_REG, 16) + bytes([15, 0x40]) body += _short(be.VRAM_BYTE_AUTO, 16) + bytes([0xCC]) events = [e for e in _events(_log(body)) if e[1] != "vdp-reg"] assert [f["address"] for _, _, f in events] == [0x1000, 0x1080, 0x10C0] def test_word_addresses_are_carried_as_deltas_too(): body = _short(be.VRAM_WORD, 16) + bytes([0x01]) + (0x2000).to_bytes(2, "big") body += (0x1234).to_bytes(2, "big") body += _short(be.VRAM_WORD_DELTA, 16) + bytes([0x08]) + (0x5678).to_bytes(2, "big") events = _events(_log(body)) assert [f["address"] for _, _, f in events] == [0x12000, 0x12008] assert [f["value"] for _, _, f in events] == [0x1234, 0x5678] def test_a_frame_is_taken_from_the_cycle_and_not_from_flush(): # The flush event is an output-buffer flush; its count lands near the frame count, # which is what made it look like a frame marker. t // frame_mclk is the honest one. decoder = be.Decoder(_log(b"", video=0)) assert _frame_of(decoder, 0) == 0 assert _frame_of(decoder, decoder.frame_cycles - 1) == 0 assert _frame_of(decoder, decoder.frame_cycles) == 1 assert decoder.frame_cycles == 262 * 3420 # NTSC def test_register_writes_fall_in_their_frames(): frame = be.FRAME_CYCLES[0] body = bytes([0xE0 | be.VDP_REG]) + (20).to_bytes(2, "big") + bytes([0, 0x04]) body += bytes([0xF0 | be.VDP_REG, frame >> 16]) body += (frame & 0xFFFF).to_bytes(2, "big") + bytes([1, 0x74]) decoder = be.Decoder(_log(body)) grouped = {} for t, name, f in decoder: if name == "vdp-reg": grouped.setdefault(_frame_of(decoder, t), []).append((f["register"], f["value"])) assert grouped == {0: [(0, 0x04)], 1: [(1, 0x74)]} def test_a_file_that_is_not_a_log_is_refused(): try: be.Decoder(b"not a blastem log at all") except ValueError as exc: assert "BLSTEL" in str(exc) else: raise AssertionError("a file without the magic was decoded") def test_the_cycle_counter_is_masked_to_thirty_two_bits(): # BlastEm's counter is 32 bits and wraps. Python's unbounded integers do not, # which is why it has to be masked here. body = bytes([0xF0 | be.VDP_REG, 0xFF]) + (0xFFF0).to_bytes(2, "big") + bytes([0, 4]) decoder = be.Decoder(_log(body)) ((t, _, _),) = list(decoder) assert t == -16 # absolute time follows the delta assert decoder.raw == 0xFFFFFFF0 # the wrapped counter does not def test_an_adjust_deducts_from_the_counter_and_absolute_time_keeps_it(): # The adjust event is how BlastEm stops its 32-bit counter overflowing: it deducts # a large amount. Real time does not go backwards, so t keeps rising across it. A # 12,000-frame Overdrive 2 log read without this appears to stop at frame 4,008. deduction = 4_278_391_830 body = bytes([0xE0 | be.VDP_REG]) + (1000).to_bytes(2, "big") + bytes([0, 4]) body += bytes([0xE0 | be.ADJUST]) + (500).to_bytes(2, "big") body += deduction.to_bytes(4, "big") body += bytes([0xE0 | be.VDP_REG]) + (250).to_bytes(2, "big") + bytes([1, 0x74]) events = _events(_log(body)) assert [n for _, n, _ in events] == ["vdp-reg", "adjust", "vdp-reg"] assert events[1][2] == {"deduction": deduction} # Absolute time is monotonic across the adjust: 1000, then 1500, then 1750. assert [t for t, _, _ in events] == [1000, 1500, 1750] def test_absolute_time_survives_a_wrap_of_the_raw_counter(): # A delta is at most 24 bits, so the counter can only reach 2**32 by accumulating. # Once it wraps, the counter BlastEm holds starts again from a small number while # absolute time keeps climbing -- which is the whole point of keeping both. step = 0x7FFFF0 count = (1 << 32) // step + 2 body = b"" for _ in range(count): body += bytes([0xF0 | be.VDP_REG, step >> 16]) body += (step & 0xFFFF).to_bytes(2, "big") + bytes([0, 4]) decoder = be.Decoder(_log(body)) events = list(decoder) assert len(events) == count assert events[-1][0] == step * count # absolute time never wraps assert events[-1][0] > 1 << 32 assert decoder.raw == (step * count) & 0xFFFFFFFF # the counter does assert decoder.raw < 1 << 32 assert all(b[0] > a[0] for a, b in itertools.pairwise(events)) def test_intram_names_its_memory(): body = _short(be.VDP_INTRAM, 16) + bytes([0x06, 0x0E, 0xEE]) # CRAM byte address 6 body += _short(be.VDP_INTRAM, 16) + bytes([128 + 5, 0x07, 0xFF]) # VSRAM word 5 events = _events(_log(body)) assert [f for _, _, f in events] == [ {"memory": "cram", "index": 3, "value": 0x0EEE}, {"memory": "vsram", "index": 5, "value": 0x07FF}, ] if __name__ == "__main__": tests = [(n, f) for n, f in sorted(globals().items()) if n.startswith("test_")] for name, test in tests: test() print(f"{len(tests)} passed")