# SPDX-License-Identifier: MIT AND ISC """The CD-ROM decoder: a Sanyo LC8951 with its 16 KB buffer, and the gate array's transfer of buffer data to the five destinations. Sources: - Sanyo, *LC8950 / LC8951 Design Manual* (``reference/docs/datasheets``, text extracted from the scan; cited "LC8951 §N"): the register map during reads and writes (§10, Table 7), IFSTAT and IFCTRL (§11.3: active-low status bits, "Bit 4 is unused and always returns a 1"; DTEI cleared by writing DTACK; DECI cleared by reading STAT3), DBC as a 12-bit byte counter (§11.4), and the register address AR incrementing after each access. DOC. - KRIKzz, forum t=3166 (2020; prose of his tests on a CDX and a Mega-CD 2): "RS+AR pair acts as internal 5-bit address register ... RS=0 means that you access to regs 0-15, RS=1 for regs 16-31. Regs 16-31 have no any effect and returns 0xff if read them. Gate array reg 0x8005 also actually show 5bit value." DOC (community, hardware findings). Mike Pavone in the same thread reports that a Wondermega M1, a Sega CD 2 (LC89515) and a LaserActive fail the CDC REGS row with 01: CDC chips differ by model. - Sega's hardware manual, p.26-27 ($FF8004 EDT/DSR/DD, $FF800A in 8-byte units) (DOC). - ares 9408cb4 (``cdc.cpp``, ``cdc-transfer.cpp``; ISC, notice in NOTICE): what the decoder writes for each sector (header and user data from the block pointer, the 12 sync bytes after them), the DMA pace (a word every 6 sub clocks), the host register's $FFFF while no data is ready. OBSERVED. The decoder is error-free: every block is reported correct. """ from __future__ import annotations from typing import TYPE_CHECKING from .wiring import unplugged if TYPE_CHECKING: from .megacd import MegaCD BUFFER_SIZE = 0x4000 #: Sub CPU clocks a DMA word takes, by destination. Read off the MiSTer repository's #: SignalTap captures of a real Mega-CD (``docs/mcd logs``; pictures, hardware #: recordings): with DD=5 (``dma_prgram_continue.PNG``) and DD=7 (``dma_wordram.jpg``) the #: gate array strobes the LC8951's host read (HRD) once every 5 sub clocks, one byte each, #: so 10 clocks a word; with DD=4 (``dma_pcm_continue.PNG``) once every 20 (PCM DMA moves #: bytes, so this one is a byte's period). #: MEASURED (third-party capture of real hardware; the periods are read off the pictures #: to a clock, the phase against the sub CPU's own accesses is not modelled). ares uses 6 #: for every destination (OBSERVED). DMA_CLOCKS = {4: 20, 5: 10, 7: 10} #: Sub CPU clocks a block takes at single speed, 1/75 s (ECMA-130: 75 sectors a second). BLOCK_CLOCKS = 12_500_000 // 75 #: DD2-0 (p.26). MAIN_READ, SUB_READ, PCM_DMA, PRG_DMA, WORD_DMA = 2, 3, 4, 5, 7 def _bcd(value: int) -> int: return ((value // 10) << 4) | (value % 10) class CDC: #: Class default so that a machine saved before inserted syncs existed loads. since_block = 0 #: Sub clocks left of the decoder interrupt's pulse (and a default for old states). deci_clocks = 0 def __init__(self) -> None: self.request = unplugged # the gate array's INT5, set by the device self.device: MegaCD | None = None self.ram = bytearray(BUFFER_SIZE) self.reset_chip() #: The gate array's side: DD2-0, EDT, DSR, the DMA address (p.26-27). self.destination = 0 self.edt = 0 self.dsr = 0 self.dma_address = 0 self.dma_clocks = 0 self.host_word = 0 self._host_last = False #: Sub clocks since the decoder last saw a block (from the drive or inserted). self.since_block = 0 def attach(self, device: MegaCD) -> None: self.device = device def reset_chip(self) -> None: """The state after RESET (register 15 written; LC8951 §11): everything idle.""" self.address = 0 # AR, five bits with RS (KRIKzz) self.command = [] # COMIN FIFO (unused by the drive here) # IFCTRL self.ifctrl = 0 # Interrupt flags, active state (1 = pending). self.cmdi = 0 self.dtei = 0 self.deci = 0 self.deci_clocks = 0 self.dtbsy = 0 # data transfer busy self.dten = 0 # data transfer enabled (in progress) self.stbsy = 0 self.sten = 0 self.dbc = 0 # DBCL/DBCH, 12 bits self.dac = 0 # DACL/DACH, the transfer's source address in the buffer self.wa = 0 # WAL/WAH, the decoder's write address self.pt = 0 # PTL/PTH, the block pointer self.ctrl0 = 0 self.ctrl1 = 0 self.ctrl2 = 0 self.head = bytes(4) self.valid = 0 # the decoder has a block (STAT3 bit 7 reads its inverse) self.transferring = False self.int_active = False self._update_line() # -- interrupts ----------------------------------------------------------- def _update_line(self) -> None: """The LC8951's INT output is active while an enabled flag is set (IFCTRL bits 7-5: CMDIEN, DTEIEN, DECIEN; LC8951 §11.3; DOC). The gate array turns it into INT5 on its leading edge, a request the acknowledge clears: mcd-verificator's CDC INIT row handles INT5 without clearing the CDC's flag and passes on hardware only if the request does not repeat (TEST ROM; FITTED). ares raises it only on a change too (OBSERVED).""" ifctrl = self.ifctrl active = bool( (self.cmdi and ifctrl & 0x80) or (self.dtei and ifctrl & 0x40) or (self.deci and ifctrl & 0x20) ) if active and not self.int_active: self.request(5) self.int_active = active def _new_block_edge(self) -> None: """A decoded block starts the decoder interrupt, a pulse: the INT pin is held low "About 2750" us when none of WRRQ, PRQ and QRQ (CTRL0 bits 2-0) is set, "About 1800" in mode 1 or mode 2 form 1 and "About 1500" in mode 2 form 2 (LC8951 design manual, appendix E, section 12.6, p.108, the LC8951's own figures), and "Decoder interrupts become inactive immediately after the STAT3 register is read, or when DECEN is set to 0" (§12.6, p.63). DOC. The pin is a level, active while any enabled flag is (§11.3), so a pulse that starts while an unacknowledged DTEI holds it brings no new INT5: mcd-verificator's CDC FLAGS row leaves DTEI set and fails with 34 when a later block interrupts anyway (TEST ROM). Before 2026-11-24 DECI stayed set until STAT3 was read and every block forced a new edge (HYPOTHESIS, then needed by CDC INIT, whose handler never reads STAT3: the pulse ending by itself serves it the same way).""" if self.ctrl0 & 0x07: mode, form = (self.ctrl1 >> 3) & 1, (self.ctrl1 >> 2) & 1 micro = 1500 if mode and form else 1800 else: micro = 2750 self.deci_clocks = micro * 25 // 2 # sub clocks at 12.5 MHz self._update_line() # -- the register file (sub CPU $FF8006, address in $FF8005) --------------------- def read_register(self) -> int: address = self.address value = self._read(address) # AR increments after an access; COMIN (0) does not move it (LC8951 §10); with # RS, five bits wrap from 31 to 0 (KRIKzz). DOC. if address: self.address = (address + 1) & 0x1F return value def _read(self, address: int) -> int: if address >= 16: return 0xFF # "Regs 16-31 ... returns 0xff" (KRIKzz). DOC. if address == 0: return 0xFF # COMIN, no command bytes (the drive sends none here) if address == 1: # IFSTAT, active low but bit 4 (LC8951 §11.3.1). DOC. return ( (0 if self.cmdi else 0x80) | (0 if self.dtei else 0x40) | (0 if self.deci else 0x20) | 0x10 | (0 if self.dtbsy else 0x08) | (0 if self.stbsy else 0x04) | (0 if self.dten else 0x02) | (0 if self.sten else 0x01) ) if address == 2: return self.dbc & 0xFF if address == 3: # DBCH: bits 3-0 the counter's high bits. Table 7 prints DTEI in bits 7-4; # read as IFSTAT's active-low DTEI they fail mcd-verificator's CDC REGS row # (0B), read as 0 they pass it (TEST ROM), as ares has them (OBSERVED). return (self.dbc >> 8) & 0xF if 4 <= address <= 7: return self.head[address - 4] if address == 8: return self.pt & 0xFF if address == 9: return self.pt >> 8 if address == 10: return self.wa & 0xFF if address == 11: return self.wa >> 8 if address == 12: # STAT0: CRCOK while the decoder is on, no errors (error-free decoder). return 0x80 if self.ctrl0 & 0x80 else 0 if address == 13: return 0 # STAT1: no header errors if address == 14: # STAT2: MODE and FORM as CTRL1 asked (bits 3, 2), FORM only with AUTORQ. mode = (self.ctrl1 >> 3) & 1 form = (self.ctrl1 >> 2) & 1 & (self.ctrl0 >> 4) return mode << 3 | form << 2 # STAT3: bit 7 VALST (0 = valid). Reading it clears DECI (LC8951 §11.3.1). DOC. value = 0 if self.valid else 0x80 self.deci = 0 self.deci_clocks = 0 self.valid = 0 self._update_line() return value def write_register(self, value: int) -> None: address = self.address self._write(address, value) if address: self.address = (address + 1) & 0x1F def _write(self, address: int, value: int) -> None: if address >= 16 or address == 0: return # SBOUT (status bytes to the host: unused) and the empty registers if address == 1: self.ifctrl = value if not value & 0x02: # DOUTEN off stops a transfer (LC8951 §11.3.2). DOC. self._stop_transfer() self._update_line() elif address == 2: self.dbc = (self.dbc & 0xF00) | value elif address == 3: self.dbc = (self.dbc & 0x0FF) | (value & 0xF) << 8 elif address == 4: self.dac = (self.dac & 0xFF00) | value elif address == 5: self.dac = (self.dac & 0x00FF) | value << 8 elif address == 6: self._start_transfer() # DTTRG elif address == 7: self.dtei = 0 # DTACK self._update_line() elif address == 8: self.wa = (self.wa & 0xFF00) | value elif address == 9: self.wa = (self.wa & 0x00FF) | value << 8 elif address == 10: self.ctrl0 = value if not value & 0x80 and self.deci: # DECEN off ends the decoder interrupt (§12.6, p.63). DOC. self.deci = 0 self.deci_clocks = 0 self._update_line() elif address == 11: self.ctrl1 = value elif address == 12: self.pt = (self.pt & 0xFF00) | value elif address == 13: self.pt = (self.pt & 0x00FF) | value << 8 elif address == 14: self.ctrl2 = value else: address_now = self.address self.reset_chip() # RESET (register 15) self.address = address_now # -- the decoder --------------------------------------------------------------- def decode(self, lba: int, sector: bytes) -> None: """A block from the drive (75 a second while it plays a data track). With DECEN (CTRL0 bit 7) the header is latched and DECI raised; with WRRQ (bit 2) the block goes into the buffer at WA and PT moves to it. Layout: ares, OBSERVED.""" self.since_block = 0 if not self.ctrl0 & 0x80: return if self.ctrl1 & 1: self.head = bytes(sector[16:20]) # SHDREN: the subheader else: self.head = bytes(sector[12:16]) self.valid = 1 self.deci = 1 if self.ctrl0 & 0x04: self.pt = (self.pt + 2352) & 0xFFFF self.wa = (self.wa + 2352) & 0xFFFF ram, at = self.ram, self.pt for i, byte in enumerate(sector[12:]): ram[(at + i) & 0x3FFF] = byte for i, byte in enumerate(sector[:12]): ram[(at + 2340 + i) & 0x3FFF] = byte self._new_block_edge() # -- the transfer (LC8951 §11.4-11.5; the gate array's DD, p.26) ------------------ def _start_transfer(self) -> None: if not self.ifctrl & 0x02: # DOUTEN return self.transferring = True self.dtbsy = 1 self.dten = 1 self.edt = 0 # DTTRG leaves DTEI as it is: only DTACK clears it (LC8951 §11.3; DOC). CDC # FLAGS starts a second DMA without writing DTACK and fails with 26 when that # DMA's end raises INT5 again (TEST ROM; ares clears it here, OBSERVED). self.dsr = 0 self.dma_clocks = 0 if self.destination in (MAIN_READ, SUB_READ): self._load_host_word() self._update_line() def _stop_transfer(self) -> None: self.transferring = False self.dtbsy = 0 self.dten = 0 self.dsr = 0 def _complete(self) -> None: """The counter ran out: EDT (p.26), DTEI (LC8951 §11.3.1).""" self._stop_transfer() self.edt = 1 self.dtei = 1 self._update_line() def _next_word(self) -> tuple[int, bool]: """The next word from the buffer and whether it was the last: DBC counts bytes less one (LC8951 §11.4; DOC). The gate array moves whole words, and a transfer of an odd number of bytes ends with the last whole word, its odd byte not moved: mcd-verificator's CDC DMA2 row sends 2,349 bytes to word RAM and fails with 04 when 1,175 words are written, gets past that step (to 12) with 1,174 (TEST ROM; the mechanism, the gate array waiting for a second byte that never comes, is a HYPOTHESIS).""" at = self.dac & 0x3FFE word = (self.ram[at] << 8) | self.ram[at + 1] self.dac = (self.dac + 2) & 0xFFFF self.dbc -= 2 last = self.dbc < 1 self.dbc &= 0xFFF return word, last def _load_host_word(self) -> None: """The next word into the gate array's host register (DSR). The last word leaving the CDC ends the transfer there and then -- EDT, "all the data has been transferred from the CDC" (p.26; DOC), and DTEI with INT5 -- while DSR stays set until the CPU reads it: mcd-verificator's CDC FLAGS row reads all but the last word of a main-CPU transfer and fails with ERROR 22 unless INT5 has come by then (TEST ROM).""" self.host_word, self._host_last = self._next_word() if self._host_last: self._complete() self.dsr = 1 def host_read(self, main: bool) -> int: """$A12008 / $FF8008: a word when DSR is set; DD selects which CPU (p.26-27, 58). Without data ready it reads $FFFF here (ares, OBSERVED). The other CPU's register shows the same latched word without taking it: mcd-verificator's CDC DMA3 row has the main CPU read $A12008 during a sub-CPU read (DD=3) and fails with 28 when it reads $FFFF (TEST ROM; that the read does not take the word is a HYPOTHESIS, the row's next step is the judge).""" wanted = MAIN_READ if main else SUB_READ if not self.dsr or self.destination not in (MAIN_READ, SUB_READ): return 0xFFFF if self.destination != wanted: return self.host_word word = self.host_word if self._host_last: self.dsr = 0 self._host_last = False else: self._load_host_word() return word def set_destination(self, value: int) -> None: """ "When data is written in DD2-DD0, the DMA circuit is reset (The DMA address is also reset.)"; EDT "is reset when the device destination is set" (p.26-27). DOC.""" self.destination = value self.edt = 0 self.dsr = 0 self.dma_address = 0 def set_dma_address(self, value: int) -> None: self.dma_address = value def _inserted_sync(self, clocks: int) -> None: """With SYIEN (CTRL1 bit 7) the LC8951 inserts a block sync itself when none is detected at the block boundary (LC8951 design manual, CTRL1: "Internal Block-Sync Insertion Enable", and Figure 9; DOC), so the decoder goes on reporting a block every 1/75 s with no data coming in. That it does so with the drive stopped (the byte clock from the drive's DSP running on) is a HYPOTHESIS that mcd-verificator's CDC FLAGS row asks for: it turns DECEN, SYIEN and DECIEN on with the drive stopped, waits for INT5 and fails with 30 when none comes (TEST ROM). The inserted block raises DECI only; nothing is written.""" self.since_block += clocks if self.since_block < BLOCK_CLOCKS: return self.since_block -= BLOCK_CLOCKS if self.ctrl0 & 0x80 and self.ctrl1 & 0x80: self.valid = 1 self.deci = 1 self._new_block_edge() def run(self, clocks: int) -> None: if self.deci_clocks: self.deci_clocks -= clocks if self.deci_clocks <= 0: self.deci_clocks = 0 self.deci = 0 self._update_line() self._inserted_sync(clocks) if not self.transferring or self.destination not in (PCM_DMA, PRG_DMA, WORD_DMA): return self.dma_clocks += clocks device = self.device period = DMA_CLOCKS[self.destination] while self.transferring and self.dma_clocks >= period: destination = self.destination if destination == WORD_DMA and device.cdc_dma_word_ram_held(): # 2M word RAM the main CPU owns: the DMA waits, as the sub CPU does # (megacd.py, "The hang"), until the RAM is the sub CPU's again. # mcd-verificator's CDC DMA3 row hands the RAM back to the main CPU just # after starting a word-RAM DMA and fails with 44 when the transfer ends # and INT5 comes anyway (TEST ROM); ares holds the DMA the same way # (OBSERVED). self.dma_clocks = period return if destination == PRG_DMA and device.cdc_dma_prg_held(): # PRG RAM switched to the main CPU (switch A, "By setting SBRQ=1 or # SRES=0 ... set to the MAIN side"; on the sub side "the REFRESH or DMA # can access the PRG-RAM", p.6-7; DOC): the DMA waits. CDC DMA3 takes # the bus during a PRG-RAM DMA and fails with 48 when INT5 has come by # the time it lets go (TEST ROM). self.dma_clocks = period return self.dma_clocks -= period if destination == PCM_DMA: # PCM DMA moves one byte at a time (p.26: DSR "For PCM DMA it sets per # byte received"; the capture's one HRD a byte), so an odd count ends # with its last byte: CDC DMA2 sends 9 bytes to wave RAM and fails with # 12 when 8 arrive (TEST ROM). The address in $FF800A is the sub CPU's: # PCM sits on odd bytes, so a byte of wave RAM is two addresses (p.15, # p.27 "the limit is A12"; ares adds 4 a word, OBSERVED). at = self.dac & 0x3FFF self.dac = (self.dac + 1) & 0xFFFF self.dbc -= 1 last = self.dbc < 0 self.dbc &= 0xFFF device.cdc_dma_pcm(0x1000 | ((self.dma_address & 0x1FFF) >> 1), self.ram[at]) self.dma_address = (self.dma_address + 2) & 0x1FFF if last: self._complete() continue word, last = self._next_word() if destination == PRG_DMA: at = self.dma_address & 0x7FFFE # The write protect does not stop the DMA: CDC DMA3 sets WP=$FF, sends a # sector to $9000 and fails with 56 when it is kept out (TEST ROM). The # manual words the protect for the sub CPU only (p.14, p.57); ares # protects DMA writes too (OBSERVED, overruled by the row). device.cdc_dma_prg(at, word) self.dma_address = (at + 2) & 0x7FFFF else: self.dma_address = device.cdc_dma_word_ram(self.dma_address, word) if last: self._complete() __all__ = ["BUFFER_SIZE", "CDC"]